@yuriai/web 0.2.20-beta.3 → 0.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/{AgentAvatar-D5KPQI1N.js → AgentAvatar-MK9jNcwx.js} +1 -1
  3. package/dist/assets/{AssistantView-huAUB-2Y.js → AssistantView-CVf9ta92.js} +3 -3
  4. package/dist/assets/{DiagramView-DWV04Xws.js → DiagramView-ys2UVvx1.js} +1 -1
  5. package/dist/assets/{FadeInOnReveal-CdoLG8fY.js → FadeInOnReveal-B1g8C4P7.js} +1 -1
  6. package/dist/assets/{GuiPluginSurface-DhD8BqvL.js → GuiPluginSurface-C1KQZUmj.js} +1 -1
  7. package/dist/assets/{GuiPluginWindow-ezsy5l_y.js → GuiPluginWindow-D4TIvZDn.js} +1 -1
  8. package/dist/assets/{Icon-DvqOB4Dx.js → Icon-C93bLV0e.js} +1 -1
  9. package/dist/assets/{ImageLoadingPlaceholder-BVlgaa2r.js → ImageLoadingPlaceholder-DM2ifWd8.js} +1 -1
  10. package/dist/assets/{LoadingImage-BSG8jmn5.js → LoadingImage-BoaGSpZ_.js} +1 -1
  11. package/dist/assets/MarkdownRenderer-B8LWUc6A.js +2 -0
  12. package/dist/assets/{MarkdownRendererImpl-CH8TUMKZ.js → MarkdownRendererImpl-DL069I2q.js} +1 -1
  13. package/dist/assets/{MarkstreamRendererImpl-Bmz56IzM.js → MarkstreamRendererImpl-CwR_p-oQ.js} +1 -1
  14. package/dist/assets/{MobileDetailNavigation-kKHM_dU3.js → MobileDetailNavigation-C7Z7mVZV.js} +1 -1
  15. package/dist/assets/{MobileResizableSheet-jHNytoyX.js → MobileResizableSheet-ChrM2_er.js} +1 -1
  16. package/dist/assets/{MobileShareBridge-CSDivsPk.js → MobileShareBridge-DtXwoQtk.js} +1 -1
  17. package/dist/assets/MobileTabPageHeader-BT7U61qi.js +2 -0
  18. package/dist/assets/{MultiRunWindow-DbllgaJR.js → MultiRunWindow-CFWkmiwx.js} +1 -1
  19. package/dist/assets/{OnboardingScreen-DONIcirJ.js → OnboardingScreen-Bb3wmiKY.js} +1 -1
  20. package/dist/assets/{OverlayScrollbar-DB2eeXFh.js → OverlayScrollbar-DD6avzvO.js} +1 -1
  21. package/dist/assets/SettingsView-B4xkRLZ3.js +29 -0
  22. package/dist/assets/SettingsView-BRIvklfP.css +1 -0
  23. package/dist/assets/{SettingsWindow-BrrnHfnR.js → SettingsWindow-jF7nPmJG.js} +1 -1
  24. package/dist/assets/{TerminalView-8JYW5f-c.js → TerminalView-Cms4rfIE.js} +1 -1
  25. package/dist/assets/{ToolOutputDialog-DZO89hKv.js → ToolOutputDialog-CBSb39qy.js} +1 -1
  26. package/dist/assets/{YuriLogo-CYdRUurL.js → YuriLogo-CeZsIqiE.js} +1 -1
  27. package/dist/assets/{appThemeRegistry-Nb-sUfbK.js → appThemeRegistry-Bps27som.js} +1 -1
  28. package/dist/assets/{button-nola46HU.js → button--mt1oJ-H.js} +1 -1
  29. package/dist/assets/{capgoAdapter-CHeo9q51.js → capgoAdapter-ZBPKiKyL.js} +1 -1
  30. package/dist/assets/{collapsible-BQaMLh6O.js → collapsible-Dh2xZynB.js} +1 -1
  31. package/dist/assets/{diagram-COti_aKS.js → diagram-CrQbE7QP.js} +1 -1
  32. package/dist/assets/{dialog-B2CTTXwv.js → dialog-BG9W4FO9.js} +1 -1
  33. package/dist/assets/{dropdown-menu.styles-BzpQaok_.js → dropdown-menu.styles-BOP49Dw2.js} +1 -1
  34. package/dist/assets/es-CuWYQYZ1.js +15 -0
  35. package/dist/assets/{fileMentionTouchSelection-CXepBNtQ.js → fileMentionTouchSelection-m4Xsn0cx.js} +1 -1
  36. package/dist/assets/fr-yebDRPGw.js +13 -0
  37. package/dist/assets/{gitApi-B7AeNXrj.js → gitApi-C1pkEDXu.js} +1 -1
  38. package/dist/assets/{host-BCXyr41J.js → host-BqNFap4A.js} +1 -1
  39. package/dist/assets/{input-DGnhaqoc.js → input-BMUm4I0i.js} +1 -1
  40. package/dist/assets/{insertionBoundaries-Db0R1aBj.js → insertionBoundaries-WLpirs0A.js} +1 -1
  41. package/dist/assets/ja-f1wDEfxS.js +15 -0
  42. package/dist/assets/ko-n8CMb8k9.js +15 -0
  43. package/dist/assets/{main-DQ0F0yuL.js → main-CNmq04w8.js} +21 -21
  44. package/dist/assets/{main-d2AaD_PZ.js → main-djohnOii.js} +2 -2
  45. package/dist/assets/{markdownHeightCache-C_JI5qIR.js → markdownHeightCache-BWrnxGTO.js} +1 -1
  46. package/dist/assets/{mcpQueries-BgFj7wfO.js → mcpQueries-BfSiXImW.js} +1 -1
  47. package/dist/assets/{miniChat-BHdsTyJ3.js → miniChat-DXN8mcdi.js} +2 -2
  48. package/dist/assets/{mobile-BEhQq4tx.js → mobile--08sYbKy.js} +2 -2
  49. package/dist/assets/{mobileBackNavigation-s9RsXUUH.js → mobileBackNavigation-EIV61ZvG.js} +1 -1
  50. package/dist/assets/{multirun-BZsBsBAj.js → multirun-Dfuqt2Sd.js} +1 -1
  51. package/dist/assets/{native-config-BmrfOzkM.js → native-config-Cswl9jqU.js} +1 -1
  52. package/dist/assets/pl-BpveZ1bR.js +15 -0
  53. package/dist/assets/{projectMeta-BCGIXTbR.js → projectMeta-CuVxfoYb.js} +1 -1
  54. package/dist/assets/pt-BR-bq37AHb6.js +15 -0
  55. package/dist/assets/{readiness-BxT5OBkk.js → readiness-DDF6yf-o.js} +1 -1
  56. package/dist/assets/{renderElectronMiniChatApp-BbfF6SjM.js → renderElectronMiniChatApp-Cfs2xjgL.js} +2 -2
  57. package/dist/assets/{renderMobileApp-ulSQxT-l.js → renderMobileApp-B66uW5zc.js} +7 -7
  58. package/dist/assets/{runtimeConfig-BHRHZbwI.js → runtimeConfig-DTkP4z43.js} +1 -1
  59. package/dist/assets/runtimeEndpointReset-BMAP5ZCY.js +149 -0
  60. package/dist/assets/{scheduledTaskNavigation-CkBcoGV4.js → scheduledTaskNavigation-7slq1geN.js} +1 -1
  61. package/dist/assets/{sessionChangeSummary-CAU-06Bu.js → sessionChangeSummary-BYv_KUyn.js} +1 -1
  62. package/dist/assets/{sessionLookup-YvkfClst.js → sessionLookup-Cx0pE6yS.js} +1 -1
  63. package/dist/assets/{sortable-tabs-strip-pCvZjmMt.js → sortable-tabs-strip-D_efLXen.js} +1 -1
  64. package/dist/assets/{speechSettingsQueries-1LD5eEHK.js → speechSettingsQueries-BxHtdoOT.js} +1 -1
  65. package/dist/assets/src-DHHaXffU.css +2 -0
  66. package/dist/assets/store-CKBj6kYd.js +15 -0
  67. package/dist/assets/{textarea-DSHEMw8t.js → textarea-CNvFHvhC.js} +1 -1
  68. package/dist/assets/{tooltip-BwTvgqWG.js → tooltip-C-gdI2Am.js} +1 -1
  69. package/dist/assets/types-BHKyslK4.js +2 -0
  70. package/dist/assets/uk-Ds3imyqV.js +15 -0
  71. package/dist/assets/{useAppFontEffects-Cz9eoInx.js → useAppFontEffects-Ucq0gPN8.js} +5 -5
  72. package/dist/assets/{useDesktopWindowControlsLayout-HpOlTBoV.js → useDesktopWindowControlsLayout-BEscodj1.js} +1 -1
  73. package/dist/assets/{useEffectiveDirectory-DE-YccE8.js → useEffectiveDirectory-BWRQNoDF.js} +1 -1
  74. package/dist/assets/{useMobileNavigationStore-DPE5LVui.js → useMobileNavigationStore-DzkVc9H_.js} +12 -11
  75. package/dist/assets/{useWorkerHighlightedLines-o-elkNrd.js → useWorkerHighlightedLines-Dz6lLZ-1.js} +1 -1
  76. package/dist/assets/zh-CN-BNJ3ElZ9.js +15 -0
  77. package/dist/assets/{zh-TW-CtLsIcFb.js → zh-TW-C0jQloeH.js} +2 -2
  78. package/dist/index.html +6 -6
  79. package/dist/mini-chat.html +6 -6
  80. package/dist/mobile.html +6 -6
  81. package/package.json +1 -1
  82. package/server/lib/assistants/DOCUMENTATION.md +4 -4
  83. package/server/lib/assistants/contact-store.js +151 -17
  84. package/server/lib/assistants/contact-store.test.js +44 -2
  85. package/server/lib/assistants/contact-tools.js +43 -2
  86. package/server/lib/assistants/contact-tools.test.js +21 -0
  87. package/server/lib/assistants/harness.js +17 -8
  88. package/server/lib/assistants/harness.test.js +24 -8
  89. package/server/lib/assistants/service.js +64 -6
  90. package/server/lib/assistants/service.test.js +62 -19
  91. package/server/lib/assistants/summary.js +90 -0
  92. package/server/lib/assistants/summary.test.js +86 -0
  93. package/server/lib/llm/DOCUMENTATION.md +12 -2
  94. package/server/lib/llm/bridge-client.js +65 -16
  95. package/server/lib/llm/bridge-client.test.js +63 -2
  96. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  97. package/server/lib/opencode/npm-registry.js +106 -11
  98. package/server/lib/opencode/npm-registry.test.js +64 -0
  99. package/server/lib/opencode/plugin-routes.js +3 -1
  100. package/server/lib/opencode/plugin-routes.test.js +3 -3
  101. package/server/lib/quota/magpie.js +2 -2
  102. package/server/lib/small-model/DOCUMENTATION.md +2 -1
  103. package/dist/assets/MarkdownRenderer-BiRplAST.js +0 -2
  104. package/dist/assets/MobileTabPageHeader-BkWvNBtr.js +0 -2
  105. package/dist/assets/SettingsView-6D55BNjw.js +0 -26
  106. package/dist/assets/es-DklBd0ox.js +0 -15
  107. package/dist/assets/fr-CVUs46wM.js +0 -13
  108. package/dist/assets/ja-5reg09JK.js +0 -15
  109. package/dist/assets/ko-DZdC6ooz.js +0 -15
  110. package/dist/assets/pl-BerZSK-a.js +0 -15
  111. package/dist/assets/pt-BR-ydmV6U49.js +0 -15
  112. package/dist/assets/runtimeEndpointReset-H2W1kxcO.js +0 -149
  113. package/dist/assets/src-DGCTlpkW.css +0 -2
  114. package/dist/assets/store-ClIuNNU7.js +0 -15
  115. package/dist/assets/types-CiQgQf3s.js +0 -2
  116. package/dist/assets/uk-BnTevguX.js +0 -15
  117. package/dist/assets/zh-CN-DT6qIAPJ.js +0 -15
@@ -1,30 +1,79 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
- import { randomUUID } from 'node:crypto';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { OpenCode } from '@opencode/client';
7
7
  import { LlmBridge, LLM_BRIDGE_VERSION } from './bridge-contract.js';
8
8
 
9
+ const BRIDGE_PLUGIN_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bridge-plugin.bundle.js');
10
+
11
+ // Every directory activates one upstream Location that the shared service keeps
12
+ // alive. The directory is keyed by plugin content, so restarts and concurrent
13
+ // hosts running the same bundle reuse one Location instead of adding one each.
14
+ export async function prepareLlmBridgeDirectory({ pluginPath = BRIDGE_PLUGIN_PATH, root = os.tmpdir(), fsLike = fs } = {}) {
15
+ const code = await fsLike.readFile(pluginPath);
16
+ const digest = createHash('sha256').update(code).digest('hex').slice(0, 16);
17
+ const directory = path.join(root, `yuri-inference-${digest}`);
18
+ const plugins = path.join(directory, '.opencode', 'plugins');
19
+ const target = path.join(plugins, 'yuri-llm.js');
20
+ const current = await fsLike.readFile(target).catch(() => null);
21
+ if (current && current.equals(code)) return directory;
22
+ await fsLike.mkdir(plugins, { recursive: true });
23
+ // Another host may be loading the same file; replace it atomically.
24
+ const staging = `${target}.${process.pid}.${randomUUID()}.tmp`;
25
+ try {
26
+ await fsLike.writeFile(staging, code);
27
+ await fsLike.rename(staging, target);
28
+ } catch (error) {
29
+ await fsLike.rm(staging, { force: true });
30
+ throw error;
31
+ }
32
+ return directory;
33
+ }
34
+
35
+ /**
36
+ * Removes bridge directories left by earlier builds or by the former per-process
37
+ * temporary layout. A directory whose Location is still loaded upstream may be
38
+ * in use by another host, so it stays until the upstream idle sweep unloads it.
39
+ * Only failure to read the live inventory skips the whole pass.
40
+ */
41
+ export async function pruneStaleLlmBridgeDirectories({ client, keep, root = os.tmpdir(), fsLike = fs, signal }) {
42
+ const entries = await Promise.resolve().then(() => client.debug.location.list(signal ? { signal } : undefined)).catch(() => null);
43
+ if (!Array.isArray(entries)) return [];
44
+ const live = new Set(entries.map((entry) => entry?.directory && path.resolve(entry.directory)).filter(Boolean));
45
+ const names = await fsLike.readdir(root).catch(() => []);
46
+ const removed = [];
47
+ for (const name of names) {
48
+ if (!name.startsWith('yuri-inference-')) continue;
49
+ const directory = path.join(root, name);
50
+ if (directory === keep || live.has(directory)) continue;
51
+ const resolved = await fsLike.realpath(directory).catch(() => directory);
52
+ if (live.has(resolved)) continue;
53
+ await fsLike.rm(directory, { recursive: true, force: true }).then(() => removed.push(directory), () => undefined);
54
+ }
55
+ return removed;
56
+ }
57
+
9
58
  let directoryPromise;
10
- export async function ensureLlmBridgeDirectory() {
11
- if (!directoryPromise) directoryPromise = (async () => {
12
- const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-inference-'));
13
- try {
14
- const plugins = path.join(directory, '.opencode', 'plugins');
15
- await fs.mkdir(plugins, { recursive: true });
16
- const plugin = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bridge-plugin.bundle.js');
17
- await fs.copyFile(plugin, path.join(plugins, 'yuri-llm.js'));
18
- return directory;
19
- } catch (error) { await fs.rm(directory, { recursive: true, force: true }); throw error; }
20
- })().catch(error => { directoryPromise = undefined; throw error; });
21
- return directoryPromise;
59
+ let pruneStarted = false;
60
+ export async function ensureLlmBridgeDirectory({ client } = {}) {
61
+ if (!directoryPromise) directoryPromise = prepareLlmBridgeDirectory()
62
+ .catch(error => { directoryPromise = undefined; throw error; });
63
+ const directory = await directoryPromise;
64
+ if (client && !pruneStarted) {
65
+ pruneStarted = true;
66
+ // Cleanup is best effort and never delays inference.
67
+ void pruneStaleLlmBridgeDirectories({ client, keep: directory }).catch(() => undefined);
68
+ }
69
+ return directory;
22
70
  }
23
71
 
72
+ // The content-addressed directory may be shared with other hosts, so shutdown
73
+ // only forgets it and never deletes it.
24
74
  export async function stopLlmBridgeDirectory() {
25
- const pending = directoryPromise;
26
75
  directoryPromise = undefined;
27
- if (pending) await fs.rm(await pending, { recursive: true, force: true });
76
+ pruneStarted = false;
28
77
  }
29
78
 
30
79
  export async function generateCleanCompletion({ buildOpenCodeUrl, getOpenCodeAuthHeaders, clientFactory,
@@ -33,7 +82,7 @@ export async function generateCleanCompletion({ buildOpenCodeUrl, getOpenCodeAut
33
82
  }) {
34
83
  signal?.throwIfAborted();
35
84
  const client = clientFactory?.() ?? OpenCode.make({ baseUrl: buildOpenCodeUrl('/', '').replace(/\/$/, ''), headers: getOpenCodeAuthHeaders() });
36
- const directory = await ensureBridgeDirectory();
85
+ const directory = await ensureBridgeDirectory({ client });
37
86
  const options = { location: { directory }, signal };
38
87
  const rpc = client.rpc(LlmBridge);
39
88
  // Loading this isolated Location activates only its own plugin file, without global config writes.
@@ -1,5 +1,8 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import { generateCleanCompletion } from './bridge-client.js';
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { generateCleanCompletion, prepareLlmBridgeDirectory, pruneStaleLlmBridgeDirectories } from './bridge-client.js';
3
6
  import { LLM_BRIDGE_VERSION } from './bridge-contract.js';
4
7
 
5
8
  describe('external OpenCode inference bridge', () => {
@@ -32,4 +35,62 @@ describe('external OpenCode inference bridge', () => {
32
35
  expect(vi.getTimerCount()).toBe(0);
33
36
  } finally { vi.useRealTimers(); }
34
37
  });
38
+
39
+ it('passes the client to directory preparation so stale bridge cleanup can consult upstream', async () => {
40
+ const client = { plugin: { list: async () => [] }, rpc: () => ({ ready: async () => ({ version: LLM_BRIDGE_VERSION }), generate: async () => ({ text: '', toolCalls: [] }) }) };
41
+ const ensureBridgeDirectory = vi.fn(async () => '/isolated');
42
+ await generateCleanCompletion({ clientFactory: () => client, ensureBridgeDirectory });
43
+ expect(ensureBridgeDirectory).toHaveBeenCalledWith({ client });
44
+ });
45
+ });
46
+
47
+ describe('bridge directory lifecycle', () => {
48
+ const roots = [];
49
+ const makeRoot = async () => {
50
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'bridge-root-'));
51
+ roots.push(root);
52
+ return root;
53
+ };
54
+ afterEach(async () => {
55
+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
56
+ });
57
+
58
+ it('reuses one content-addressed directory across restarts and rewrites only changed plugins', async () => {
59
+ const root = await makeRoot();
60
+ const pluginPath = path.join(root, 'bundle.js');
61
+ await fs.writeFile(pluginPath, 'v1');
62
+ const first = await prepareLlmBridgeDirectory({ pluginPath, root });
63
+ const target = path.join(first, '.opencode', 'plugins', 'yuri-llm.js');
64
+ const { mtimeMs } = await fs.stat(target);
65
+ expect(await prepareLlmBridgeDirectory({ pluginPath, root })).toBe(first);
66
+ expect((await fs.stat(target)).mtimeMs).toBe(mtimeMs);
67
+ expect(await fs.readFile(target, 'utf8')).toBe('v1');
68
+
69
+ await fs.writeFile(pluginPath, 'v2');
70
+ const second = await prepareLlmBridgeDirectory({ pluginPath, root });
71
+ expect(second).not.toBe(first);
72
+ expect(path.basename(second)).toMatch(/^yuri-inference-[0-9a-f]{16}$/);
73
+ expect(await fs.readFile(path.join(second, '.opencode', 'plugins', 'yuri-llm.js'), 'utf8')).toBe('v2');
74
+ expect((await fs.readdir(path.join(second, '.opencode', 'plugins')))).toEqual(['yuri-llm.js']);
75
+ });
76
+
77
+ it('prunes stale bridge directories except the current and upstream-loaded ones', async () => {
78
+ const root = await makeRoot();
79
+ const make = async (name) => { const dir = path.join(root, name); await fs.mkdir(dir); return dir; };
80
+ const keep = await make('yuri-inference-current');
81
+ const loaded = await make('yuri-inference-loaded');
82
+ const stale = await make('yuri-inference-AbC123');
83
+ const unrelated = await make('other-dir');
84
+ const client = { debug: { location: { list: vi.fn(async () => [{ directory: loaded }]) } } };
85
+ expect(await pruneStaleLlmBridgeDirectories({ client, keep, root })).toEqual([stale]);
86
+ expect((await fs.readdir(root)).sort()).toEqual([path.basename(unrelated), path.basename(keep), path.basename(loaded)].sort());
87
+ });
88
+
89
+ it('skips pruning when the upstream inventory cannot be read', async () => {
90
+ const root = await makeRoot();
91
+ await fs.mkdir(path.join(root, 'yuri-inference-stale'));
92
+ const client = { debug: { location: { list: vi.fn(async () => { throw new Error('503'); }) } } };
93
+ expect(await pruneStaleLlmBridgeDirectories({ client, keep: '/none', root })).toEqual([]);
94
+ expect(await fs.readdir(root)).toEqual(['yuri-inference-stale']);
95
+ });
35
96
  });
@@ -70,6 +70,7 @@ This module provides OpenCode server integration utilities for the web server ru
70
70
  - `packages/web/server/lib/opencode/settings-normalization-runtime.js`: path/settings normalization and sanitization helpers runtime used by settings/routes/config wiring.
71
71
  - `packages/web/server/lib/opencode/theme-runtime.js`: custom theme JSON validation and theme directory loading runtime for settings utility routes.
72
72
  - `packages/web/server/lib/opencode/proxy.js`: OpenCode API/SSE forwarding and readiness-gate route registration.
73
+ - `npm-registry.js`: plugin package lookup used by `GET /api/config/plugins/registry`. It asks the user's own `npm view` first (run in the project directory, so scope registries, auth tokens and mirrors from `.npmrc` apply as they do for `npm install`) and falls back to a direct request to the public registry only when the CLI is unavailable; a CLI 404 is final. Results are cached per name and directory. The latest release's `magpie.icon` is returned as `icon` only when it is an `https://` URL or `data:image/` URI of at most ~1.5 MB (`sanitizePluginIcon`); nothing is fetched server-side and clients render it as an image.
73
74
  - `plugin-gui-response.js`: shared Web/Electron/VS Code code-only revision response owner for exact `GET /api/plugin/gui?id=…` (one nonempty id). The installed GUI client alias is official `@opencode/client@2.2.0`: HTTP returns `{ location, data: { code, revision, options } }`. Every call still reads the complete current upstream response through the existing auth/readiness/abort boundary; there is no Host bundle cache.
74
75
  - Request `X-Yuri-Gui-Revision: <lowercase SHA-256 hex of UTF-8 revision>` opts into code reuse. This header and HTTP condition/range headers are stripped before upstream so Yuri always requests a complete representation. Other query and request headers retain proxy semantics.
75
76
  - A valid upstream 200 JSON bundle (`code` string, nonempty `revision` string, `options` object) receives `X-Yuri-Gui-Revision` and `Cache-Control: private, no-store`. Matching tokens additionally receive `X-Yuri-Gui-Code: cached` and only `data.code` becomes `''`; current `options`, `revision`, location and other fields remain. Unmatched/ordinary calls preserve original body bytes. No 304 or Yuri ETag is generated. Upstream failure statuses/bodies remain failures; malformed successful bodies remain unchanged without a revision receipt.
@@ -1,3 +1,4 @@
1
+ import { execFile } from 'child_process';
1
2
  import fs from 'fs';
2
3
  import path from 'path';
3
4
  import { fileURLToPath } from 'url';
@@ -12,6 +13,7 @@ const NPM_REGISTRY_BASE = 'https://registry.npmjs.org';
12
13
  * @property {string|null} latest
13
14
  * @property {string[]} versions
14
15
  * @property {Record<string, string>} distTags
16
+ * @property {string} [icon] sanitized `magpie.icon` of the latest release
15
17
  *
16
18
  * @typedef {Object} NpmLookupError
17
19
  * @property {false} ok
@@ -79,13 +81,101 @@ function cacheResult(name, payload) {
79
81
  }
80
82
  }
81
83
 
84
+ const NPM_ICON_MAX_LENGTH = 3 << 19;
85
+
86
+ /**
87
+ * A package's own picture, as magpie reads `magpie.icon` from package.json:
88
+ * an https URL or a data:image URI, at most ~1.5 MB. Anything else is dropped.
89
+ * Nothing is fetched here; the client renders it as an image.
90
+ *
91
+ * @param {unknown} value
92
+ * @returns {string | undefined}
93
+ */
94
+ export function sanitizePluginIcon(value) {
95
+ const icon = typeof value === 'string' ? value.trim() : '';
96
+ return icon.length > 0 && icon.length <= NPM_ICON_MAX_LENGTH && /^(https:\/\/|data:image\/)/i.test(icon)
97
+ ? icon
98
+ : undefined;
99
+ }
100
+
101
+ const VALID_NPM_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
102
+ const NPM_CLI_TIMEOUT_MS = 15_000;
103
+
104
+ /**
105
+ * Ask the user's own npm CLI. It resolves `.npmrc` (per-scope `@scope:registry`,
106
+ * auth tokens, mirrors, proxies) exactly as `npm install` would, which a bare
107
+ * request to registry.npmjs.org cannot do for private or mirrored scopes.
108
+ *
109
+ * Resolves to `null` when the CLI is unavailable or fails for a reason other than
110
+ * the package being absent, so the caller can fall back to a direct request.
111
+ *
112
+ * @param {string} name npm package name
113
+ * @param {string | undefined} cwd directory whose `.npmrc` applies
114
+ * @returns {Promise<NpmLookupResult | null>}
115
+ */
116
+ function lookupViaNpmCli(name, cwd) {
117
+ if (!VALID_NPM_NAME.test(name)) return Promise.resolve(null);
118
+ return new Promise((resolve) => {
119
+ execFile(
120
+ process.platform === 'win32' ? 'npm.cmd' : 'npm',
121
+ ['view', name, 'dist-tags', 'versions', 'magpie.icon', '--json'],
122
+ {
123
+ cwd: cwd || undefined,
124
+ timeout: NPM_CLI_TIMEOUT_MS,
125
+ windowsHide: true,
126
+ maxBuffer: 16 * 1024 * 1024,
127
+ shell: process.platform === 'win32',
128
+ },
129
+ (error, stdout, stderr) => {
130
+ if (error) {
131
+ const output = `${stdout}\n${stderr}`;
132
+ if (/\bE404\b|404 Not Found/i.test(output)) {
133
+ resolve({ ok: false, status: 404, error: 'Package not found' });
134
+ return;
135
+ }
136
+ resolve(null);
137
+ return;
138
+ }
139
+ try {
140
+ const data = JSON.parse(stdout);
141
+ const distTags = parseDistTags(data?.['dist-tags']);
142
+ const versions = Array.isArray(data?.versions)
143
+ ? data.versions.filter((version) => typeof version === 'string')
144
+ : typeof data?.versions === 'string' ? [data.versions] : [];
145
+ const icon = sanitizePluginIcon(data?.['magpie.icon'] ?? data?.magpie?.icon);
146
+ resolve({ ok: true, latest: distTags.latest ?? null, versions, distTags, ...(icon ? { icon } : {}) });
147
+ } catch {
148
+ resolve(null);
149
+ }
150
+ },
151
+ );
152
+ });
153
+ }
154
+
155
+ /** Seam so tests can isolate the direct-request path from the developer's npm. */
156
+ export const npmCli = { lookup: lookupViaNpmCli };
157
+
158
+ /**
159
+ * Fetch package metadata: the npm CLI first (honours scope registries and auth),
160
+ * then a direct request to the public registry when the CLI cannot answer.
161
+ *
162
+ * @param {string} name npm package name
163
+ * @param {{ cwd?: string }} [options]
164
+ * @returns {Promise<NpmLookupResult>}
165
+ */
166
+ export async function lookupNpmPackage(name, options = {}) {
167
+ const viaCli = await npmCli.lookup(name, options.cwd);
168
+ if (viaCli) return viaCli;
169
+ return lookupNpmPackageOverHttp(name);
170
+ }
171
+
82
172
  /**
83
- * Fetch package metadata directly from the npm registry.
173
+ * Fetch package metadata directly from the public npm registry.
84
174
  *
85
175
  * @param {string} name npm package name
86
176
  * @returns {Promise<NpmLookupResult>}
87
177
  */
88
- export async function lookupNpmPackage(name) {
178
+ async function lookupNpmPackageOverHttp(name) {
89
179
  try {
90
180
  const response = await fetch(`${NPM_REGISTRY_BASE}/${encodeName(name)}`, {
91
181
  headers: {
@@ -98,11 +188,14 @@ export async function lookupNpmPackage(name) {
98
188
  if (response.ok) {
99
189
  const data = await response.json();
100
190
  const distTags = parseDistTags(data?.['dist-tags']);
191
+ const latest = distTags.latest ?? null;
192
+ const icon = sanitizePluginIcon(latest ? data?.versions?.[latest]?.magpie?.icon : undefined);
101
193
  return {
102
194
  ok: true,
103
- latest: distTags.latest ?? null,
195
+ latest,
104
196
  versions: parseVersions(data?.versions),
105
197
  distTags,
198
+ ...(icon ? { icon } : {}),
106
199
  };
107
200
  }
108
201
 
@@ -124,29 +217,31 @@ export async function lookupNpmPackage(name) {
124
217
  * @returns {Promise<NpmLookupResult>}
125
218
  */
126
219
  export async function getNpmInfo(name, options = {}) {
127
- const { forceRefresh = false } = options;
128
- const cached = _cache.get(name);
220
+ const { forceRefresh = false, cwd } = options;
221
+ // The cwd selects which `.npmrc` applies, so it is part of the cache identity.
222
+ const cacheKey = cwd ? `${cwd}\0${name}` : name;
223
+ const cached = _cache.get(cacheKey);
129
224
  if (cached && !forceRefresh && Date.now() - cached.fetchedAt < NPM_CACHE_TTL_MS) {
130
225
  return cached.payload;
131
226
  }
132
227
 
133
- const existing = _inFlight.get(name);
228
+ const existing = _inFlight.get(cacheKey);
134
229
  if (existing && !forceRefresh) {
135
230
  return existing;
136
231
  }
137
232
 
138
233
  const lookup = (async () => {
139
- const result = await lookupNpmPackage(name);
140
- cacheResult(name, result);
234
+ const result = await lookupNpmPackage(name, { cwd });
235
+ cacheResult(cacheKey, result);
141
236
  return result;
142
237
  })();
143
238
 
144
- _inFlight.set(name, lookup);
239
+ _inFlight.set(cacheKey, lookup);
145
240
  try {
146
241
  return await lookup;
147
242
  } finally {
148
- if (_inFlight.get(name) === lookup) {
149
- _inFlight.delete(name);
243
+ if (_inFlight.get(cacheKey) === lookup) {
244
+ _inFlight.delete(cacheKey);
150
245
  }
151
246
  }
152
247
  }
@@ -13,18 +13,54 @@ function jsonResponse(body, status = 200) {
13
13
  }));
14
14
  }
15
15
 
16
+ const originalCliLookup = npm.npmCli.lookup;
17
+
16
18
  describe('npm registry client', () => {
17
19
  beforeEach(() => {
18
20
  npm.clearCache();
19
21
  Date.now = originalDateNow;
20
22
  fetchMock = mock(() => jsonResponse({}));
21
23
  globalThis.fetch = fetchMock;
24
+ npm.npmCli.lookup = async () => null;
22
25
  });
23
26
 
24
27
  afterEach(() => {
25
28
  npm.clearCache();
26
29
  globalThis.fetch = originalFetch;
27
30
  Date.now = originalDateNow;
31
+ npm.npmCli.lookup = originalCliLookup;
32
+ });
33
+
34
+ test('npm CLI answer wins and skips the direct request (scope registries/auth)', async () => {
35
+ npm.npmCli.lookup = async () => ({ ok: true, latest: '2.0.0', versions: ['1.0.0', '2.0.0'], distTags: { latest: '2.0.0' } });
36
+
37
+ const result = await npm.lookupNpmPackage('@private/pkg', { cwd: '/proj' });
38
+
39
+ expect(result).toMatchObject({ ok: true, latest: '2.0.0' });
40
+ expect(fetchMock).not.toHaveBeenCalled();
41
+ });
42
+
43
+ test('CLI 404 is definitive and not retried over HTTP', async () => {
44
+ npm.npmCli.lookup = async () => ({ ok: false, status: 404, error: 'Package not found' });
45
+
46
+ const result = await npm.lookupNpmPackage('@private/missing');
47
+
48
+ expect(result).toMatchObject({ ok: false, status: 404 });
49
+ expect(fetchMock).not.toHaveBeenCalled();
50
+ });
51
+
52
+ test('cache is separated by cwd because .npmrc differs per project', async () => {
53
+ let calls = 0;
54
+ npm.npmCli.lookup = async () => {
55
+ calls += 1;
56
+ return { ok: true, latest: '1.0.0', versions: ['1.0.0'], distTags: { latest: '1.0.0' } };
57
+ };
58
+
59
+ await npm.getNpmInfo('foo', { cwd: '/a' });
60
+ await npm.getNpmInfo('foo', { cwd: '/b' });
61
+ await npm.getNpmInfo('foo', { cwd: '/a' });
62
+
63
+ expect(calls).toBe(2);
28
64
  });
29
65
 
30
66
  test('200 success returns latest versions and dist tags', async () => {
@@ -176,4 +212,32 @@ describe('npm registry client', () => {
176
212
 
177
213
  expect(fetchMock.mock.calls[0][1].headers['User-Agent']).toMatch(/^yuri-server\//);
178
214
  });
215
+ test('npm CLI answer carries a vetted magpie.icon', async () => {
216
+ npm.npmCli.lookup = async () => ({ ok: true, latest: '1.0.0', versions: ['1.0.0'], distTags: { latest: '1.0.0' }, icon: 'https://cdn.example/a.png' });
217
+
218
+ const result = await npm.getNpmInfo('@scope/pkg', { cwd: '/proj' });
219
+
220
+ expect(result.icon).toBe('https://cdn.example/a.png');
221
+ });
222
+
223
+ test('registry fallback reads magpie.icon from the latest release', async () => {
224
+ fetchMock.mockImplementation(() => jsonResponse({
225
+ 'dist-tags': { latest: '1.0.0' },
226
+ versions: { '1.0.0': { magpie: { icon: 'data:image/svg+xml;base64,AAAA' } } },
227
+ }));
228
+
229
+ const result = await npm.lookupNpmPackage('foo');
230
+
231
+ expect(result.icon).toBe('data:image/svg+xml;base64,AAAA');
232
+ });
233
+
234
+ test('sanitizePluginIcon keeps only https and data:image, within the size cap', () => {
235
+ expect(npm.sanitizePluginIcon('https://x/y.png')).toBe('https://x/y.png');
236
+ expect(npm.sanitizePluginIcon(' data:image/png;base64,AA ')).toBe('data:image/png;base64,AA');
237
+ expect(npm.sanitizePluginIcon('http://x/y.png')).toBeUndefined();
238
+ expect(npm.sanitizePluginIcon('javascript:alert(1)')).toBeUndefined();
239
+ expect(npm.sanitizePluginIcon('data:text/html;base64,AA')).toBeUndefined();
240
+ expect(npm.sanitizePluginIcon(42)).toBeUndefined();
241
+ expect(npm.sanitizePluginIcon(`https://x/${'a'.repeat(3 << 19)}`)).toBeUndefined();
242
+ });
179
243
  });
@@ -149,7 +149,7 @@ export const registerPluginRoutes = (app, dependencies) => {
149
149
 
150
150
  const npmInfoByName = new Map();
151
151
  await Promise.all(Array.from(npmJobs.keys()).map(async (name) => {
152
- npmInfoByName.set(name, await getNpmInfo(name, { forceRefresh: refresh }));
152
+ npmInfoByName.set(name, await getNpmInfo(name, { forceRefresh: refresh, cwd: directory || undefined }));
153
153
  }));
154
154
 
155
155
  const results = [];
@@ -198,6 +198,7 @@ export const registerPluginRoutes = (app, dependencies) => {
198
198
  currentVersion,
199
199
  latestVersion: info.latest,
200
200
  versions: info.versions,
201
+ ...(info.icon ? { icon: info.icon } : {}),
201
202
  });
202
203
  continue;
203
204
  }
@@ -210,6 +211,7 @@ export const registerPluginRoutes = (app, dependencies) => {
210
211
  latestVersion: info.latest,
211
212
  versions: info.versions,
212
213
  hasUpdate: currentVersion !== null && isExactSemver(currentVersion) && currentVersion !== info.latest,
214
+ ...(info.icon ? { icon: info.icon } : {}),
213
215
  });
214
216
  }
215
217
 
@@ -219,7 +219,7 @@ describe('opencode plugin routes', () => {
219
219
  await request(app).get('/api/config/plugins/registry?specs=foo@1,foo@2,foo@3').expect(200);
220
220
 
221
221
  expect(getNpmInfo).toHaveBeenCalledTimes(1);
222
- expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: false });
222
+ expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: false, cwd: expect.any(String) });
223
223
  });
224
224
 
225
225
  test('GET /registry forwards refresh true to npm lookup', async () => {
@@ -228,7 +228,7 @@ describe('opencode plugin routes', () => {
228
228
 
229
229
  await request(app).get('/api/config/plugins/registry?specs=foo&refresh=true').expect(200);
230
230
 
231
- expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: true });
231
+ expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: true, cwd: expect.any(String) });
232
232
  });
233
233
 
234
234
  test('GET /registry rejects more than 100 unique specs', async () => {
@@ -261,7 +261,7 @@ describe('opencode plugin routes', () => {
261
261
 
262
262
  const response = await request(app).get('/api/config/plugins/registry?specs=%40scope%2Ffoo%401.0.0').expect(200);
263
263
 
264
- expect(getNpmInfo).toHaveBeenCalledWith('@scope/foo', { forceRefresh: false });
264
+ expect(getNpmInfo).toHaveBeenCalledWith('@scope/foo', { forceRefresh: false, cwd: expect.any(String) });
265
265
  expect(response.body.results[0]).toMatchObject({ kind: 'npm-ok', spec: '@scope/foo@1.0.0', name: '@scope/foo' });
266
266
  });
267
267
 
@@ -46,7 +46,7 @@ export function projectMagpieQuotas(payload, source, now = Date.now()) {
46
46
  usedPercent: w.unlimited ? null : percent(w.used), remainingPercent: w.unlimited ? null : percent(w.remaining),
47
47
  resetAt, resetAfterSeconds: resetAt === null ? null : Math.max(0, Math.ceil((resetAt - now) / 1000)),
48
48
  valueLabel: w.unlimited ? '∞' : text(w.display) || (Number.isFinite(w.amount) && Number.isFinite(w.limit) && w.limit > 0 ? `${w.amount} / ${w.limit}${text(w.unit) ? ` ${w.unit}` : ''}` : null),
49
- label: w.name, accountName: account.name, disablePace: true,
49
+ label: w.name, disablePace: true,
50
50
  };
51
51
  account.windows[`${i}:${w.name}`] = window;
52
52
  // Magpie serializes this informational window as used: 0 without its
@@ -57,7 +57,7 @@ export function projectMagpieQuotas(payload, source, now = Date.now()) {
57
57
  result.usage.windows[key] = window;
58
58
  }
59
59
  if (account.balance) {
60
- const window = { ...emptyWindow(), valueLabel: account.balance, label: 'credits_balance', accountName: account.name, disablePace: true };
60
+ const window = { ...emptyWindow(), valueLabel: account.balance, label: 'credits_balance', disablePace: true };
61
61
  account.windows.balance = window;
62
62
  result.usage.windows[`${account.name} · ${q.kind} (${result.usage.accounts.length + 1})`] = window;
63
63
  }
@@ -111,7 +111,8 @@ the inference input. Clean inference does not use the Session context builder.
111
111
  `{ buildOpenCodeUrl, getOpenCodeAuthHeaders, persistSessionMetadata,
112
112
  onSystemSessionPersisted }` into the factory (and the service into session
113
113
  assist/title/goal, scheduled tasks, and `createFeatureRoutesRuntime`). Server
114
- `stop()` calls `stopLlmBridgeDirectory()` to remove the isolated plugin directory.
114
+ `stop()` calls `stopLlmBridgeDirectory()` to forget the isolated plugin directory;
115
+ the content-addressed directory is shared across hosts and is not deleted.
115
116
 
116
117
  ## Summary AI settings
117
118
 
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkstreamRendererImpl-Bmz56IzM.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-base-ui-CdzJ6My_.js","assets/useUIStore-CEingF2z.js","assets/runtime-switch-DhMY9eiB.js","assets/runtime-auth-BaBM02zI.js","assets/vendor-zustand-o69pgTEK.js","assets/brand-storage-bootstrap-D4BW3w-M.js","assets/brand-storage-migration-Bhz6UOBJ.js","assets/vendor-react-BP2cRVqX.js","assets/fileQueries-Bd-OEFmO.js","assets/vendor-tanstack-react-query-CdqCAt40.js","assets/vendor-tanstack-query-core-BWz0ose6.js","assets/queryRuntime-DWgXfxGx.js","assets/runtime-fetch-DfALP7-b.js","assets/vendor-markstream-react-Bm0cO70Z.js","assets/vendor-aparajita-capacitor-secure-storage-xol_6BsB.js","assets/vendor-markstream-core-Cm34iPLL.js","assets/vendor-floating-ui-dom-BHhLtF5l.js","assets/vendor-floating-ui-core-Co1I1lFV.js","assets/vendor-reactuses-core-BJ-jJ4YM.js","assets/vendor-lodash-es-DfLbG5Af.js","assets/vendor-js-cookie-hSOiFTtX.js","assets/button-nola46HU.js","assets/desktop-CiqEZVr5.js","assets/runtimeAPIRegistry-C2VogTny.js","assets/store-ClIuNNU7.js","assets/vendor-class-variance-authority-BLUaYARZ.js","assets/vendor-tailwind-merge-BicNWLTg.js","assets/useMobileNavigationStore-DPE5LVui.js","assets/gitApiHttp-CoNokuDM.js","assets/vendor-opencode-client-fxfj4IA_.js","assets/vendor-effect-DV9F8PTZ.js","assets/persistence-CNEHspb4.js","assets/pathNormalization-ewtPqJWn.js","assets/vendor-pathe-vBmvQE8f.js","assets/runtime-file-resource-DtsKbFf3.js","assets/runtime-file-store-BVRgEtI-.js","assets/path-utils-jGozTg9d.js","assets/platform-Q45KPuGv.js","assets/vendor-sonner-ZS8XIOVl.js","assets/useAssistantUIStore-BZt-lLlW.js","assets/vendor-zod-Dzk5kdUU.js","assets/vendor-fuse.js-DB5wDJbI.js","assets/vendor-fuzzysort-ukaRp9PC.js","assets/useThemeSystem-8jhE4Zyk.js","assets/tooltip-BwTvgqWG.js","assets/image-loading-DVZlFuU5.js","assets/image-loading-D9Z_BASK.css","assets/url-MRa-FtQa.js","assets/useEffectiveDirectory-DE-YccE8.js","assets/LoadingImage-BSG8jmn5.js","assets/ImageLoadingPlaceholder-BVlgaa2r.js","assets/markdownHeightCache-C_JI5qIR.js","assets/dualLimitLru-D8Sphgua.js","assets/MarkdownRendererImpl-CH8TUMKZ.js","assets/vendor-katex-DNVSTX6g.js","assets/FadeInOnReveal-CdoLG8fY.js","assets/markdownTheme-DHoKvD6O.js","assets/vendor-pierre-diffs-DPBtNDJ5.js","assets/vendor-hast-util-to-html-Bw_SgZ1t.js","assets/vendor-character-entities-legacy-Wut6vMuj.js","assets/vendor-character-entities-html4-DlN_yAFd.js","assets/vendor-ccount-CyGsA0u7.js","assets/vendor-comma-separated-tokens-B9ouxNNS.js","assets/vendor-oniguruma-to-es-CrHzjjSU.js","assets/vendor-oniguruma-parser-D2DIvhSP.js","assets/vendor-diff-Dq7CZNim.js","assets/vendor-lru_map-BMOrLc9L.js","assets/markdown-worker-oBGEB9Eg.js","assets/vendor-morphdom-BbKiNDAu.js","assets/vendor-dompurify-CeJNOzik.js","assets/vendor-pele-C1WTNWUm.js","assets/vendor-marked-WVekxjAN.js","assets/vendor-remend-C3cXc-tf.js","assets/fileReferenceActions-BnPPqYXw.js","assets/toolHelpers-DL452NVK.js","assets/fileReferenceParser-1HHDBUum.js","assets/MarkstreamRendererImpl-EpBnVy9J.css"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{a as t}from"./vendor-zustand-o69pgTEK.js";import{it as n,rt as r}from"./vendor-base-ui-CdzJ6My_.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as i}from"./vendor-react-BP2cRVqX.js";import{o as a}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{r as o}from"./button-nola46HU.js";import{t as s}from"./useEffectiveDirectory-DE-YccE8.js";import{i as c,n as l,t as u}from"./markdownHeightCache-C_JI5qIR.js";var d=i(),f=e(n(),1),p=`yuri:chunk-import-reload`,m=250,h=3e4,g=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function _(e){if(e instanceof Error)return`${e.name}\n${e.message}\n${e.stack??``}`;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function v(e){let t=_(e);return g.some(e=>e.test(t))}function y(e){return`0.2.20-beta.3:${_(e).slice(0,500)}`}function b(e){if(typeof window>`u`)return;let t=Date.now(),n=y(e),r=null;try{let e=window.sessionStorage.getItem(p);if(e)try{r=JSON.parse(e)}catch{r=null}}catch{return}let i=typeof r?.timestamp==`number`?r.timestamp:0;if(!(r?.signature===n&&t-i<h)){try{window.sessionStorage.setItem(p,JSON.stringify({signature:n,timestamp:t}))}catch{return}console.error(`[refresh-debug] chunk-import-reload`,{error:_(e).slice(0,1e3)}),window.setTimeout(()=>{window.location.reload()},0)}}async function x(e,t={}){let n=t.retries??1,r;for(let t=0;t<=n;t+=1)try{return await e()}catch(e){if(r=e,!v(e)||t>=n)break;await new Promise(e=>setTimeout(e,m*(t+1)))}throw v(r)&&b(r),r}var S=e=>(0,f.lazy)(()=>x(e)),C=(e,t)=>!!t?.toLowerCase().startsWith(`video/`)||/^data:video\//i.test(e)||/\.(?:mp4|m4v|webm|mov|ogv|ogg)(?:[?#]|$)/i.test(e),w=(e,t)=>{try{let n=t??(typeof localStorage>`u`?null:localStorage);return!n||n.getItem(e)!==`0`}catch{return!0}},T=(e,t)=>{try{typeof localStorage<`u`&&localStorage.setItem(e,t?`1`:`0`)}catch{}},E=`yuri:markstream-react`,D=e=>w(E,e),O=t(e=>({markstreamReactEnabled:D(),setMarkstreamReactEnabled:t=>{T(E,t),e({markstreamReactEnabled:t})}})),k=null,A=()=>(k??=a(()=>import(`./MarkstreamRendererImpl-Bmz56IzM.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78])).catch(e=>{throw k=null,e}),k),j=()=>{A().catch(()=>void 0)},M=null,N=()=>(M??=a(()=>import(`./MarkdownRendererImpl-CH8TUMKZ.js`).then(e=>e.n),__vite__mapDeps([55,1,4,5,24,25,2,3,6,7,8,9,10,11,12,13,14,39,56,20,21,22,23,26,16,27,28,29,30,31,32,33,34,35,36,37,38,40,41,42,43,44,54,45,47,48,49,50,57,53,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77])).catch(e=>{throw M=null,e}),M),P=()=>{N().catch(()=>void 0),D()&&j()},F=class extends f.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.warn(`[markstream-react] falling back to the current Markdown renderer`,e)}render(){return this.state.hasError?this.props.fallback:this.props.children}},I=f.createContext(!0),L=()=>f.useContext(I),R=r(),z=S(()=>N().then(e=>({default:e.MarkdownRenderer}))),B=S(()=>A().then(e=>({default:e.MarkstreamRenderer}))),V=S(()=>N().then(e=>({default:e.SimpleMarkdownRenderer}))),H=e=>e===`tool`?`markdown-content markdown-tool`:e===`reasoning`?`markdown-content markdown-reasoning`:`markdown-content leading-relaxed`,U=e=>{let t=(0,d.c)(15),n=O(K),r=typeof e.content==`string`?e.content:``,i=typeof e.variant==`string`?e.variant:`assistant`,a;t[0]!==r||t[1]!==n||t[2]!==e.reserveMeasuredHeight||t[3]!==i?(a=e.reserveMeasuredHeight?l(u(r,n?`markstream:${i}`:i)):void 0,t[0]=r,t[1]=n,t[2]=e.reserveMeasuredHeight,t[3]=i,t[4]=a):a=t[4];let s=a,f;t[5]!==e.className||t[6]!==e.variant?(f=o(`relative break-words w-full min-w-0`,H(e.variant),typeof e.className==`string`?e.className:void 0),t[5]=e.className,t[6]=e.variant,t[7]=f):f=t[7];let p;t[8]!==r||t[9]!==e.animated||t[10]!==s?(p=(0,R.jsx)(c,{animated:e.animated,content:r,reservedHeight:s}),t[8]=r,t[9]=e.animated,t[10]=s,t[11]=p):p=t[11];let m;return t[12]!==f||t[13]!==p?(m=(0,R.jsx)(`div`,{className:f,"aria-busy":`true`,"data-markdown-hydration":`deferred`,"data-markdown-ready":`false`,children:p}),t[12]=f,t[13]=p,t[14]=m):m=t[14],m},W=e=>{let t=(0,d.c)(13),n=L(),r=O(q);if(!n&&e.isStreaming!==!0){let n;return t[0]===e?n=t[1]:(n=(0,R.jsx)(U,{...e,animated:!1,reserveMeasuredHeight:!0}),t[0]=e,t[1]=n),n}let i;t[2]===e?i=t[3]:(i=(0,R.jsx)(f.Suspense,{fallback:(0,R.jsx)(U,{...e,reserveMeasuredHeight:!0}),children:(0,R.jsx)(z,{...e})}),t[2]=e,t[3]=i);let a=i,o;t[4]!==a||t[5]!==r||t[6]!==e?(o=r?(0,R.jsx)(F,{fallback:a,children:(0,R.jsx)(f.Suspense,{fallback:(0,R.jsx)(U,{...e,reserveMeasuredHeight:!0}),children:(0,R.jsx)(B,{...e})})}):a,t[4]=a,t[5]=r,t[6]=e,t[7]=o):o=t[7];let c=o,l;t[8]===e?l=t[9]:(l=t=>{if(!e.onShowPopup||t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let n=t.target instanceof Element?t.target.closest(`a[href]`):null,r=n?.getAttribute(`href`);if(!r||!C(r))return;t.preventDefault(),t.stopPropagation();let i=n?.textContent?.trim()||r.split(/[/?#]/).filter(Boolean).pop()||r;e.onShowPopup({open:!0,title:i,content:``,video:{url:r,filename:i,directory:s()??``}})},t[8]=e,t[9]=l);let u;return t[10]!==c||t[11]!==l?(u=(0,R.jsx)(`div`,{className:`contents`,onClickCapture:l,children:c}),t[10]=c,t[11]=l,t[12]=u):u=t[12],u},G=e=>{let t=(0,d.c)(4);if(!L()){let n;return t[0]===e?n=t[1]:(n=(0,R.jsx)(U,{...e,animated:!1}),t[0]=e,t[1]=n),n}let n;return t[2]===e?n=t[3]:(n=(0,R.jsx)(f.Suspense,{fallback:(0,R.jsx)(U,{...e}),children:(0,R.jsx)(V,{...e})}),t[2]=e,t[3]=n),n};function K(e){return e.markstreamReactEnabled}function q(e){return e.markstreamReactEnabled}export{C as a,P as i,G as n,S as o,I as r,W as t};