From 20a0ba9b173b78d69c0fb9464a18bb0bfe8ff020 Mon Sep 17 00:00:00 2001 From: Haozhe Date: Thu, 3 Sep 2026 14:32:28 +0800 Subject: [PATCH 01/19] test: speed up kap-server suite and exclude minidb from default projects (#3504) * test: speed up kap-server suite and exclude minidb from default projects * test(kap-server): restore baseline server after sessions tests replace it --- packages/kap-server/package.json | 1 + .../test/apiSurface.snapshot.test.ts | 33 +-- packages/kap-server/test/approvals.test.ts | 6 +- packages/kap-server/test/auth.test.ts | 28 +-- .../kap-server/test/authMiddleware.test.ts | 24 +- .../kap-server/test/authWiring.e2e.test.ts | 16 +- packages/kap-server/test/capabilities.test.ts | 45 +--- packages/kap-server/test/config.test.ts | 64 +++-- packages/kap-server/test/connections.test.ts | 6 +- .../kap-server/test/disableAuth.e2e.test.ts | 81 +++--- packages/kap-server/test/fileHistory.test.ts | 22 +- packages/kap-server/test/files.test.ts | 29 ++- packages/kap-server/test/fs-watch.e2e.test.ts | 34 +-- packages/kap-server/test/fs.test.ts | 112 ++------- packages/kap-server/test/globalSetup.ts | 36 +++ packages/kap-server/test/guiStore.test.ts | 7 +- .../test/helpers/fakeModelCatalog.ts | 28 +++ .../kap-server/test/helpers/sharedServer.ts | 34 +++ packages/kap-server/test/messages.test.ts | 6 +- packages/kap-server/test/meta.test.ts | 55 ++-- packages/kap-server/test/modelCatalog.test.ts | 53 +++- .../test/modelCatalogCatalog.test.ts | 34 +-- .../test/modelCatalogProviderWrite.test.ts | 28 +-- packages/kap-server/test/openapi.test.ts | 36 +-- packages/kap-server/test/plugins.test.ts | 49 +++- packages/kap-server/test/prompts.test.ts | 77 +++--- packages/kap-server/test/questions.test.ts | 6 +- .../kap-server/test/requestLogging.test.ts | 18 +- packages/kap-server/test/rpc.test.ts | 14 +- .../test/search/searchRoute.test.ts | 11 +- .../test/search/searchService.bench.ts | 235 ++++++++++++++++++ .../test/search/searchService.test.ts | 195 ++++----------- .../kap-server/test/securityExposure.test.ts | 73 +++--- packages/kap-server/test/sessions.test.ts | 54 +++- packages/kap-server/test/skills.test.ts | 8 +- packages/kap-server/test/snapshot.test.ts | 6 +- packages/kap-server/test/tasks.test.ts | 6 +- packages/kap-server/test/terminals.test.ts | 24 +- packages/kap-server/test/tools.test.ts | 6 +- packages/kap-server/test/transcript.test.ts | 6 +- .../test/transcriptContract.e2e.test.ts | 22 +- packages/kap-server/test/v2Sessions.test.ts | 32 ++- packages/kap-server/test/workspaceFs.test.ts | 18 +- .../kap-server/test/workspaceLayout.test.ts | 6 +- packages/kap-server/test/workspaces.test.ts | 21 +- .../kap-server/test/wsBearerProtocol.test.ts | 32 +-- packages/kap-server/test/wsHostOrigin.test.ts | 9 +- .../kap-server/test/wsUpgradeAuth.test.ts | 58 ++--- packages/kap-server/test/wsV1Resync.test.ts | 6 +- packages/kap-server/vitest.bench.config.ts | 12 + packages/kap-server/vitest.config.ts | 2 + vitest.config.ts | 2 +- 52 files changed, 1059 insertions(+), 767 deletions(-) create mode 100644 packages/kap-server/test/globalSetup.ts create mode 100644 packages/kap-server/test/helpers/fakeModelCatalog.ts create mode 100644 packages/kap-server/test/helpers/sharedServer.ts create mode 100644 packages/kap-server/test/search/searchService.bench.ts create mode 100644 packages/kap-server/vitest.bench.config.ts diff --git a/packages/kap-server/package.json b/packages/kap-server/package.json index 92f170fd63f..6709ec295bb 100644 --- a/packages/kap-server/package.json +++ b/packages/kap-server/package.json @@ -22,6 +22,7 @@ "build": "tsdown", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "vitest run", + "test:bench": "vitest run --config vitest.bench.config.ts", "clean": "rm -rf dist" }, "dependencies": { diff --git a/packages/kap-server/test/apiSurface.snapshot.test.ts b/packages/kap-server/test/apiSurface.snapshot.test.ts index aec66bae156..0f0688c168d 100644 --- a/packages/kap-server/test/apiSurface.snapshot.test.ts +++ b/packages/kap-server/test/apiSurface.snapshot.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { startServer, type RunningServer } from '../src'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -25,7 +25,19 @@ describe('API surface snapshot', () => { let home: string | undefined; let server: RunningServer | undefined; - afterEach(async () => { + beforeAll(async () => { + home = mkdtempSync(join(tmpdir(), 'kimi-server-v2-api-surface-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + debugEndpoints: true, + }); + }); + + afterAll(async () => { if (server !== undefined) { try { await server.close(); @@ -40,20 +52,9 @@ describe('API surface snapshot', () => { }); it('matches the documented v2 route table and meta endpoints', async () => { - home = mkdtempSync(join(tmpdir(), 'kimi-server-v2-api-surface-')); - - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - debugEndpoints: true, - }); - - const base = `http://${server.host}:${server.port}`; + const base = `http://${server!.host}:${server!.port}`; - const openApiRes = await fetch(`${base}/openapi.json`, { headers: authHeaders(server) } as never); + const openApiRes = await fetch(`${base}/openapi.json`, { headers: authHeaders(server as RunningServer) } as never); expect(openApiRes.status).toBe(200); const openApi = (await openApiRes.json()) as { paths?: Record>; @@ -73,7 +74,7 @@ describe('API surface snapshot', () => { const meta: Array<[string, string, number]> = []; for (const endpoint of META_ENDPOINTS) { - const res = await fetch(`${base}${endpoint}`, { headers: authHeaders(server) } as never); + const res = await fetch(`${base}${endpoint}`, { headers: authHeaders(server as RunningServer) } as never); meta.push(['GET', endpoint, res.status]); } meta.sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1]) || a[2] - b[2]); diff --git a/packages/kap-server/test/approvals.test.ts b/packages/kap-server/test/approvals.test.ts index 1e261ce26d0..aae15326185 100644 --- a/packages/kap-server/test/approvals.test.ts +++ b/packages/kap-server/test/approvals.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { ISessionApprovalService, ensureMainAgent, getLiveSessionById } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -43,7 +43,7 @@ describe('server-v2 /api/v1/sessions/{sid}/approvals', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-approvals-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -55,7 +55,7 @@ describe('server-v2 /api/v1/sessions/{sid}/approvals', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/auth.test.ts b/packages/kap-server/test/auth.test.ts index f5e10e64521..ed7897b11a5 100644 --- a/packages/kap-server/test/auth.test.ts +++ b/packages/kap-server/test/auth.test.ts @@ -2,8 +2,9 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { IConfigService } from '@moonshot-ai/agent-core-v2'; import { authSummarySchema, type AuthSummary } from '@moonshot-ai/agent-core-v2/app/authLegacy/authLegacy'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -21,11 +22,19 @@ describe('server-v2 GET /api/v1/auth', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-auth-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -37,17 +46,8 @@ describe('server-v2 GET /api/v1/auth', () => { }); async function boot(toml?: string): Promise { - if (toml !== undefined) { - await writeFile(join(home as string, 'config.toml'), toml, 'utf-8'); - } - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - base = `http://127.0.0.1:${server.port}`; + await writeFile(join(home as string, 'config.toml'), toml ?? '', 'utf-8'); + await (server as RunningServer).core.accessor.get(IConfigService).reload(); } async function getAuth(): Promise { diff --git a/packages/kap-server/test/authMiddleware.test.ts b/packages/kap-server/test/authMiddleware.test.ts index d5d4f4081de..4dfa20f426a 100644 --- a/packages/kap-server/test/authMiddleware.test.ts +++ b/packages/kap-server/test/authMiddleware.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -11,11 +11,12 @@ describe('server-v2 /api/v1 bearer auth', () => { let server: RunningServer | undefined; let home: string | undefined; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-auth-middleware-')); + server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -27,22 +28,19 @@ describe('server-v2 /api/v1 bearer auth', () => { }); it('allows healthz without a token', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ method: 'GET', url: '/api/v1/healthz' }); + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/healthz' }); expect(res.statusCode).toBe(200); }); it('rejects /api/v1/auth without a token with 40101', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ method: 'GET', url: '/api/v1/auth' }); + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/auth' }); expect(res.statusCode).toBe(401); const body = res.json() as Record; expect(body['code']).toBe(40101); }); it('rejects /api/v1/auth with a wrong token', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/auth', headers: { authorization: 'Bearer wrong-token' }, @@ -53,9 +51,8 @@ describe('server-v2 /api/v1 bearer auth', () => { }); it('accepts /api/v1/auth with the persistent token', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const token = server.authTokenService.getToken(); - const res = await server.app.inject({ + const token = server!.authTokenService.getToken(); + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/auth', headers: { authorization: `Bearer ${token}` }, @@ -66,8 +63,7 @@ describe('server-v2 /api/v1 bearer auth', () => { }); it('requires auth for /openapi.json', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ method: 'GET', url: '/openapi.json' }); + const res = await server!.app.inject({ method: 'GET', url: '/openapi.json' }); expect(res.statusCode).toBe(401); }); }); diff --git a/packages/kap-server/test/authWiring.e2e.test.ts b/packages/kap-server/test/authWiring.e2e.test.ts index fae55e60b30..23481144c86 100644 --- a/packages/kap-server/test/authWiring.e2e.test.ts +++ b/packages/kap-server/test/authWiring.e2e.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { WebSocket, type RawData } from 'ws'; import { type RunningServer, startServer } from '../src/start'; @@ -58,19 +58,26 @@ describe('production auth wiring', () => { let base: string; const sockets: WebSocket[] = []; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-auth-wiring-')); + await boot(); + }); + + async function boot(): Promise { server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); base = `http://127.0.0.1:${server.port}`; - }); + } - afterEach(async () => { + afterEach(() => { for (const ws of sockets.splice(0)) { try { ws.close(); } catch { } } + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -92,6 +99,7 @@ describe('production auth wiring', () => { server = undefined; const after = await stat(p); expect(after.mode & 0o777).toBe(0o600); + await boot(); }); it('gates HTTP: 200 with the token, 401 without', async () => { diff --git a/packages/kap-server/test/capabilities.test.ts b/packages/kap-server/test/capabilities.test.ts index 745898b404e..07d08d0bdbd 100644 --- a/packages/kap-server/test/capabilities.test.ts +++ b/packages/kap-server/test/capabilities.test.ts @@ -1,16 +1,10 @@ -import { mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; - -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { capabilityStatusSchema, listCapabilitiesResponseSchema, } from '../src/protocol/rest-capability'; -import { type RunningServer, startServer } from '../src/start'; -import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; -import { authHeaders } from './helpers/auth'; +import { sharedAuthHeaders, sharedServer } from './helpers/sharedServer'; interface Envelope { code: number; @@ -20,44 +14,17 @@ interface Envelope { } describe('server-v2 /api/v1 capabilities', () => { - let server: RunningServer | undefined; - let home: string | undefined; - let base: string; - - beforeEach(async () => { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-capabilities-')); - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - base = `http://127.0.0.1:${server.port}`; - }); - - afterEach(async () => { - if (server !== undefined) { - await server.close(); - server = undefined; - } - if (home !== undefined) { - await rm(home, { recursive: true, force: true, maxRetries: 3, retryDelay: 25 } as never); - home = undefined; - } - }); - async function getJson(path: string): Promise<{ status: number; body: Envelope }> { - const res = await fetch(`${base}${path}`, { - headers: authHeaders(server as RunningServer), + const res = await fetch(`${sharedServer().base}${path}`, { + headers: sharedAuthHeaders(), } as never); return { status: res.status, body: (await res.json()) as Envelope }; } async function postJson(path: string): Promise<{ status: number; body: Envelope }> { - const res = await fetch(`${base}${path}`, { + const res = await fetch(`${sharedServer().base}${path}`, { method: 'POST', - headers: authHeaders(server as RunningServer, { 'content-type': 'application/json' }), + headers: sharedAuthHeaders({ 'content-type': 'application/json' }), body: '{}', } as never); return { status: res.status, body: (await res.json()) as Envelope }; diff --git a/packages/kap-server/test/config.test.ts b/packages/kap-server/test/config.test.ts index f6d81e3c312..e1ea4268a99 100644 --- a/packages/kap-server/test/config.test.ts +++ b/packages/kap-server/test/config.test.ts @@ -12,7 +12,7 @@ import { } from '@moonshot-ai/agent-core-v2'; import { configResponseSchema, type ConfigResponse } from '../src/protocol/rest-config'; import { ErrorCode } from '../src/protocol/error-codes'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { WebSocket } from 'ws'; import { type RunningServer, startServer } from '../src/start'; @@ -32,11 +32,19 @@ describe('server-v2 /api/v1/config', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-config-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -48,17 +56,8 @@ describe('server-v2 /api/v1/config', () => { }); async function boot(toml?: string): Promise { - if (toml !== undefined) { - await writeFile(join(home as string, 'config.toml'), toml, 'utf-8'); - } - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - base = `http://127.0.0.1:${server.port}`; + await writeFile(join(home as string, 'config.toml'), toml ?? '', 'utf-8'); + await (server as RunningServer).core.accessor.get(IConfigService).reload(); } async function getConfig(): Promise { @@ -178,12 +177,23 @@ describe('server-v2 config changed WS notifications', () => { let base: string; const sockets: WebSocket[] = []; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-config-ws-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterEach(() => { for (const ws of sockets.splice(0)) ws.close(); + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -195,17 +205,19 @@ describe('server-v2 config changed WS notifications', () => { }); async function boot(toml?: string): Promise { - if (toml !== undefined) { - await writeFile(join(home as string, 'config.toml'), toml, 'utf-8'); + if (server === undefined) { + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + base = `http://127.0.0.1:${server.port}`; } - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - base = `http://127.0.0.1:${server.port}`; + await writeFile(join(home as string, 'config.toml'), toml ?? '', 'utf-8'); + await (server as RunningServer).core.accessor.get(IConfigService).reload(); + await new Promise((resolve) => setTimeout(resolve, 25)); } interface ConfigChangedFrame { diff --git a/packages/kap-server/test/connections.test.ts b/packages/kap-server/test/connections.test.ts index c2a0008310a..ce3aa1a65a4 100644 --- a/packages/kap-server/test/connections.test.ts +++ b/packages/kap-server/test/connections.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { connectionsListResponseSchema } from '../src/protocol/rest-connection'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { WebSocket } from 'ws'; import { type RunningServer, startServer } from '../src/start'; @@ -23,14 +23,14 @@ describe('server-v2 GET /api/v1/connections', () => { let base: string; let wsUrl: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-connections-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); base = `http://127.0.0.1:${server.port}`; wsUrl = `ws://127.0.0.1:${server.port}/api/v1/ws`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/disableAuth.e2e.test.ts b/packages/kap-server/test/disableAuth.e2e.test.ts index cb31acb0a04..aa4360a1cfc 100644 --- a/packages/kap-server/test/disableAuth.e2e.test.ts +++ b/packages/kap-server/test/disableAuth.e2e.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { WebSocket, type RawData } from 'ws'; import { type RunningServer, startServer } from '../src/start'; @@ -37,13 +37,29 @@ describe('server-v2 disableAuth (--dangerous-bypass-auth)', () => { let home: string | undefined; const sockets: WebSocket[] = []; - afterEach(async () => { + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-disable-auth-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + authTokenService: fixedTokenAuth(TOKEN), + disableAuth: true, + }); + }); + + afterEach(() => { for (const ws of sockets.splice(0)) { try { ws.close(); } catch { } } + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -54,22 +70,8 @@ describe('server-v2 disableAuth (--dangerous-bypass-auth)', () => { } }); - async function boot(disableAuth?: boolean): Promise<{ base: string; port: number }> { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-disable-auth-')); - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - authTokenService: fixedTokenAuth(TOKEN), - disableAuth, - }); - return { base: `http://127.0.0.1:${server.port}`, port: server.port }; - } - it('disableAuth:true lets REST through without a token and advertises it in /meta', async () => { - const { base } = await boot(true); + const base = `http://127.0.0.1:${server!.port}`; const meta = await fetch(`${base}/api/v1/meta`); expect(meta.status).toBe(200); @@ -85,27 +87,40 @@ describe('server-v2 disableAuth (--dangerous-bypass-auth)', () => { }); it('disableAuth:true lets WebSocket upgrades through without a token', async () => { - const { port } = await boot(true); - - const v1 = await openConn(`ws://127.0.0.1:${port}/api/v1/ws`); + const v1 = await openConn(`ws://127.0.0.1:${server!.port}/api/v1/ws`); sockets.push(v1.ws); expect(v1.firstFrame).toMatchObject({ type: 'server_hello' }); }); it('default boot keeps the gate closed and reports dangerous_bypass_auth: false', async () => { - const { base } = await boot(undefined); - - const unauthed = await fetch(`${base}/api/v1/meta`); - expect(unauthed.status).toBe(401); - - const meta = await fetch(`${base}/api/v1/meta`, { - headers: { authorization: `Bearer ${TOKEN}` }, + const altHome = await mkdtemp(join(tmpdir(), 'kimi-server-v2-disable-auth-')); + const alt = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: altHome, + logLevel: 'silent', + authTokenService: fixedTokenAuth(TOKEN), + disableAuth: undefined, }); - expect(meta.status).toBe(200); - const metaBody = (await meta.json()) as { - code: number; - data: { dangerous_bypass_auth: boolean }; - }; - expect(metaBody.data.dangerous_bypass_auth).toBe(false); + try { + const base = `http://127.0.0.1:${alt.port}`; + + const unauthed = await fetch(`${base}/api/v1/meta`); + expect(unauthed.status).toBe(401); + + const meta = await fetch(`${base}/api/v1/meta`, { + headers: { authorization: `Bearer ${TOKEN}` }, + }); + expect(meta.status).toBe(200); + const metaBody = (await meta.json()) as { + code: number; + data: { dangerous_bypass_auth: boolean }; + }; + expect(metaBody.data.dangerous_bypass_auth).toBe(false); + } finally { + await alt.close(); + await rm(altHome, { recursive: true, force: true }); + } }); }); diff --git a/packages/kap-server/test/fileHistory.test.ts b/packages/kap-server/test/fileHistory.test.ts index 3cf3071db91..bee046d866d 100644 --- a/packages/kap-server/test/fileHistory.test.ts +++ b/packages/kap-server/test/fileHistory.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -10,11 +10,18 @@ import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; let home: string; let server: RunningServer | undefined; -beforeEach(() => { +beforeAll(async () => { home = mkdtempSync(join(tmpdir(), 'kimi-server-v2-file-history-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); }); -afterEach(async () => { +afterAll(async () => { try { await server?.close(); } catch { @@ -24,14 +31,7 @@ afterEach(async () => { }); async function boot(): Promise { - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - return server; + return server as RunningServer; } interface InjectResponse { diff --git a/packages/kap-server/test/files.test.ts b/packages/kap-server/test/files.test.ts index 802e181d3cd..c3395ea2900 100644 --- a/packages/kap-server/test/files.test.ts +++ b/packages/kap-server/test/files.test.ts @@ -8,7 +8,7 @@ import { ISessionManager, ISessionMediaStore, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -16,11 +16,18 @@ import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; let home: string; let server: RunningServer | undefined; -beforeEach(() => { +beforeAll(async () => { home = mkdtempSync(join(tmpdir(), 'kimi-server-v2-files-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); }); -afterEach(async () => { +afterAll(async () => { try { await server?.close(); } catch { @@ -30,13 +37,15 @@ afterEach(async () => { }); async function boot(): Promise { - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); + if (server === undefined) { + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + } return server; } diff --git a/packages/kap-server/test/fs-watch.e2e.test.ts b/packages/kap-server/test/fs-watch.e2e.test.ts index 8b7afcf2db4..c423e492b97 100644 --- a/packages/kap-server/test/fs-watch.e2e.test.ts +++ b/packages/kap-server/test/fs-watch.e2e.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pino } from 'pino'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { WebSocket, type RawData } from 'ws'; import { startServer, type RunningServer } from '../src/start'; @@ -14,9 +14,20 @@ let bridgeHome: string; let workspace: string; let server: RunningServer | undefined; +beforeAll(async () => { + bridgeHome = mkdtempSync(join(tmpdir(), 'kap-fswatch-home-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: bridgeHome, + logger: pino({ level: 'silent' }), + disableAuth: true, + }); +}); + beforeEach(() => { tmpDir = mkdtempSync(join(tmpdir(), 'kap-fswatch-')); - bridgeHome = mkdtempSync(join(tmpdir(), 'kap-fswatch-home-')); workspace = join(tmpDir, 'workspace'); mkdirSync(workspace, { recursive: true }); mkdirSync(join(workspace, 'src'), { recursive: true }); @@ -24,26 +35,21 @@ beforeEach(() => { }); afterEach(async () => { + vi.unstubAllEnvs(); + rmSync(tmpDir, { recursive: true, force: true }); +}); + +afterAll(async () => { try { await server?.close(); } catch { } server = undefined; - vi.unstubAllEnvs(); - rmSync(tmpDir, { recursive: true, force: true }); rmSync(bridgeHome, { recursive: true, force: true }); }); async function boot(): Promise { - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: bridgeHome, - logger: pino({ level: 'silent' }), - disableAuth: true, - }); - return server; + return server as RunningServer; } function addressOf(r: RunningServer): string { @@ -210,7 +216,7 @@ describe('WS fs watch (kap-server)', () => { writeFileSync(join(workspace, 'src', 'instant.ts'), 'export const i = 1;\n'); - const ev = await receiveType(conn, 'event.fs.changed', 3000); + const ev = await receiveType(conn, 'event.fs.changed', 10_000); expect(ev.session_id).toBe(sid); const payload = ev.payload as { changes: Array<{ path: string }> }; expect(payload.changes.some((c) => c.path === 'src/instant.ts' || c.path === 'src')).toBe(true); diff --git a/packages/kap-server/test/fs.test.ts b/packages/kap-server/test/fs.test.ts index 2a2d35daba8..de43d112504 100644 --- a/packages/kap-server/test/fs.test.ts +++ b/packages/kap-server/test/fs.test.ts @@ -1,4 +1,4 @@ -import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { chmod, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, sep } from 'node:path'; @@ -6,11 +6,12 @@ import { IModelCatalog, IWorkspaceInstanceManager } from '@moonshot-ai/agent-cor import { HostFileSystem } from '@moonshot-ai/agent-core-v2/os/backends/node-local/hostFsService'; import { FakeRuntime } from '@moonshot-ai/agent-core-v2/runtime/fakeRuntime'; import { ErrorCode } from '../src/protocol/error-codes'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; import { authHeaders } from './helpers/auth'; +import { fakeModelCatalog } from './helpers/fakeModelCatalog'; interface Envelope { code: number; @@ -36,45 +37,31 @@ describe('server-v2 /api/v1 fs routes', () => { let work: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fs-home-')); - work = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fs-work-')); - const modelCatalog: IModelCatalog = { - _serviceBrand: undefined, - get: () => { - throw new Error('modelCatalog.get not exercised in this test'); - }, - getRequester: () => { - throw new Error('modelCatalog.getRequester not exercised in this test'); - }, - inspect: () => { - throw new Error('modelCatalog.inspect not exercised in this test'); - }, - ping: () => { - throw new Error('modelCatalog.ping not exercised in this test'); - }, - findByName: () => [], - listModels: async () => [], - listProviders: async () => [], - getProvider: async () => { - throw new Error('modelCatalog.getProvider not exercised in this test'); - }, - setDefaultModel: async () => { - throw new Error('modelCatalog.setDefaultModel not exercised in this test'); - }, - }; server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent', - seeds: [[IModelCatalog, modelCatalog]], + seeds: [[IModelCatalog, fakeModelCatalog()]], }); base = `http://127.0.0.1:${server.port}`; }); + beforeEach(async () => { + work = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fs-work-')); + }); + afterEach(async () => { + if (work !== undefined) { + await rm(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); + work = undefined; + } + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -83,10 +70,6 @@ describe('server-v2 /api/v1 fs routes', () => { await rm(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); home = undefined; } - if (work !== undefined) { - await rm(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); - work = undefined; - } }); async function createSession(): Promise { @@ -371,57 +354,6 @@ describe('server-v2 /api/v1 fs routes', () => { } }); - it('GET fs/{path}:download streams the file and honors If-None-Match', async () => { - await writeFile(join(work!, 'a.txt'), 'download-me'); - const id = await createSession(); - - const res = await fetch(`${base}/api/v1/sessions/${id}/fs/a.txt:download?runtime_id=local`, { - headers: authHeaders(server as RunningServer), - } as never); - expect(res.status).toBe(200); - const text = await res.text(); - expect(text).toBe('download-me'); - const etag = res.headers.get('etag'); - expect(etag).toBeTruthy(); - - const cached = await fetch(`${base}/api/v1/sessions/${id}/fs/a.txt:download?runtime_id=local`, { - headers: authHeaders(server as RunningServer, { 'if-none-match': etag as string }), - } as never); - expect(cached.status).toBe(304); - }); - - it('GET fs/{path}:download defaults to the local runtime when runtime_id is omitted', async () => { - await writeFile(join(work!, 'b.txt'), 'compat-download'); - const id = await createSession(); - - const res = await fetch(`${base}/api/v1/sessions/${id}/fs/b.txt:download`, { - headers: authHeaders(server as RunningServer), - } as never); - expect(res.status).toBe(200); - expect(await res.text()).toBe('compat-download'); - }); - - it('GET fs/{path}:download untracks the stream from the runtime generation after completion', async () => { - await writeFile(join(work!, 'c.txt'), 'tracked-download'); - const id = await createSession(); - const instance = server!.core.accessor.get(IWorkspaceInstanceManager).findByRoot(work!); - expect(instance).toBeDefined(); - const generations = (instance!.runtimes as unknown as { - currentGenerations: Map }>; - }).currentGenerations; - const resources = generations.get('local')!.resources; - const baseline = resources.size; - - for (let i = 0; i < 2; i += 1) { - const res = await fetch(`${base}/api/v1/sessions/${id}/fs/c.txt:download?runtime_id=local`, { - headers: authHeaders(server as RunningServer), - } as never); - expect(res.status).toBe(200); - expect(await res.text()).toBe('tracked-download'); - await vi.waitFor(() => expect(resources.size).toBe(baseline)); - } - }); - async function postWorkspaceSearch(body: unknown): Promise> { const res = await fetch(`${base}/api/v1/workspace/fs:search`, { method: 'POST', @@ -648,15 +580,21 @@ describe('server-v2 /api/v1 fs routes', () => { expect(body.code).toBe(0); expect(body.data.items.map((i) => i.path)).toContain('kappa.ts'); - expect(await listWorkspaces()).toEqual([]); - expect(server!.core.accessor.get(IWorkspaceInstanceManager).list()).toEqual([]); + const workAliases = [work!, await realpath(work!)]; + expect((await listWorkspaces()).some((w) => workAliases.includes(w.root))).toBe(false); + expect( + server!.core.accessor + .get(IWorkspaceInstanceManager) + .list() + .some((w) => workAliases.includes(w.root)), + ).toBe(false); const again = await postRootSuggest<{ items: SuggestItemWire[] }>({ roots: [work], query: 'kappa', }); expect(again.code).toBe(0); - expect(await listWorkspaces()).toEqual([]); + expect((await listWorkspaces()).some((w) => workAliases.includes(w.root))).toBe(false); }); it('fs:suggest matches the workspace route for the same single root', async () => { diff --git a/packages/kap-server/test/globalSetup.ts b/packages/kap-server/test/globalSetup.ts new file mode 100644 index 00000000000..757b46523a7 --- /dev/null +++ b/packages/kap-server/test/globalSetup.ts @@ -0,0 +1,36 @@ +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { IModelCatalog } from '@moonshot-ai/agent-core-v2'; +import type { TestProject } from 'vitest/node'; + +import { startServer } from '../src/start'; +import { fakeModelCatalog } from './helpers/fakeModelCatalog'; +import { fixedTokenAuth } from './helpers/fixedAuth'; +import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; + +export const SHARED_SERVER_TOKEN = 'test-token'; + +export default async function globalSetup(project: TestProject): Promise<() => Promise> { + process.env['KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER'] = 'false'; + process.env['KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL'] = 'false'; + const home = await mkdtemp(join(tmpdir(), 'kimi-kap-server-shared-home-')); + const server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + authTokenService: fixedTokenAuth(SHARED_SERVER_TOKEN), + seeds: [[IModelCatalog, fakeModelCatalog()]], + }); + project.provide('sharedServer', { + base: `http://127.0.0.1:${server.port}`, + token: SHARED_SERVER_TOKEN, + }); + return async () => { + await server.close(); + await rm(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); + }; +} diff --git a/packages/kap-server/test/guiStore.test.ts b/packages/kap-server/test/guiStore.test.ts index 55c0317c6bf..c7afacc2e3f 100644 --- a/packages/kap-server/test/guiStore.test.ts +++ b/packages/kap-server/test/guiStore.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -59,12 +59,12 @@ describe('server-v2 gui store routes', () => { let home: string | undefined; let server: RunningServer | undefined; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-gui-store-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -131,6 +131,7 @@ describe('server-v2 gui store routes', () => { it('length reports the count and clear empties the store', async () => { const api = appOf(server as RunningServer); + await api.inject({ method: 'POST', url: '/api/v1/gui/store/clear' }); await setItem(api, 'a', '1'); await setItem(api, 'b', '2'); diff --git a/packages/kap-server/test/helpers/fakeModelCatalog.ts b/packages/kap-server/test/helpers/fakeModelCatalog.ts new file mode 100644 index 00000000000..846611b9dd5 --- /dev/null +++ b/packages/kap-server/test/helpers/fakeModelCatalog.ts @@ -0,0 +1,28 @@ +import { IModelCatalog } from '@moonshot-ai/agent-core-v2'; + +export function fakeModelCatalog(): IModelCatalog { + return { + _serviceBrand: undefined, + get: () => { + throw new Error('modelCatalog.get not exercised in this test'); + }, + getRequester: () => { + throw new Error('modelCatalog.getRequester not exercised in this test'); + }, + inspect: () => { + throw new Error('modelCatalog.inspect not exercised in this test'); + }, + ping: () => { + throw new Error('modelCatalog.ping not exercised in this test'); + }, + findByName: () => [], + listModels: async () => [], + listProviders: async () => [], + getProvider: async () => { + throw new Error('modelCatalog.getProvider not exercised in this test'); + }, + setDefaultModel: async () => { + throw new Error('modelCatalog.setDefaultModel not exercised in this test'); + }, + }; +} diff --git a/packages/kap-server/test/helpers/sharedServer.ts b/packages/kap-server/test/helpers/sharedServer.ts new file mode 100644 index 00000000000..941bd6fe718 --- /dev/null +++ b/packages/kap-server/test/helpers/sharedServer.ts @@ -0,0 +1,34 @@ +import { inject } from 'vitest'; + +export interface SharedServerContext { + readonly base: string; + readonly token: string; +} + +declare module 'vitest' { + interface ProvidedContext { + readonly sharedServer: SharedServerContext; + } +} + +export function sharedServer(): SharedServerContext { + return inject('sharedServer'); +} + +export function sharedAuthHeaders(extra: Record = {}): Record { + return { ...extra, authorization: `Bearer ${sharedServer().token}` }; +} + +interface SharedFetchOptions { + readonly method?: string; + readonly headers?: Record; + readonly body?: string; + readonly signal?: AbortSignal; +} + +export async function sharedAuthedFetch(path: string, init: SharedFetchOptions = {}): Promise { + return fetch(`${sharedServer().base}${path}`, { + ...init, + headers: sharedAuthHeaders(init.headers), + } as never); +} diff --git a/packages/kap-server/test/messages.test.ts b/packages/kap-server/test/messages.test.ts index 548d6a3bac8..6162210aa24 100644 --- a/packages/kap-server/test/messages.test.ts +++ b/packages/kap-server/test/messages.test.ts @@ -11,7 +11,7 @@ import { type ContextMessage, type ScopeSeed, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -47,7 +47,7 @@ describe('server-v2 /api/v1/sessions/{sid}/messages', () => { let base: string; let seeds: ScopeSeed | undefined; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-messages-')); const modelCatalog: IModelCatalog = { _serviceBrand: undefined, @@ -89,7 +89,7 @@ describe('server-v2 /api/v1/sessions/{sid}/messages', () => { base = `http://127.0.0.1:${server.port}`; } - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/meta.test.ts b/packages/kap-server/test/meta.test.ts index ef0606e8097..9fdb6cf195f 100644 --- a/packages/kap-server/test/meta.test.ts +++ b/packages/kap-server/test/meta.test.ts @@ -2,9 +2,10 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { IConfigService } from '@moonshot-ai/agent-core-v2'; import { IFeatureManager } from '@moonshot-ai/agent-core-v2/app/feature/featureManager'; import { getFeatureRecipes } from '@moonshot-ai/agent-core-v2/features/featureRegistry'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -19,6 +20,17 @@ describe('/api/v1/meta experimental_flags', () => { let server: RunningServer | undefined; let home: string | undefined; + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-meta-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + }); + beforeEach(() => { vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0'); vi.stubEnv('KIMI_CODE_EXPERIMENTAL_TOOL_SELECT', undefined); @@ -26,6 +38,9 @@ describe('/api/v1/meta experimental_flags', () => { afterEach(async () => { vi.unstubAllEnvs(); + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -37,18 +52,9 @@ describe('/api/v1/meta experimental_flags', () => { }); async function boot(toml?: string): Promise { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-meta-')); - if (toml !== undefined) { - await writeFile(join(home, 'config.toml'), toml, 'utf-8'); - } - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - return `http://127.0.0.1:${server.port}`; + await writeFile(join(home as string, 'config.toml'), toml ?? '', 'utf-8'); + await (server as RunningServer).core.accessor.get(IConfigService).reload(); + return `http://127.0.0.1:${(server as RunningServer).port}`; } async function getMetaFlags(base: string): Promise> { @@ -164,7 +170,18 @@ describe('/api/v1/meta features', () => { meta: Record; } - afterEach(async () => { + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-meta-features-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -176,15 +193,7 @@ describe('/api/v1/meta features', () => { }); async function boot(): Promise { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-meta-features-')); - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - return `http://127.0.0.1:${server.port}`; + return `http://127.0.0.1:${(server as RunningServer).port}`; } async function getMetaFeatures(base: string): Promise { diff --git a/packages/kap-server/test/modelCatalog.test.ts b/packages/kap-server/test/modelCatalog.test.ts index da7e1f4f26c..4393f1068be 100644 --- a/packages/kap-server/test/modelCatalog.test.ts +++ b/packages/kap-server/test/modelCatalog.test.ts @@ -13,7 +13,7 @@ import { type ModelCatalogConfig, type ScopeSeed, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -59,19 +59,39 @@ const CATALOG_TOML = [ describe('server-v2 /api/v1 model/provider catalog', () => { let server: RunningServer | undefined; + let active: RunningServer | undefined; + const alts: RunningServer[] = []; let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-model-catalog-')); process.env['KIMI_CODE_MODEL_CATALOG_REFRESH_ON_START'] = '0'; process.env['KIMI_CODE_MODEL_CATALOG_REFRESH_INTERVAL_MS'] = '0'; + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + active = server; + base = `http://127.0.0.1:${server.port}`; }); afterEach(async () => { + for (const alt of alts.splice(0)) { + await alt.close(); + } + active = server; + base = `http://127.0.0.1:${(server as RunningServer).port}`; + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; + active = undefined; } if (home !== undefined) { await rm(home, { recursive: true, force: true }); @@ -85,20 +105,27 @@ describe('server-v2 /api/v1 model/provider catalog', () => { if (toml !== undefined) { await writeFile(join(home as string, 'config.toml'), toml, 'utf-8'); } - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - seeds, - }); - base = `http://127.0.0.1:${server.port}`; + if (seeds !== undefined) { + const alt = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + seeds, + }); + alts.push(alt); + active = alt; + } else { + await (server as RunningServer).core.accessor.get(IConfigService).reload(); + active = server; + } + base = `http://127.0.0.1:${(active as RunningServer).port}`; } async function getJson(path: string): Promise<{ status: number; body: Envelope }> { const res = await fetch(`${base}${path}`, { - headers: authHeaders(server as RunningServer), + headers: authHeaders(active as RunningServer), } as never); return { status: res.status, body: (await res.json()) as Envelope }; } @@ -110,7 +137,7 @@ describe('server-v2 /api/v1 model/provider catalog', () => { const res = await fetch(`${base}${path}`, { method: 'POST', headers: authHeaders( - server as RunningServer, + active as RunningServer, body === undefined ? {} : { 'content-type': 'application/json' }, ), body: body === undefined ? undefined : JSON.stringify(body), diff --git a/packages/kap-server/test/modelCatalogCatalog.test.ts b/packages/kap-server/test/modelCatalogCatalog.test.ts index e37fdc09f60..854da0fabc8 100644 --- a/packages/kap-server/test/modelCatalogCatalog.test.ts +++ b/packages/kap-server/test/modelCatalogCatalog.test.ts @@ -2,8 +2,9 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { IConfigService } from '@moonshot-ai/agent-core-v2'; import { parse as parseToml } from 'smol-toml'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { resetModelsDevUpstreamForTest, @@ -124,16 +125,30 @@ describe('server-v2 /api/v1 catalog browse + import endpoints', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-catalog-')); process.env['KIMI_CODE_MODEL_CATALOG_REFRESH_ON_START'] = '0'; process.env['KIMI_CODE_MODEL_CATALOG_REFRESH_INTERVAL_MS'] = '0'; + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + base = `http://127.0.0.1:${server.port}`; + }); + + beforeEach(() => { resetModelsDevUpstreamForTest(); setModelsDevUpstreamForTest({ fetchImpl: catalogFetchOk() }); }); - afterEach(async () => { + afterEach(() => { resetModelsDevUpstreamForTest(); + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -147,17 +162,8 @@ describe('server-v2 /api/v1 catalog browse + import endpoints', () => { }); async function boot(toml?: string): Promise { - if (toml !== undefined) { - await writeFile(join(home as string, 'config.toml'), toml, 'utf-8'); - } - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - base = `http://127.0.0.1:${server.port}`; + await writeFile(join(home as string, 'config.toml'), toml ?? '', 'utf-8'); + await (server as RunningServer).core.accessor.get(IConfigService).reload(); } async function getJson(path: string): Promise<{ status: number; body: Envelope }> { diff --git a/packages/kap-server/test/modelCatalogProviderWrite.test.ts b/packages/kap-server/test/modelCatalogProviderWrite.test.ts index cc941ea55ff..a86bbe11e36 100644 --- a/packages/kap-server/test/modelCatalogProviderWrite.test.ts +++ b/packages/kap-server/test/modelCatalogProviderWrite.test.ts @@ -2,8 +2,9 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { IConfigService } from '@moonshot-ai/agent-core-v2'; import { parse as parseToml } from 'smol-toml'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -115,13 +116,21 @@ describe('server-v2 /api/v1 provider write endpoints', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-provider-write-')); process.env['KIMI_CODE_MODEL_CATALOG_REFRESH_ON_START'] = '0'; process.env['KIMI_CODE_MODEL_CATALOG_REFRESH_INTERVAL_MS'] = '0'; + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + }); + base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -135,17 +144,8 @@ describe('server-v2 /api/v1 provider write endpoints', () => { }); async function boot(toml?: string): Promise { - if (toml !== undefined) { - await writeFile(join(home as string, 'config.toml'), toml, 'utf-8'); - } - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - base = `http://127.0.0.1:${server.port}`; + await writeFile(join(home as string, 'config.toml'), toml ?? '', 'utf-8'); + await (server as RunningServer).core.accessor.get(IConfigService).reload(); } async function getJson(path: string): Promise<{ status: number; body: Envelope }> { diff --git a/packages/kap-server/test/openapi.test.ts b/packages/kap-server/test/openapi.test.ts index 20c9a13388e..7bbc4593f58 100644 --- a/packages/kap-server/test/openapi.test.ts +++ b/packages/kap-server/test/openapi.test.ts @@ -1,39 +1,11 @@ -import { mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; -import { afterEach, describe, expect, it } from 'vitest'; - -import { type RunningServer, startServer } from '../src/start'; -import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; -import { authHeaders } from './helpers/auth'; +import { sharedAuthHeaders, sharedServer } from './helpers/sharedServer'; describe('server-v2 OpenAPI', () => { - let server: RunningServer | undefined; - let home: string | undefined; - - afterEach(async () => { - if (server !== undefined) { - await server.close(); - server = undefined; - } - if (home !== undefined) { - await rm(home, { recursive: true, force: true }); - home = undefined; - } - }); - async function fetchOpenApi(): Promise> { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-openapi-')); - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - }); - const res = await fetch(`http://127.0.0.1:${server.port}/openapi.json`, { - headers: authHeaders(server), + const res = await fetch(`${sharedServer().base}/openapi.json`, { + headers: sharedAuthHeaders(), } as never); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toContain('application/json'); diff --git a/packages/kap-server/test/plugins.test.ts b/packages/kap-server/test/plugins.test.ts index 4fa9bad710f..7961ed15eb4 100644 --- a/packages/kap-server/test/plugins.test.ts +++ b/packages/kap-server/test/plugins.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { WebSocket } from 'ws'; @@ -83,10 +83,28 @@ describe('server-v2 /api/v1 plugins', () => { let server: RunningServer | undefined; let home: string | undefined; let base: string; + let custom = false; const createdDirs: string[] = []; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-plugins-')); + await bootDefault(); + }); + + async function bootDefault(): Promise { + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home!, + logLevel: 'silent', + pluginMarketplaceUrl: CATALOG_URL, + }); + base = `http://127.0.0.1:${server.port}`; + custom = false; + } + + beforeEach(async () => { const realFetch = globalThis.fetch; vi.stubGlobal( 'fetch', @@ -106,27 +124,26 @@ describe('server-v2 /api/v1 plugins', () => { return realFetch(url as never, init); }), ); - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - pluginMarketplaceUrl: CATALOG_URL, - }); - base = `http://127.0.0.1:${server.port}`; }); afterEach(async () => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); - if (server !== undefined) { - await server.close(); + if (custom) { + await server?.close(); server = undefined; + await bootDefault(); } for (const dir of createdDirs.splice(0)) { await rm(dir, { recursive: true, force: true }); } + }); + + afterAll(async () => { + if (server !== undefined) { + await server.close(); + server = undefined; + } if (home !== undefined) { await rm(home, { recursive: true, force: true, maxRetries: 3, retryDelay: 25 } as never); home = undefined; @@ -365,6 +382,7 @@ describe('server-v2 /api/v1 plugins', () => { logLevel: 'silent', }); base = `http://127.0.0.1:${server.port}`; + custom = true; const { body } = await call<{ entries: { id: string; capabilityId?: string }[] }>( 'GET', @@ -402,6 +420,8 @@ describe('server-v2 /api/v1 plugins', () => { expect(both.body.data.entries.find((e) => e.id === 'kimi-cu')?.installed?.version).toBe( expected, ); + await call('POST', '/api/v1/plugins/kimi-cu-win:remove'); + await call('POST', '/api/v1/plugins/kimi-cu:remove'); }); it('maps an unreachable marketplace to 50001', async () => { @@ -443,6 +463,7 @@ describe('server-v2 /api/v1 plugins', () => { pluginMarketplaceUrl: join(catalogDir, 'marketplace.json'), }); base = `http://127.0.0.1:${server.port}`; + custom = true; const { body } = await call<{ entries: { id: string; source: string }[] }>( 'GET', @@ -489,6 +510,7 @@ describe('server-v2 /api/v1 plugins', () => { logLevel: 'silent', }); base = `http://127.0.0.1:${server.port}`; + custom = true; const { body } = await call<{ entries: { @@ -551,6 +573,7 @@ describe('server-v2 /api/v1 plugins', () => { pluginMarketplaceUrl: '~/marketplace.json', }); base = `http://127.0.0.1:${server.port}`; + custom = true; const { body } = await call<{ entries: { id: string; source: string }[] }>( 'GET', diff --git a/packages/kap-server/test/prompts.test.ts b/packages/kap-server/test/prompts.test.ts index a305f871295..0bbd934fbac 100644 --- a/packages/kap-server/test/prompts.test.ts +++ b/packages/kap-server/test/prompts.test.ts @@ -14,6 +14,7 @@ import { IAgentStateService, IAgentToolPolicyService, IBootstrapService, + IConfigService, IFileService, ISessionContext, ISessionMetadata, @@ -21,7 +22,7 @@ import { closeSessionById, getLiveSessionById, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { projectPromptSnapshot, watchPromptSettlements } from '../src/routes/prompts'; @@ -193,14 +194,19 @@ describe('server-v2 /api/v1 prompts', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-prompts-')); await writeConfigToml(home, PROMPT_TOML); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + beforeEach(async () => { + await writeConfigToml(home as string, PROMPT_TOML); + await (server as RunningServer).core.accessor.get(IConfigService).reload(); + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -1537,39 +1543,44 @@ describe('server-v2 /api/v1 prompts', () => { }); it('binds a discovered custom agent profile on the first prompt', async () => { - await mkdir(join(home as string, 'agents'), { recursive: true }); - await writeFile( - join(home as string, 'agents', 'route-reviewer.md'), - [ - '---', - 'name: route-reviewer', - 'description: reviewer defined by a user-level agent file', - '---', - '', - 'You are a route-test reviewer.', - '', - ].join('\n'), - 'utf-8', - ); - const id = await createSession(home as string); - await createMainAgent(id); + const work = await mkdtemp(join(tmpdir(), 'kimi-server-v2-prompts-profile-')); + try { + await mkdir(join(home as string, 'agents'), { recursive: true }); + await writeFile( + join(home as string, 'agents', 'route-reviewer.md'), + [ + '---', + 'name: route-reviewer', + 'description: reviewer defined by a user-level agent file', + '---', + '', + 'You are a route-test reviewer.', + '', + ].join('\n'), + 'utf-8', + ); + const id = await createSession(work); + await createMainAgent(id); - const submitted = await call('POST', `/api/v1/sessions/${id}/prompts`, { - content: [{ type: 'text', text: 'hello' }], - profile: 'route-reviewer', - }); - expect(submitted.body.code).toBe(0); + const submitted = await call('POST', `/api/v1/sessions/${id}/prompts`, { + content: [{ type: 'text', text: 'hello' }], + profile: 'route-reviewer', + }); + expect(submitted.body.code).toBe(0); - const session = getLiveSessionById(server!.core.accessor, id); - if (session === undefined) throw new Error(`session ${id} not found`); - const main = session.accessor.get(IAgentLifecycleService).handleOf('main'); - expect(main?.accessor.get(IAgentProfileService).data().profileName).toBe('route-reviewer'); + const session = getLiveSessionById(server!.core.accessor, id); + if (session === undefined) throw new Error(`session ${id} not found`); + const main = session.accessor.get(IAgentLifecycleService).handleOf('main'); + expect(main?.accessor.get(IAgentProfileService).data().profileName).toBe('route-reviewer'); - const again = await call('POST', `/api/v1/sessions/${id}/prompts`, { - content: [{ type: 'text', text: 'again' }], - profile: 'route-reviewer', - }); - expect(again.body.code).toBe(0); + const again = await call('POST', `/api/v1/sessions/${id}/prompts`, { + content: [{ type: 'text', text: 'again' }], + profile: 'route-reviewer', + }); + expect(again.body.code).toBe(0); + } finally { + await rm(work, { recursive: true, force: true }); + } }); it('rejects switching to a different profile once bound', async () => { diff --git a/packages/kap-server/test/questions.test.ts b/packages/kap-server/test/questions.test.ts index a9eecc60437..fe1aad09e93 100644 --- a/packages/kap-server/test/questions.test.ts +++ b/packages/kap-server/test/questions.test.ts @@ -9,7 +9,7 @@ import { type QuestionRequest, type QuestionResult, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -69,7 +69,7 @@ describe('server-v2 /api/v1/sessions/{sid}/questions', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-questions-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -81,7 +81,7 @@ describe('server-v2 /api/v1/sessions/{sid}/questions', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/requestLogging.test.ts b/packages/kap-server/test/requestLogging.test.ts index 9526a1d5915..56913934fa8 100644 --- a/packages/kap-server/test/requestLogging.test.ts +++ b/packages/kap-server/test/requestLogging.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path'; import { Writable } from 'node:stream'; import { pino, type Logger } from 'pino'; -import { afterEach, assert, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, assert, describe, expect, it } from 'vitest'; import { extractEnvelopeCode } from '../src/requestLogging'; import { type RunningServer, startServer } from '../src/start'; @@ -36,8 +36,16 @@ function parseEntries(lines: string[]): Record[] { describe('requestLogging', () => { let server: RunningServer | undefined; let home: string | undefined; + let lines: string[]; - afterEach(async () => { + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-request-log-')); + const captured = captureLogger(); + lines = captured.lines; + server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logger: captured.logger }); + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -49,11 +57,7 @@ describe('requestLogging', () => { }); it('logs the envelope code instead of the HTTP status code', async () => { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-request-log-')); - const { logger, lines } = captureLogger(); - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logger }); - - const res = await fetch(`http://127.0.0.1:${String(server.port)}/api/v1/healthz`); + const res = await fetch(`http://127.0.0.1:${String(server!.port)}/api/v1/healthz`); expect(res.status).toBe(200); expect(((await res.json()) as { code: number }).code).toBe(0); diff --git a/packages/kap-server/test/rpc.test.ts b/packages/kap-server/test/rpc.test.ts index 76826efc65f..0a98ddbebdd 100644 --- a/packages/kap-server/test/rpc.test.ts +++ b/packages/kap-server/test/rpc.test.ts @@ -30,7 +30,7 @@ import type { WorkspaceInstanceSnapshot, } from '@moonshot-ai/agent-core-v2'; import { FakeRuntime } from '@moonshot-ai/agent-core-v2/runtime/fakeRuntime'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -69,13 +69,13 @@ describe('server-v2 /api/v1/debug RPC', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-rpc-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent', debugEndpoints: true }); base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -729,7 +729,7 @@ describe('server-v2 /api/v1/debug RPC auth', () => { let base: string; const token = 'test-secret-token'; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-rpc-auth-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -742,7 +742,7 @@ describe('server-v2 /api/v1/debug RPC auth', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -797,7 +797,7 @@ describe('server-v2 /api/v1/debug RPC (dev-only, whitelist-free)', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-debug-rpc-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -810,7 +810,7 @@ describe('server-v2 /api/v1/debug RPC (dev-only, whitelist-free)', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/search/searchRoute.test.ts b/packages/kap-server/test/search/searchRoute.test.ts index e8e92088190..ec657c597bd 100644 --- a/packages/kap-server/test/search/searchRoute.test.ts +++ b/packages/kap-server/test/search/searchRoute.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; process.env['KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER'] = '1'; import { ISessionIndex, type SessionSummary } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../../src/start'; import { TEST_HOST_IDENTITY } from '../helpers/hostIdentity'; @@ -63,7 +63,7 @@ describe('server-v2 /api/v1/search', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-search-')); const sessionDir = join(home, 'sessions', WS, 's1', 'agents', 'main'); await mkdir(sessionDir, { recursive: true }); @@ -117,7 +117,7 @@ describe('server-v2 /api/v1/search', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -213,12 +213,12 @@ describe('server-v2 session routes with the global search DB unavailable', () => let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-search-down-')); await writeFile(join(home, 'search-index'), 'not a minidb directory', 'utf8'); }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -230,6 +230,7 @@ describe('server-v2 session routes with the global search DB unavailable', () => }); async function boot(): Promise { + if (server !== undefined) return; server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', diff --git a/packages/kap-server/test/search/searchService.bench.ts b/packages/kap-server/test/search/searchService.bench.ts new file mode 100644 index 00000000000..d38c13765a8 --- /dev/null +++ b/packages/kap-server/test/search/searchService.bench.ts @@ -0,0 +1,235 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { monitorEventLoopDelay, performance, type IntervalHistogram } from 'node:perf_hooks'; + +import type { + IBootstrapService, + IFlagService, + ILogService, + ISessionIndex, + SessionSummary, +} from '@moonshot-ai/agent-core-v2'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + GlobalSearchService, + SEARCH_WORKER_FLAG_ID, + drainGlobalSearchDisposals, +} from '../../src/search/searchService'; + +const WS = 'ws_test'; + +const T1 = 1_700_000_000_000; + +function summary(id: string, title: string, updatedAt = T1): SessionSummary { + return { id, workspaceId: WS, title, createdAt: updatedAt, updatedAt, archived: false }; +} + +function makeBootstrap(home: string): IBootstrapService { + return { + homeDir: home, + scope: (name: string) => name, + } as unknown as IBootstrapService; +} + +function makeSessionIndex(list: ISessionIndex['listRecent']): ISessionIndex { + return { + _serviceBrand: undefined, + prepare: async () => ({ state: 'uninitialized', degradedCount: 0 }), + status: () => ({ state: 'uninitialized', degradedCount: 0 }), + listRecent: list, + get: async () => undefined, + count: async () => 0, + remove: async () => {}, + }; +} + +function staticIndex(summaries: SessionSummary[]): ISessionIndex { + return makeSessionIndex(async () => ({ items: summaries, nextCursor: undefined })); +} + +function userLine(text: string, time: number, origin?: unknown): string { + return JSON.stringify({ + type: 'context.append_message', + time, + message: { + role: 'user', + content: [{ type: 'text', text }], + origin: origin ?? { kind: 'user' }, + }, + }); +} + +function assistantLine(text: string, time: number): string { + return JSON.stringify({ + type: 'context.append_loop_event', + time, + event: { type: 'content.part', part: { type: 'text', text } }, + }); +} + +async function writeWire( + home: string, + sessionId: string, + agentId: string, + lines: string[], +): Promise { + const dir = join(home, 'sessions', WS, sessionId, 'agents', agentId); + await mkdir(dir, { recursive: true }); + const file = join(dir, 'wire.jsonl'); + await writeFile(file, lines.map((l) => `${l}\n`).join(''), 'utf8'); + return file; +} + +const noopLog = { + error: () => {}, + warn: () => {}, + info: () => {}, + debug: () => {}, +} as unknown as ILogService; + +function makeFlags(workerEnabled: boolean): IFlagService { + return { + enabled: (id: string) => id === SEARCH_WORKER_FLAG_ID && workerEnabled, + } as unknown as IFlagService; +} + +function makeService(home: string, index: ISessionIndex): GlobalSearchService { + const service = new GlobalSearchService(index, makeBootstrap(home), noopLog, makeFlags(true)); + service.syncDebounceMs = 0; + return service; +} + +describe('baseline: synthetic corpus', () => { + let home: string | undefined; + const services: GlobalSearchService[] = []; + + beforeEach(async () => { + home = await mkdtemp(join(tmpdir(), 'kimi-kap-search-baseline-')); + }); + + afterEach(async () => { + for (const service of services.splice(0)) service.dispose(); + await drainGlobalSearchDisposals(); + if (home !== undefined) { + await rm(home, { recursive: true, force: true }); + home = undefined; + } + }); + + const TOPICS = ['compaction', 'walrus', 'snapshot', 'recovery', '索引', '持久化']; + + async function writeCorpus(from: number, to: number): Promise { + const summaries: SessionSummary[] = []; + for (let i = from; i < to; i++) { + const id = `s${i}`; + summaries.push(summary(id, `session ${i} 索引讨论`, T1 + i)); + const lines: string[] = []; + for (let j = 0; j < 8; j++) { + lines.push(userLine(`session ${i} message ${j} about ${TOPICS[(i + j) % TOPICS.length]!}`, T1 + i * 100 + j)); + lines.push(assistantLine(`reply ${j} covering ${TOPICS[(i + 2 * j) % TOPICS.length]!}`, T1 + i * 100 + j + 1)); + } + await writeWire(home!, id, 'main', lines); + } + return summaries; + } + + async function medianMs(fn: () => Promise, runs = 5): Promise { + const times: number[] = []; + for (let r = 0; r < runs; r++) { + const t0 = performance.now(); + await fn(); + times.push(performance.now() - t0); + } + times.sort((a, b) => a - b); + return times[(times.length / 2) | 0]!; + } + + it('indexing and search latency scale within a linear budget from 100 to 400 sessions', async () => { + const all: SessionSummary[] = []; + const service = makeService(home!, staticIndex(all)); + services.push(service); + + all.push(...(await writeCorpus(0, 100))); + const t0 = performance.now(); + await service.reindex(); + const index100 = performance.now() - t0; + const terms100 = await medianMs(() => service.search({ query: 'compaction' })); + const literal100 = await medianMs(() => service.search({ query: 'message 3 about', mode: 'literal' })); + + all.push(...(await writeCorpus(100, 400))); + const t1 = performance.now(); + await service.reindex(); + const index400 = performance.now() - t1; + const terms400 = await medianMs(() => service.search({ query: 'compaction' })); + const literal400 = await medianMs(() => service.search({ query: 'message 3 about', mode: 'literal' })); + + const hits = await service.search({ query: 'compaction' }); + expect(hits.items.length).toBeGreaterThan(0); + expect((await service.search({ query: 'message 3 about', mode: 'literal' })).items.length).toBeGreaterThan(0); + + console.log( + `[baseline] searchService ${JSON.stringify({ + sessions: [100, 400], + reindexMs: [index100, index400], + termsMedianMs: [terms100, terms400], + literalMedianMs: [literal100, literal400], + })}`, + ); + expect(index400).toBeLessThan(index100 * 10 + 2000); + expect(terms400).toBeLessThan(terms100 * 10 + 100); + expect(literal400).toBeLessThan(literal100 * 10 + 100); + }, 120_000); + + it('stage-4: deep keyset pages cost like the first page, with a bounded event-loop pause', async () => { + const all: SessionSummary[] = []; + const service = makeService(home!, staticIndex(all)); + services.push(service); + all.push(...(await writeCorpus(0, 400))); + await service.reindex(); + + const eld: IntervalHistogram = monitorEventLoopDelay(); + eld.enable(); + try { + const tokens: (string | undefined)[] = [undefined]; + let page = await service.search({ query: 'message', sort: 'time_desc', pageSize: 20 }); + for (let p = 1; p < 10; p++) { + tokens.push(page.pageToken); + page = await service.search({ + query: 'message', + sort: 'time_desc', + pageSize: 20, + pageToken: page.pageToken, + }); + } + expect(page.items.length).toBe(20); + + const page1Ms = await medianMs(() => + service.search({ query: 'message', sort: 'time_desc', pageSize: 20 }), + ); + const page10Ms = await medianMs(() => + service.search({ query: 'message', sort: 'time_desc', pageSize: 20, pageToken: tokens[9] }), + ); + const literalMs = await medianMs(() => + service.search({ query: 'message 3 about', mode: 'literal' }), + ); + + const eldMaxMs = eld.max / 1e6; + const eldP99Ms = eld.percentile(99) / 1e6; + console.log( + `[baseline] stage4 ${JSON.stringify({ + sessions: 400, + page1MedianMs: page1Ms, + page10MedianMs: page10Ms, + literalMedianMs: literalMs, + eventLoopDelayMs: { p99: eldP99Ms, max: eldMaxMs }, + })}`, + ); + expect(page10Ms).toBeLessThan(page1Ms * 5 + 50); + expect(eldMaxMs).toBeLessThan(500); + } finally { + eld.disable(); + } + }, 120_000); +}); diff --git a/packages/kap-server/test/search/searchService.test.ts b/packages/kap-server/test/search/searchService.test.ts index dc9eb305ed6..58e10303b2d 100644 --- a/packages/kap-server/test/search/searchService.test.ts +++ b/packages/kap-server/test/search/searchService.test.ts @@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'; import { appendFile, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { monitorEventLoopDelay, performance, type IntervalHistogram } from 'node:perf_hooks'; +import { monitorEventLoopDelay, performance } from 'node:perf_hooks'; import { Worker } from 'node:worker_threads'; import type { @@ -2276,7 +2276,12 @@ describe('search worker host (stage 4)', () => { expect(degraded.indexState.state).toBe('building'); expect(degraded.indexState.degraded).toContain('worker'); - await new Promise((resolve) => setTimeout(resolve, 700)); + await vi.waitFor( + async () => { + expect((await hostOf(service).status()).readOnly).toBe(false); + }, + { timeout: 10_000 }, + ); await settleSync(service); const page = await service.search({ query: '苹果' }); expect(page.items.length).toBe(1); @@ -2321,9 +2326,13 @@ describe('search worker host (stage 4)', () => { await opening; await waitForGone(lockPath()); - await new Promise((resolve) => setTimeout(resolve, 700)); - const reopened = await host.ensureOpen(); - expect(reopened.readOnly).toBe(false); + await vi.waitFor( + async () => { + const reopened = await host.ensureOpen(); + expect(reopened.readOnly).toBe(false); + }, + { timeout: 10_000 }, + ); }); it('recovers a read-only open caused by an orphaned same-pid lock', { timeout: 30_000 }, async () => { @@ -2363,7 +2372,14 @@ describe('search worker host (stage 4)', () => { await host.ensureOpen(); const sync = host.sync(inputs); - await new Promise((resolve) => setTimeout(resolve, 20)); + await vi.waitFor( + () => { + expect( + (host as unknown as { requests: Map }).requests.size, + ).toBeGreaterThan(0); + }, + { timeout: 10_000 }, + ); host.beginClose(); const outcome = await sync; expect(outcome.noop).toBe(true); @@ -2400,9 +2416,13 @@ describe('search worker host (stage 4)', () => { await expect(wedged).rejects.toThrow(/timed out/); gate = false; - await new Promise((resolve) => setTimeout(resolve, 700)); - const status = await host.status(); - expect(status.readOnly).toBe(false); + await vi.waitFor( + async () => { + const status = await host.status(); + expect(status.readOnly).toBe(false); + }, + { timeout: 10_000 }, + ); }); it('rejects in-flight requests as disposed during a clean close', { timeout: 30_000 }, async () => { @@ -2454,7 +2474,12 @@ describe('search worker host (stage 4)', () => { expect(page1.pageToken).toBeDefined(); await hostOf(service).killWorkerForTest(); - await new Promise((resolve) => setTimeout(resolve, 700)); + await vi.waitFor( + async () => { + expect((await hostOf(service).status()).readOnly).toBe(false); + }, + { timeout: 10_000 }, + ); await settleSync(service); await expect( @@ -2876,7 +2901,12 @@ describe('search lifecycle diagnostics (stage 5)', () => { expect(down.state).toBe('degraded'); expect(down.detail).toContain('worker'); - await new Promise((resolve) => setTimeout(resolve, 700)); + await vi.waitFor( + async () => { + expect((await hostOf(service).status()).readOnly).toBe(false); + }, + { timeout: 10_000 }, + ); await settleSync(service); expect(service.lifecycleReport().state).toBe('ready'); expect((await service.search({ query: '苹果' })).items.length).toBe(1); @@ -2890,9 +2920,16 @@ describe('search lifecycle diagnostics (stage 5)', () => { expect(service.lifecycleReport().state).toBe('ready'); await hostOf(service).killWorkerForTest(); - await new Promise((resolve) => setTimeout(resolve, 700)); - const host = hostOf(service); + await vi.waitFor( + () => { + expect( + (host as unknown as { nextRetryAfter: number }).nextRetryAfter, + ).toBeLessThanOrEqual(Date.now()); + }, + { timeout: 10_000 }, + ); + const respawn = syncNow(service); respawn.catch(() => {}); await vi.waitFor( @@ -2955,135 +2992,3 @@ describe('search lifecycle diagnostics (stage 5)', () => { }); }); -describe('baseline: synthetic corpus', () => { - let home: string | undefined; - const services: GlobalSearchService[] = []; - - beforeEach(async () => { - home = await mkdtemp(join(tmpdir(), 'kimi-kap-search-baseline-')); - }); - - afterEach(async () => { - for (const service of services.splice(0)) service.dispose(); - await drainGlobalSearchDisposals(); - if (home !== undefined) { - await rm(home, { recursive: true, force: true }); - home = undefined; - } - }); - - const TOPICS = ['compaction', 'walrus', 'snapshot', 'recovery', '索引', '持久化']; - - async function writeCorpus(from: number, to: number): Promise { - const summaries: SessionSummary[] = []; - for (let i = from; i < to; i++) { - const id = `s${i}`; - summaries.push(summary(id, `session ${i} 索引讨论`, T1 + i)); - const lines: string[] = []; - for (let j = 0; j < 8; j++) { - lines.push(userLine(`session ${i} message ${j} about ${TOPICS[(i + j) % TOPICS.length]!}`, T1 + i * 100 + j)); - lines.push(assistantLine(`reply ${j} covering ${TOPICS[(i + 2 * j) % TOPICS.length]!}`, T1 + i * 100 + j + 1)); - } - await writeWire(home!, id, 'main', lines); - } - return summaries; - } - - async function medianMs(fn: () => Promise, runs = 5): Promise { - const times: number[] = []; - for (let r = 0; r < runs; r++) { - const t0 = performance.now(); - await fn(); - times.push(performance.now() - t0); - } - times.sort((a, b) => a - b); - return times[(times.length / 2) | 0]!; - } - - it('indexing and search latency scale within a linear budget from 100 to 400 sessions', async () => { - const all: SessionSummary[] = []; - const service = makeService(home!, staticIndex(all)); - services.push(service); - - all.push(...(await writeCorpus(0, 100))); - const t0 = performance.now(); - await service.reindex(); - const index100 = performance.now() - t0; - const terms100 = await medianMs(() => service.search({ query: 'compaction' })); - const literal100 = await medianMs(() => service.search({ query: 'message 3 about', mode: 'literal' })); - - all.push(...(await writeCorpus(100, 400))); - const t1 = performance.now(); - await service.reindex(); - const index400 = performance.now() - t1; - const terms400 = await medianMs(() => service.search({ query: 'compaction' })); - const literal400 = await medianMs(() => service.search({ query: 'message 3 about', mode: 'literal' })); - - const hits = await service.search({ query: 'compaction' }); - expect(hits.items.length).toBeGreaterThan(0); - expect((await service.search({ query: 'message 3 about', mode: 'literal' })).items.length).toBeGreaterThan(0); - - console.log( - `[baseline] searchService ${JSON.stringify({ - sessions: [100, 400], - reindexMs: [index100, index400], - termsMedianMs: [terms100, terms400], - literalMedianMs: [literal100, literal400], - })}`, - ); - expect(index400).toBeLessThan(index100 * 10 + 2000); - expect(terms400).toBeLessThan(terms100 * 10 + 100); - expect(literal400).toBeLessThan(literal100 * 10 + 100); - }, 120_000); - - it('stage-4: deep keyset pages cost like the first page, with a bounded event-loop pause', async () => { - const all: SessionSummary[] = []; - const service = makeService(home!, staticIndex(all)); - services.push(service); - all.push(...(await writeCorpus(0, 400))); - await service.reindex(); - - const eld: IntervalHistogram = monitorEventLoopDelay(); - eld.enable(); - try { - const tokens: (string | undefined)[] = [undefined]; - let page = await service.search({ query: 'message', sort: 'time_desc', pageSize: 20 }); - for (let p = 1; p < 10; p++) { - tokens.push(page.pageToken); - page = await service.search({ - query: 'message', - sort: 'time_desc', - pageSize: 20, - pageToken: page.pageToken, - }); - } - expect(page.items.length).toBe(20); - - const page1Ms = await medianMs(() => - service.search({ query: 'message', sort: 'time_desc', pageSize: 20 }), - ); - const page10Ms = await medianMs(() => - service.search({ query: 'message', sort: 'time_desc', pageSize: 20, pageToken: tokens[9] }), - ); - const literalMs = await medianMs(() => - service.search({ query: 'message 3 about', mode: 'literal' }), - ); - - const eldMaxMs = eld.max / 1e6; - const eldP99Ms = eld.percentile(99) / 1e6; - console.log( - `[baseline] stage4 ${JSON.stringify({ - sessions: 400, - page1MedianMs: page1Ms, - page10MedianMs: page10Ms, - literalMedianMs: literalMs, - eventLoopDelayMs: { p99: eldP99Ms, max: eldMaxMs }, - })}`, - ); - expect(page10Ms).toBeLessThan(page1Ms * 5 + 50); - expect(eldMaxMs).toBeLessThan(500); - } finally { - eld.disable(); - } - }, 120_000); -}); diff --git a/packages/kap-server/test/securityExposure.test.ts b/packages/kap-server/test/securityExposure.test.ts index 5e768083836..5d8444106af 100644 --- a/packages/kap-server/test/securityExposure.test.ts +++ b/packages/kap-server/test/securityExposure.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -11,11 +11,12 @@ describe('server-v2 exposure hardening hooks', () => { let server: RunningServer | undefined; let home: string | undefined; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-exposure-')); + server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -27,8 +28,7 @@ describe('server-v2 exposure hardening hooks', () => { }); it('rejects a disallowed Host header with 40301', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/healthz', headers: { host: 'evil.com' }, @@ -39,14 +39,12 @@ describe('server-v2 exposure hardening hooks', () => { }); it('allows the default loopback Host header', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ method: 'GET', url: '/api/v1/healthz' }); + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/healthz' }); expect(res.statusCode).toBe(200); }); it('echoes CORS headers for a same-origin request', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/healthz', headers: { origin: 'http://localhost:80', host: 'localhost:80' }, @@ -62,7 +60,7 @@ describe('server-v2 exposure hardening hooks', () => { }); it('sets security headers on a non-loopback bind without HSTS', async () => { - server = await startServer({ + const alt = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '0.0.0.0', port: 0, @@ -70,19 +68,22 @@ describe('server-v2 exposure hardening hooks', () => { logLevel: 'silent', insecureNoTls: true, }); - const res = await server.app.inject({ method: 'GET', url: '/api/v1/healthz' }); - expect(res.statusCode).toBe(200); - expect(res.headers['x-content-type-options']).toBe('nosniff'); - expect(res.headers['referrer-policy']).toBe('no-referrer'); - expect(res.headers['content-security-policy']).toBe( - "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'self'", - ); - expect(res.headers['strict-transport-security']).toBeUndefined(); + try { + const res = await alt.app.inject({ method: 'GET', url: '/api/v1/healthz' }); + expect(res.statusCode).toBe(200); + expect(res.headers['x-content-type-options']).toBe('nosniff'); + expect(res.headers['referrer-policy']).toBe('no-referrer'); + expect(res.headers['content-security-policy']).toBe( + "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'self'", + ); + expect(res.headers['strict-transport-security']).toBeUndefined(); + } finally { + await alt.close(); + } }); it('does not set security headers on a loopback bind', async () => { - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - const res = await server.app.inject({ method: 'GET', url: '/api/v1/healthz' }); + const res = await server!.app.inject({ method: 'GET', url: '/api/v1/healthz' }); expect(res.statusCode).toBe(200); expect(res.headers['x-content-type-options']).toBeUndefined(); expect(res.headers['referrer-policy']).toBeUndefined(); @@ -91,7 +92,7 @@ describe('server-v2 exposure hardening hooks', () => { }); it('does not register shutdown or terminal routes on non-loopback by default', async () => { - server = await startServer({ + const alt = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '0.0.0.0', port: 0, @@ -99,19 +100,23 @@ describe('server-v2 exposure hardening hooks', () => { logLevel: 'silent', insecureNoTls: true, }); - const token = server.authTokenService.getToken(); - const shutdown = await server.app.inject({ - method: 'POST', - url: '/api/v1/shutdown', - headers: { authorization: `Bearer ${token}` }, - }); - expect(shutdown.statusCode).toBe(404); + try { + const token = alt.authTokenService.getToken(); + const shutdown = await alt.app.inject({ + method: 'POST', + url: '/api/v1/shutdown', + headers: { authorization: `Bearer ${token}` }, + }); + expect(shutdown.statusCode).toBe(404); - const terminals = await server.app.inject({ - method: 'GET', - url: '/api/v1/sessions/missing/terminals', - headers: { authorization: `Bearer ${token}` }, - }); - expect(terminals.statusCode).toBe(404); + const terminals = await alt.app.inject({ + method: 'GET', + url: '/api/v1/sessions/missing/terminals', + headers: { authorization: `Bearer ${token}` }, + }); + expect(terminals.statusCode).toBe(404); + } finally { + await alt.close(); + } }); }); diff --git a/packages/kap-server/test/sessions.test.ts b/packages/kap-server/test/sessions.test.ts index 66c7921663a..220592fbcd9 100644 --- a/packages/kap-server/test/sessions.test.ts +++ b/packages/kap-server/test/sessions.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { inflateRawSync } from 'node:zlib'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { Error2, @@ -79,10 +79,11 @@ function goalContinuationStarts(events: readonly Event2[]): readonly Event2 describe('server-v2 /api/v1/sessions', () => { let server: RunningServer | undefined; + let baselineServer: RunningServer | undefined; let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-sessions-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -92,12 +93,20 @@ describe('server-v2 /api/v1/sessions', () => { logLevel: 'silent', debugEndpoints: true, }); + baselineServer = server; base = `http://127.0.0.1:${server.port}`; }); afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); + if (server !== baselineServer) { + await restartWithFreshHome(); + baselineServer = server; + } + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -109,6 +118,27 @@ describe('server-v2 /api/v1/sessions', () => { } }); + async function restartWithFreshHome(): Promise { + if (server !== undefined) { + await server.close(); + server = undefined; + } + if (home !== undefined) { + await new Promise((resolve) => setTimeout(resolve, 25)); + await rm(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 } as never); + } + home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-sessions-')); + server = await startServer({ + hostIdentity: TEST_HOST_IDENTITY, + host: '127.0.0.1', + port: 0, + homeDir: home, + logLevel: 'silent', + debugEndpoints: true, + }); + base = `http://127.0.0.1:${server.port}`; + } + async function postJson( path: string, body?: unknown, @@ -357,10 +387,10 @@ describe('server-v2 /api/v1/sessions', () => { const { body } = await postJson('/api/v1/sessions', { metadata: { cwd: missing } }); expect(body.code).toBe(40409); - const workspaces = await getJson<{ items: unknown[] }>('/api/v1/workspaces'); - expect(workspaces.body.data.items).toEqual([]); + const workspaces = await getJson<{ items: { root: string }[] }>('/api/v1/workspaces'); + expect(workspaces.body.data.items.some((w) => w.root === missing)).toBe(false); const sessions = await getJson('/api/v1/sessions'); - expect(sessions.body.data.items).toEqual([]); + expect(sessions.body.data.items.some((s) => s.metadata.cwd === missing)).toBe(false); }); it('rejects create when metadata.cwd is not a directory (40409)', async () => { @@ -484,6 +514,7 @@ describe('server-v2 /api/v1/sessions', () => { }); it('paginates sessions with before_id and terminates on the last page', async () => { + await restartWithFreshHome(); const cwd = home as string; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const ids: string[] = []; @@ -1098,7 +1129,7 @@ describe('server-v2 /api/v1/sessions', () => { ]); }); - it('cold-forks a session with hundreds of agents without materializing it', async () => { + it('cold-forks a session with hundreds of agents without materializing it', { timeout: 30_000 }, async () => { const cwd = home as string; const parent = await postJson('/api/v1/sessions', { metadata: { cwd } }); const parentId = parent.body.data.id; @@ -1325,6 +1356,7 @@ describe('server-v2 /api/v1/sessions', () => { }); it('paginates archived_only without returning empty filtered pages', async () => { + await restartWithFreshHome(); const cwd = home as string; const archivedOlder = await postJson('/api/v1/sessions', { metadata: { cwd } }); await postJson<{ archived: boolean }>( @@ -1416,6 +1448,7 @@ describe('server-v2 /api/v1/sessions', () => { }); it('lists the union of legacy split buckets for one workspace, in recency order', async () => { + await restartWithFreshHome(); const typedRoot = 'C:\\Users\\Foo\\Proj'; const lowerRoot = 'c:\\users\\foo\\proj'; const typedId = encodeWorkDirKey(typedRoot); @@ -1644,6 +1677,7 @@ describe('server-v2 /api/v1/sessions', () => { }); it('derives the session title from the first prompt submitted via /api/v1', async () => { + await restartWithFreshHome(); const cwd = home as string; await writeFile(join(cwd, 'config.toml'), [ 'default_model = "stub"', '', '[providers.stub]', 'type = "openai"', @@ -1726,7 +1760,7 @@ describe('server-v2 /api/v1/sessions status context window', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-status-')); await writeFile( join(home, 'config.toml'), @@ -1758,7 +1792,7 @@ describe('server-v2 /api/v1/sessions status context window', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -1832,7 +1866,7 @@ describe('server-v2 /api/v1/sessions (minidb read model)', () => { '', ].join('\n'); - beforeEach(async () => { + beforeAll(async () => { process.env[READ_MODEL_ENV] = '1'; home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-sessions-rm-')); await writeFile(join(home, 'config.toml'), READ_MODEL_CONFIG, 'utf8'); @@ -1847,7 +1881,7 @@ describe('server-v2 /api/v1/sessions (minidb read model)', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { process.env[READ_MODEL_ENV] = 'false'; if (server !== undefined) { await server.close(); diff --git a/packages/kap-server/test/skills.test.ts b/packages/kap-server/test/skills.test.ts index 54638a00dba..f4b8c1db707 100644 --- a/packages/kap-server/test/skills.test.ts +++ b/packages/kap-server/test/skills.test.ts @@ -10,7 +10,7 @@ import { activateSkillResultSchema, listSkillsResponseSchema, } from '../src/protocol/rest-skill'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -37,13 +37,13 @@ describe('server-v2 /api/v1 skills', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-skills-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -402,7 +402,7 @@ describe('server-v2 /api/v1 skills', () => { expect(body.code).toBe(40415); const sessionTree = await readdir(join(home as string, 'sessions'), { recursive: true }); - expect(sessionTree.filter((entry) => entry.includes('attachments'))).toEqual([]); + expect(sessionTree.filter((entry) => entry.includes(id) && entry.includes('attachments'))).toEqual([]); }); }); diff --git a/packages/kap-server/test/snapshot.test.ts b/packages/kap-server/test/snapshot.test.ts index 5a53bcfa69d..bee4ffb9105 100644 --- a/packages/kap-server/test/snapshot.test.ts +++ b/packages/kap-server/test/snapshot.test.ts @@ -28,7 +28,7 @@ import { } from '@moonshot-ai/agent-core-v2'; import { sessionSnapshotResponseSchema } from '../src/protocol/rest-snapshot'; import { emptySessionUsage } from '../src/protocol/session'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { registerSnapshotRoutes } from '../src/routes/snapshot'; import { type RunningServer, startServer } from '../src/start'; @@ -362,13 +362,13 @@ describe('server-v2 GET /api/v1/sessions/:id/snapshot', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-snapshot-test-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/tasks.test.ts b/packages/kap-server/test/tasks.test.ts index 55a68889e61..bc3cecf9834 100644 --- a/packages/kap-server/test/tasks.test.ts +++ b/packages/kap-server/test/tasks.test.ts @@ -9,7 +9,7 @@ import { IModelCatalog, type AgentTask, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -50,7 +50,7 @@ describe('server-v2 /api/v1/sessions/{sid}/tasks', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-tasks-')); const modelCatalog: IModelCatalog = { _serviceBrand: undefined, @@ -87,7 +87,7 @@ describe('server-v2 /api/v1/sessions/{sid}/tasks', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/terminals.test.ts b/packages/kap-server/test/terminals.test.ts index 6a51b2a188b..730f1cb6883 100644 --- a/packages/kap-server/test/terminals.test.ts +++ b/packages/kap-server/test/terminals.test.ts @@ -12,7 +12,7 @@ import { } from '@moonshot-ai/agent-core-v2'; import { ErrorCode } from '../src/protocol/error-codes'; import type { Terminal } from '@moonshot-ai/agent-core-v2/os/interface/terminal'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -90,11 +90,8 @@ describe('server-v2 /api/v1/sessions/{sid}/terminals', () => { let work: string | undefined; let base: string; - beforeEach(async () => { - spawnOptions.length = 0; - processes.length = 0; + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-term-home-')); - work = await mkdtemp(join(tmpdir(), 'kimi-server-v2-term-work-')); await writeFile( join(home, 'config.toml'), [ @@ -120,7 +117,20 @@ describe('server-v2 /api/v1/sessions/{sid}/terminals', () => { base = `http://127.0.0.1:${server.port}`; }); + beforeEach(async () => { + spawnOptions.length = 0; + processes.length = 0; + work = await mkdtemp(join(tmpdir(), 'kimi-server-v2-term-work-')); + }); + afterEach(async () => { + if (work !== undefined) { + await rm(work, { recursive: true, force: true }); + work = undefined; + } + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -129,10 +139,6 @@ describe('server-v2 /api/v1/sessions/{sid}/terminals', () => { await rm(home, { recursive: true, force: true }); home = undefined; } - if (work !== undefined) { - await rm(work, { recursive: true, force: true }); - work = undefined; - } }); async function createSession(cwd: string): Promise { diff --git a/packages/kap-server/test/tools.test.ts b/packages/kap-server/test/tools.test.ts index a40a01494f4..a2c4005a93a 100644 --- a/packages/kap-server/test/tools.test.ts +++ b/packages/kap-server/test/tools.test.ts @@ -14,7 +14,7 @@ import { listMcpServersResponseSchema, listToolsResponseSchema, } from '../src/protocol/rest-tool'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -41,7 +41,7 @@ describe('server-v2 /api/v1 tools + mcp', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-tools-')); const modelCatalog: IModelCatalog = { _serviceBrand: undefined, @@ -78,7 +78,7 @@ describe('server-v2 /api/v1 tools + mcp', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/transcript.test.ts b/packages/kap-server/test/transcript.test.ts index 631f6018310..d7cc0db5b50 100644 --- a/packages/kap-server/test/transcript.test.ts +++ b/packages/kap-server/test/transcript.test.ts @@ -18,7 +18,7 @@ import { type Event2, type ScopeSeed, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -124,7 +124,7 @@ describe('server-v2 /api/v1/sessions/{sid}/transcript', () => { let base: string; let seeds: ScopeSeed | undefined; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-transcript-')); const modelCatalog: IModelCatalog = { _serviceBrand: undefined, @@ -166,7 +166,7 @@ describe('server-v2 /api/v1/sessions/{sid}/transcript', () => { base = `http://127.0.0.1:${server.port}`; } - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/transcriptContract.e2e.test.ts b/packages/kap-server/test/transcriptContract.e2e.test.ts index 1e5af24d4b7..02537dcca89 100644 --- a/packages/kap-server/test/transcriptContract.e2e.test.ts +++ b/packages/kap-server/test/transcriptContract.e2e.test.ts @@ -4,10 +4,11 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { WebSocket, type RawData } from 'ws'; import { IAgentLifecycleService, + IConfigService, MAIN_AGENT_ID, getLiveSessionById, resumeSessionById, @@ -242,21 +243,28 @@ describe('transcript contract e2e', () => { let llm: MockLlm | undefined; let base: string; + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), 'kimi-transcript-contract-')); + server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); + base = `http://127.0.0.1:${server.port}`; + }); + afterEach(async () => { await llm?.close(); + llm = undefined; + }); + + afterAll(async () => { await server?.close(); + server = undefined; if (home !== undefined) await rm(home, { recursive: true, force: true }); home = undefined; - server = undefined; - llm = undefined; }); async function boot(routes: readonly LlmRoute[]): Promise { llm = await startMockLlm(routes); - home = await mkdtemp(join(tmpdir(), 'kimi-transcript-contract-')); - await writeFile(join(home, 'config.toml'), configToml(llm.port), 'utf-8'); - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - base = `http://127.0.0.1:${server.port}`; + await writeFile(join(home!, 'config.toml'), configToml(llm.port), 'utf-8'); + await server!.core.accessor.get(IConfigService).reload(); } const idle = (server: RunningServer, base: string, sid: string) => diff --git a/packages/kap-server/test/v2Sessions.test.ts b/packages/kap-server/test/v2Sessions.test.ts index 7fe815dda87..c32044eb9f2 100644 --- a/packages/kap-server/test/v2Sessions.test.ts +++ b/packages/kap-server/test/v2Sessions.test.ts @@ -20,7 +20,7 @@ import { type FsPullRequest, IGitService, } from '@moonshot-ai/agent-core-v2/app/git/git'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { mapActivityStatus } from '../src/routes/v2/sessions'; @@ -161,10 +161,17 @@ describe('server /api/v2/sessions', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-sessions-list-')); + await bootSeeded(); + }); + + beforeEach(() => { gitState.calls = []; gitState.responses = new Map(); - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-sessions-list-')); + }); + + async function bootSeeded(): Promise { server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', @@ -177,9 +184,9 @@ describe('server /api/v2/sessions', () => { ], }); base = `http://127.0.0.1:${server.port}`; - }); + } - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -285,6 +292,10 @@ describe('server /api/v2/sessions', () => { const page = await getData(); const item = page.items.find((entry) => entry.id === id); expect(item?.activity).toEqual({ status: 'idle', model: 'stub' }); + + await rm(join(home as string, 'config.toml'), { force: true }); + await (server as RunningServer).close(); + await bootSeeded(); }); it('filters by workspace.id (single, repeated OR, unknown)', async () => { @@ -553,6 +564,8 @@ describe('server /api/v2/sessions', () => { }); it('degrades non-git cwds to null fields without failing the request', async () => { + await (server as RunningServer).close(); + await bootSeeded(); const page = await getData('?include=git&meta.archived=all'); for (const item of page.items) { expect(item.git).toEqual({ branch: null, pull_request: null }); @@ -690,6 +703,8 @@ describe('server /api/v2/sessions', () => { }); it('supports the ids projection and include=git inside groups', async () => { + await (server as RunningServer).close(); + await bootSeeded(); const projected = await getGroupData('?view=by_workspace&fields=id,archived'); expect(projected.groups[0]?.sessions).toEqual([ { id: 's1', archived: false }, @@ -786,7 +801,7 @@ describe('server /api/v2/sessions batch archive/restore', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-sessions-batch-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -798,8 +813,11 @@ describe('server /api/v2/sessions batch archive/restore', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterEach(() => { vi.restoreAllMocks(); + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/workspaceFs.test.ts b/packages/kap-server/test/workspaceFs.test.ts index 2c674c5c34c..4092e82b8fc 100644 --- a/packages/kap-server/test/workspaceFs.test.ts +++ b/packages/kap-server/test/workspaceFs.test.ts @@ -2,7 +2,7 @@ import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'; import { homedir, tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { type RunningServer, startServer } from '../src/start'; import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; @@ -39,7 +39,7 @@ describe('server-v2 /api/v1 fs folder picker', () => { let instancesDir: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fs-')); instancesDir = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fs-instances-')); server = await startServer({ @@ -53,7 +53,7 @@ describe('server-v2 /api/v1 fs folder picker', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -108,7 +108,7 @@ describe('server-v2 /api/v1 fs folder picker', () => { }); it('lists only directories and filters files', async () => { - const root = home as string; + const root = await mkdtemp(join(home as string, 'browse-filter-')); await mkdir(join(root, 'alpha')); await mkdir(join(root, 'beta')); await writeFile(join(root, 'README.md'), 'hi'); @@ -127,7 +127,7 @@ describe('server-v2 /api/v1 fs folder picker', () => { }); it('sorts dot-directories after regular ones', async () => { - const root = home as string; + const root = await mkdtemp(join(home as string, 'browse-dots-')); await mkdir(join(root, '.zeta')); await mkdir(join(root, 'alpha')); @@ -183,7 +183,7 @@ describe('server-v2 /api/v1 fs:mkdir', () => { let instancesDir: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fsmkdir-')); instancesDir = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fsmkdir-instances-')); server = await startServer({ @@ -197,7 +197,7 @@ describe('server-v2 /api/v1 fs:mkdir', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -285,7 +285,7 @@ describe('server-v2 /api/v1 fs:content', () => { let instancesDir: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fscontent-')); instancesDir = await mkdtemp(join(tmpdir(), 'kimi-server-v2-fscontent-instances-')); server = await startServer({ @@ -299,7 +299,7 @@ describe('server-v2 /api/v1 fs:content', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/workspaceLayout.test.ts b/packages/kap-server/test/workspaceLayout.test.ts index 8fea23d4426..4304b5246fa 100644 --- a/packages/kap-server/test/workspaceLayout.test.ts +++ b/packages/kap-server/test/workspaceLayout.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { IAgentLifecycleService, @@ -27,7 +27,7 @@ describe('local/local on-disk layout (byte compatibility)', () => { let base: string; const homes: string[] = []; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-layout-home-')); workDir = await mkdtemp(join(tmpdir(), 'kimi-layout-work-')); homes.push(home, workDir); @@ -42,7 +42,7 @@ describe('local/local on-disk layout (byte compatibility)', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/workspaces.test.ts b/packages/kap-server/test/workspaces.test.ts index 486d591dccf..b09511f66ce 100644 --- a/packages/kap-server/test/workspaces.test.ts +++ b/packages/kap-server/test/workspaces.test.ts @@ -2,7 +2,7 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { encodeWorkDirKey } from '@moonshot-ai/agent-core-v2/_base/utils/workdir-slug'; @@ -43,7 +43,7 @@ describe('server-v2 /api/v1/workspaces', () => { let home: string | undefined; let base: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-workspaces-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -55,7 +55,7 @@ describe('server-v2 /api/v1/workspaces', () => { base = `http://127.0.0.1:${server.port}`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; @@ -245,11 +245,13 @@ describe('server-v2 /api/v1/workspaces', () => { await seedBucket(typedId, 's-typed', {}); await seedBucket(lowerId, 's-lower', { archived: true, updatedAt: 2 }); - const { body } = await getJson('/api/v1/workspaces'); - expect(body.code).toBe(0); - expect(body.data.items).toHaveLength(1); - expect([typedId, lowerId]).toContain(body.data.items[0]?.id); - expect(body.data.items[0]?.session_count).toBe(2); + await vi.waitFor(async () => { + const { body } = await getJson('/api/v1/workspaces'); + expect(body.code).toBe(0); + const unions = body.data.items.filter((w) => [typedId, lowerId].includes(w.id)); + expect(unions).toHaveLength(1); + expect(unions[0]?.session_count).toBe(2); + }); }); it('adds an additional directory and persists it by default', async () => { @@ -274,7 +276,7 @@ describe('server-v2 /api/v1/workspaces', () => { }); it('adds a relative directory without persisting when persist is false', async () => { - const root = home as string; + const root = await mkdtemp(join(tmpdir(), 'kimi-server-v2-workspaces-rel-')); const extra = join(root, 'extra-rel'); await mkdir(extra); const created = await postJson('/api/v1/workspaces', { root }); @@ -288,6 +290,7 @@ describe('server-v2 /api/v1/workspaces', () => { expect(body.data.persisted).toBe(false); expect(body.data.additional_dirs).toContain(extra); await expect(readFile(body.data.config_path, 'utf8')).rejects.toThrow(); + await rm(root, { recursive: true, force: true }); }); it('returns 40410 when adding a directory to an unknown workspace', async () => { diff --git a/packages/kap-server/test/wsBearerProtocol.test.ts b/packages/kap-server/test/wsBearerProtocol.test.ts index bfc810d39aa..83bbcaf0043 100644 --- a/packages/kap-server/test/wsBearerProtocol.test.ts +++ b/packages/kap-server/test/wsBearerProtocol.test.ts @@ -1,13 +1,8 @@ -import { mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; - -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket from 'ws'; -import { type RunningServer, startServer } from '../src/start'; -import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; import { WS_BEARER_PROTOCOL_PREFIX } from '../src/transport/ws/bearerProtocol'; +import { sharedServer } from './helpers/sharedServer'; function openWs(url: string, protocols: string | string[]): Promise { return new Promise((resolve, reject) => { @@ -18,39 +13,24 @@ function openWs(url: string, protocols: string | string[]): Promise { } describe('server-v2 WS bearer subprotocol', () => { - let server: RunningServer | undefined; - let home: string | undefined; - let wsUrl: string; const sockets: WebSocket[] = []; - beforeEach(async () => { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-ws-bearer-')); - server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); - wsUrl = `ws://127.0.0.1:${server.port}/api/v1/ws`; - }); - - afterEach(async () => { + afterEach(() => { for (const ws of sockets.splice(0)) { ws.close(); } - if (server !== undefined) { - await server.close(); - server = undefined; - } - if (home !== undefined) { - await rm(home, { recursive: true, force: true }); - home = undefined; - } }); it('accepts a valid bearer subprotocol', async () => { - const token = server?.authTokenService.getToken() ?? ''; + const token = sharedServer().token; + const wsUrl = `${sharedServer().base.replace(/^http/, 'ws')}/api/v1/ws`; const ws = await openWs(wsUrl, `${WS_BEARER_PROTOCOL_PREFIX}${token}`); sockets.push(ws); expect(ws.protocol).toBe(`${WS_BEARER_PROTOCOL_PREFIX}${token}`); }); it('rejects an invalid bearer subprotocol', async () => { + const wsUrl = `${sharedServer().base.replace(/^http/, 'ws')}/api/v1/ws`; await expect(openWs(wsUrl, `${WS_BEARER_PROTOCOL_PREFIX}wrong-token`)).rejects.toThrow(); }); }); diff --git a/packages/kap-server/test/wsHostOrigin.test.ts b/packages/kap-server/test/wsHostOrigin.test.ts index d5cd2eb8458..de63f1b3de0 100644 --- a/packages/kap-server/test/wsHostOrigin.test.ts +++ b/packages/kap-server/test/wsHostOrigin.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { WebSocket } from 'ws'; import { type RunningServer, startServer } from '../src/start'; @@ -52,7 +52,7 @@ describe('WS upgrade Host/Origin checks', () => { let v1Url: string; const sockets: WebSocket[] = []; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-ws-host-origin-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, @@ -65,13 +65,16 @@ describe('WS upgrade Host/Origin checks', () => { v1Url = `ws://127.0.0.1:${server.port}/api/v1/ws`; }); - afterEach(async () => { + afterEach(() => { for (const ws of sockets.splice(0)) { try { ws.close(); } catch { } } + }); + + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/test/wsUpgradeAuth.test.ts b/packages/kap-server/test/wsUpgradeAuth.test.ts index 612b6dec94d..2ca397e2f4a 100644 --- a/packages/kap-server/test/wsUpgradeAuth.test.ts +++ b/packages/kap-server/test/wsUpgradeAuth.test.ts @@ -1,15 +1,7 @@ -import { mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; - -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { WebSocket, type RawData } from 'ws'; -import { type RunningServer, startServer } from '../src/start'; -import { TEST_HOST_IDENTITY } from './helpers/hostIdentity'; -import { fixedTokenAuth } from './helpers/fixedAuth'; - -const TOKEN = 'test-token'; +import { sharedServer } from './helpers/sharedServer'; function rawToString(data: RawData): string { if (typeof data === 'string') return data; @@ -61,57 +53,41 @@ function expectRejected(url: string, opts?: ConnectOptions): Promise { } describe('WS upgrade auth', () => { - let server: RunningServer | undefined; - let home: string | undefined; - let v1Url: string; const sockets: WebSocket[] = []; - beforeEach(async () => { - home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-ws-upgrade-auth-')); - server = await startServer({ - hostIdentity: TEST_HOST_IDENTITY, - host: '127.0.0.1', - port: 0, - homeDir: home, - logLevel: 'silent', - authTokenService: fixedTokenAuth(TOKEN), - }); - v1Url = `ws://127.0.0.1:${server.port}/api/v1/ws`; - }); - - afterEach(async () => { + afterEach(() => { for (const ws of sockets.splice(0)) { try { ws.close(); } catch { } } - if (server !== undefined) { - await server.close(); - server = undefined; - } - if (home !== undefined) { - await rm(home, { recursive: true, force: true }); - home = undefined; - } }); + function v1Url(): string { + return `${sharedServer().base.replace(/^http/, 'ws')}/api/v1/ws`; + } + + function token(): string { + return sharedServer().token; + } + describe('/api/v1/ws', () => { const firstType = 'server_hello'; - const url = (): string => v1Url; + const url = (): string => v1Url(); it('accepts a valid bearer subprotocol and echoes it', async () => { const { ws, firstFrame } = await openConn(url(), { - protocols: [`kimi-code.bearer.${TOKEN}`], + protocols: [`kimi-code.bearer.${token()}`], }); sockets.push(ws); - expect(ws.protocol).toBe(`kimi-code.bearer.${TOKEN}`); + expect(ws.protocol).toBe(`kimi-code.bearer.${token()}`); expect(firstFrame).toMatchObject({ type: firstType }); }); it('accepts a valid Authorization bearer header', async () => { const { ws, firstFrame } = await openConn(url(), { - headers: { Authorization: `Bearer ${TOKEN}` }, + headers: { Authorization: `Bearer ${token()}` }, }); sockets.push(ws); expect(firstFrame).toMatchObject({ type: firstType }); @@ -127,7 +103,7 @@ describe('WS upgrade auth', () => { }); it('rejects upgrades to a non-WS path', async () => { - const badUrl = `ws://127.0.0.1:${(server as RunningServer).port}/api/v1/other`; - await expectRejected(badUrl, { protocols: [`kimi-code.bearer.${TOKEN}`] }); + const badUrl = `${v1Url().replace('/api/v1/ws', '/api/v1/other')}`; + await expectRejected(badUrl, { protocols: [`kimi-code.bearer.${token()}`] }); }); }); diff --git a/packages/kap-server/test/wsV1Resync.test.ts b/packages/kap-server/test/wsV1Resync.test.ts index 32417e346b1..2bef30a62a0 100644 --- a/packages/kap-server/test/wsV1Resync.test.ts +++ b/packages/kap-server/test/wsV1Resync.test.ts @@ -8,7 +8,7 @@ import { IAgentLifecycleService, getLiveSessionById, } from '@moonshot-ai/agent-core-v2'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { WebSocket } from 'ws'; import { type RunningServer, startServer } from '../src/start'; @@ -105,14 +105,14 @@ describe('server-v2 /api/v1/ws resync', () => { let base: string; let wsUrl: string; - beforeEach(async () => { + beforeAll(async () => { home = await mkdtemp(join(tmpdir(), 'kimi-wsv1-test-')); server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logLevel: 'silent' }); base = `http://127.0.0.1:${server.port}`; wsUrl = `ws://127.0.0.1:${server.port}/api/v1/ws`; }); - afterEach(async () => { + afterAll(async () => { if (server !== undefined) { await server.close(); server = undefined; diff --git a/packages/kap-server/vitest.bench.config.ts b/packages/kap-server/vitest.bench.config.ts new file mode 100644 index 00000000000..f35a9cf325d --- /dev/null +++ b/packages/kap-server/vitest.bench.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'vitest/config'; + +import { rawTextPlugin } from '../../build/raw-text-plugin.mjs'; + +export default defineConfig({ + plugins: [rawTextPlugin()], + test: { + name: 'kap-server-bench', + include: ['test/**/*.bench.ts'], + setupFiles: ['test/setup.ts'], + }, +}); diff --git a/packages/kap-server/vitest.config.ts b/packages/kap-server/vitest.config.ts index 8580fc92fb5..569f81a563c 100644 --- a/packages/kap-server/vitest.config.ts +++ b/packages/kap-server/vitest.config.ts @@ -10,5 +10,7 @@ export default defineConfig({ name: 'kap-server', include: ['test/**/*.{test,e2e}.ts'], setupFiles: ['test/setup.ts'], + globalSetup: ['test/globalSetup.ts'], + testTimeout: 15_000, }, }); diff --git a/vitest.config.ts b/vitest.config.ts index fd951acb089..de40fc42cae 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,7 +3,7 @@ import { vscodeProjects } from './apps/vscode/vitest.projects'; export default defineConfig({ test: { - projects: ['packages/*', 'apps/kimi-code', ...vscodeProjects], + projects: ['packages/*', '!packages/minidb', 'apps/kimi-code', ...vscodeProjects], coverage: { provider: 'v8', include: ['packages/*/src/**/*.ts', 'apps/*/src/**/*.ts'], From a3b48a7272880dafb64e4c403006d94dc781d05c Mon Sep 17 00:00:00 2001 From: 7Sageer Date: Thu, 3 Sep 2026 14:57:24 +0800 Subject: [PATCH 02/19] fix(kimi-code): honor KIMI_DISABLE_TELEMETRY and restore crash telemetry in v2 print mode (#3498) * fix(kimi-code): honor KIMI_DISABLE_TELEMETRY and restore crash telemetry in v2 print mode * fix(kimi-code): attribute v2 print crash telemetry to the resolved session model --- .../print-mode-telemetry-disable-env.md | 5 + apps/kimi-code/src/cli/v2/run-v2-print.ts | 45 ++++++- apps/kimi-code/test/cli/v2-run-print.test.ts | 124 ++++++++++++++++-- packages/telemetry/src/index.ts | 14 +- packages/telemetry/src/sink.ts | 4 + packages/telemetry/test/telemetry.test.ts | 59 ++++++++- 6 files changed, 236 insertions(+), 15 deletions(-) create mode 100644 .changeset/print-mode-telemetry-disable-env.md diff --git a/.changeset/print-mode-telemetry-disable-env.md b/.changeset/print-mode-telemetry-disable-env.md new file mode 100644 index 00000000000..9efd39f7540 --- /dev/null +++ b/.changeset/print-mode-telemetry-disable-env.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/kimi-code": patch +--- + +Fix print mode (`kimi -p`) ignoring the `KIMI_DISABLE_TELEMETRY` environment variable. diff --git a/apps/kimi-code/src/cli/v2/run-v2-print.ts b/apps/kimi-code/src/cli/v2/run-v2-print.ts index c22f0a68a2c..f329c0e06c2 100644 --- a/apps/kimi-code/src/cli/v2/run-v2-print.ts +++ b/apps/kimi-code/src/cli/v2/run-v2-print.ts @@ -56,7 +56,19 @@ import { type PrintBackgroundMode, type Scope, } from '@moonshot-ai/agent-core-v2'; -import { createKimiDefaultHeaders, createKimiDeviceId } from '@moonshot-ai/kimi-code-oauth'; +import { + createKimiDefaultHeaders, + createKimiDeviceId, + KIMI_CODE_PROVIDER_NAME, +} from '@moonshot-ai/kimi-code-oauth'; +import { + initializeTelemetry, + setCrashPhase, + setTelemetryContext, + setTelemetryModel, + shouldEnableTelemetry, + shutdownTelemetry, +} from '@moonshot-ai/kimi-telemetry'; import type { GoalUpdated } from '@moonshot-ai/agent-core-v2/features/goal/goalOps'; import type { TurnEnded } from '@moonshot-ai/agent-core-v2/agent/loop/turnOps'; import type { @@ -78,6 +90,7 @@ import { CLI_USER_AGENT_PRODUCT, PROMPT_CLEANUP_TIMEOUT_MS, } from '#/constant/app'; +import { currentKimiProfile } from '#/utils/region'; import { formatGoalSummaryText, @@ -169,12 +182,13 @@ export async function runV2Print( // user left unset are filled, in the memory layer. await applyPrintModeConfigDefaults(configService); const defaultModel = configService.get('defaultModel') ?? undefined; - let telemetryEnabled = true; + let configTelemetryEnabled = true; try { - telemetryEnabled = configService.get('telemetry') !== false; + configTelemetryEnabled = configService.get('telemetry') !== false; } catch { - telemetryEnabled = true; + configTelemetryEnabled = true; } + const telemetryEnabled = shouldEnableTelemetry({ enabled: configTelemetryEnabled }); for (const diagnostic of configService.diagnostics()) { if (diagnostic.severity === 'warning') { stderr.write(`Warning: ${diagnostic.message}\n`); @@ -188,12 +202,14 @@ export async function runV2Print( const cleanup = async (): Promise => { const pending = (cleanupPromise ??= (async () => { removeTerminationCleanup?.(); + setCrashPhase('shutdown'); try { await restorePermission(); } finally { if (telemetryService !== undefined) { await raceWithTimeout(telemetryService.shutdown(), CLI_SHUTDOWN_TIMEOUT_MS); } + await shutdownTelemetry({ timeoutMs: CLI_SHUTDOWN_TIMEOUT_MS }).catch(() => {}); app.dispose(); } })()); @@ -206,7 +222,10 @@ export async function runV2Print( // `session_load_failed` fire inside create()/resume(), so an appender wired // up only after resolveNativeSession() would drop them to the null appender. // The model below is the best known up front; a resumed session's real - // model is reconciled via setContext once resolved. + // model is reconciled once resolved (v2 via setContext, v1 via + // setTelemetryModel). The v1 pipeline is initialized here too: the + // process-wide crash handlers report through its default client, so its + // sink must be attached before the run can crash. telemetryService = app.accessor.get(ITelemetryService); if (telemetryEnabled) { telemetryService.addAppender( @@ -218,12 +237,28 @@ export async function runV2Print( getAccessToken: async () => (await auth.getCachedAccessToken()) ?? null, }), ); + // No `first_launch` on the v1 client: the v2 side already tracks it via + // `telemetryService.track2` below, so tracking here would double-send. + initializeTelemetry({ + homeDir, + deviceId, + appName: CLI_USER_AGENT_PRODUCT, + version, + uiMode: PROMPT_UI_MODE, + model: opts.model ?? defaultModel, + endpoint: () => currentKimiProfile().telemetryEndpoint, + getAccessToken: async () => + (await auth.getCachedAccessToken(KIMI_CODE_PROVIDER_NAME)) ?? null, + }); } const resolved = await resolveNativeSession(app, opts, workDir, defaultModel, stderr); restorePermission = resolved.restorePermission; telemetryService.setContext({ session_id: resolved.session.id, model: resolved.telemetryModel }); + setTelemetryContext({ sessionId: resolved.session.id }); + setTelemetryModel(resolved.telemetryModel); + setCrashPhase('runtime'); if (firstLaunch) { telemetryService.track2('first_launch'); } diff --git a/apps/kimi-code/test/cli/v2-run-print.test.ts b/apps/kimi-code/test/cli/v2-run-print.test.ts index 173046b2450..fdb114de2aa 100644 --- a/apps/kimi-code/test/cli/v2-run-print.test.ts +++ b/apps/kimi-code/test/cli/v2-run-print.test.ts @@ -23,10 +23,13 @@ import { ISessionManager, ITelemetryService, makeAgentScopeContext, + resolveKimiHome, type BootstrapInput, type Event2, } from '@moonshot-ai/agent-core-v2'; +import { CLI_SHUTDOWN_TIMEOUT_MS, CLI_USER_AGENT_PRODUCT } from '#/constant/app'; + import { runV2Print } from '../../src/cli/v2/run-v2-print'; const mocks = vi.hoisted(() => ({ @@ -35,6 +38,11 @@ const mocks = vi.hoisted(() => ({ createKimiDefaultHeaders: vi.fn(() => ({})), resolveKimiHome: vi.fn((homeDir?: string) => homeDir ?? '/tmp/kimi-code-test-home'), createKimiDeviceId: vi.fn(() => 'device-1'), + initializeTelemetry: vi.fn(), + setCrashPhase: vi.fn(), + setTelemetryContext: vi.fn(), + setTelemetryModel: vi.fn(), + shutdownTelemetry: vi.fn(async () => {}), })); vi.mock('@moonshot-ai/agent-core-v2', async (importOriginal) => { @@ -65,14 +73,22 @@ vi.mock('@moonshot-ai/kimi-code-sdk', async (importOriginal) => { }; }); -vi.mock('@moonshot-ai/kimi-telemetry', () => ({ - initializeTelemetry: vi.fn(), - setCrashPhase: vi.fn(), - shutdownTelemetry: vi.fn(), - track: vi.fn(), - setTelemetryContext: vi.fn(), - withTelemetryContext: vi.fn(() => ({ track: vi.fn() })), -})); +vi.mock('@moonshot-ai/kimi-telemetry', async (importOriginal) => { + const actual = await importOriginal(); + return { + // Keep the real `shouldEnableTelemetry` so the tests exercise the actual + // KIMI_DISABLE_TELEMETRY semantics; only the side-effecting entry points + // are stubbed. + ...actual, + initializeTelemetry: mocks.initializeTelemetry, + setCrashPhase: mocks.setCrashPhase, + setTelemetryContext: mocks.setTelemetryContext, + setTelemetryModel: mocks.setTelemetryModel, + shutdownTelemetry: mocks.shutdownTelemetry, + track: vi.fn(), + withTelemetryContext: vi.fn(() => ({ track: vi.fn() })), + }; +}); interface FakeScope { readonly id: string; @@ -265,6 +281,9 @@ describe('runV2Print', () => { beforeEach(() => { vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '1'); vi.stubEnv('KIMI_MODEL_OUTPUT_FORMAT', ''); + // Pin the telemetry kill-switch to "unset" so the host environment cannot + // flip the default telemetry-on path these tests exercise. + vi.stubEnv('KIMI_DISABLE_TELEMETRY', ''); }); afterEach(() => { @@ -505,4 +524,93 @@ describe('runV2Print', () => { expect(profile.bind).not.toHaveBeenCalled(); expect(profile.setModel).toHaveBeenCalledWith('new-model'); }); + + it('honors KIMI_DISABLE_TELEMETRY: no cloud appender and no v1 pipeline', async () => { + vi.stubEnv('KIMI_DISABLE_TELEMETRY', '1'); + const stdout = writer(); + const stderr = writer(); + const { app, appServices } = makeFakeHarness(); + + mocks.bootstrap.mockReturnValue({ app }); + mocks.ensureMainAgent.mockResolvedValue({ agentId: 'main', generation: 1 }); + + await runV2Print(opts() as never, '1.2.3-test', { stdout, stderr }); + + const telemetry = appServices.get(ITelemetryService) as { + addAppender: ReturnType; + }; + expect(telemetry.addAppender).not.toHaveBeenCalled(); + expect(mocks.initializeTelemetry).not.toHaveBeenCalled(); + // The run itself is unaffected: the prompt still renders and cleanup runs. + expect(stdout.text()).toContain('hello world'); + expect(app.dispose).toHaveBeenCalled(); + }); + + it('initializes the v1 telemetry pipeline alongside the cloud appender', async () => { + const stdout = writer(); + const stderr = writer(); + const { app, appServices } = makeFakeHarness(); + + mocks.bootstrap.mockReturnValue({ app }); + mocks.ensureMainAgent.mockResolvedValue({ agentId: 'main', generation: 1 }); + + await runV2Print(opts() as never, '1.2.3-test', { stdout, stderr }); + + const telemetry = appServices.get(ITelemetryService) as { + addAppender: ReturnType; + }; + expect(telemetry.addAppender).toHaveBeenCalledTimes(1); + expect(mocks.initializeTelemetry).toHaveBeenCalledTimes(1); + expect(mocks.initializeTelemetry).toHaveBeenCalledWith({ + homeDir: resolveKimiHome(), + deviceId: 'device-1', + appName: CLI_USER_AGENT_PRODUCT, + version: '1.2.3-test', + uiMode: 'print', + model: 'k2', + endpoint: expect.any(Function), + getAccessToken: expect.any(Function), + }); + // The resolved session id is synced onto the v1 client so crash events and + // system metrics carry it; the sink model is reconciled too (same value + // here, since the fresh session uses the configured default). + expect(mocks.setTelemetryContext).toHaveBeenCalledWith({ sessionId: 'ses_v2' }); + expect(mocks.setTelemetryModel).toHaveBeenCalledWith('k2'); + expect(mocks.setCrashPhase).toHaveBeenCalledWith('runtime'); + expect(mocks.setCrashPhase).toHaveBeenCalledWith('shutdown'); + expect(mocks.shutdownTelemetry).toHaveBeenCalledWith({ + timeoutMs: CLI_SHUTDOWN_TIMEOUT_MS, + }); + }); + + it('reconciles the v1 sink model with the resumed session model', async () => { + const stdout = writer(); + const stderr = writer(); + const { app, appServices, agentServices } = makeFakeHarness(); + + // The resumed session's stored model differs from the configured default. + const profile = agentServices.get(IAgentProfileService) as { getModel: () => string }; + profile.getModel = () => 'resumed-model'; + const index = appServices.get(ISessionIndex) as { get: ReturnType }; + index.get.mockResolvedValue({ id: 'ses_1', cwd: process.cwd() }); + + mocks.bootstrap.mockReturnValue({ app }); + mocks.ensureMainAgent.mockResolvedValue({ agentId: 'main', generation: 1 }); + + await runV2Print(opts({ session: 'ses_1' }) as never, '1.2.3-test', { stdout, stderr }); + + // The v1 pipeline was initialized up front with the best-known model, so + // crash events during session resolution still reach a sink... + expect(mocks.initializeTelemetry).toHaveBeenCalledTimes(1); + expect(mocks.initializeTelemetry).toHaveBeenCalledWith( + expect.objectContaining({ model: 'k2' }), + ); + // ...and the sink's model was reconciled to the resumed session's real + // model only after the session resolved. + expect(mocks.setTelemetryModel).toHaveBeenCalledWith('resumed-model'); + const initOrder = mocks.initializeTelemetry.mock.invocationCallOrder[0]; + const reconcileOrder = mocks.setTelemetryModel.mock.invocationCallOrder[0]; + expect(initOrder).toBeDefined(); + expect(reconcileOrder).toBeGreaterThan(initOrder!); + }); }); diff --git a/packages/telemetry/src/index.ts b/packages/telemetry/src/index.ts index 1f03b1a6537..ef268c9785e 100644 --- a/packages/telemetry/src/index.ts +++ b/packages/telemetry/src/index.ts @@ -1,5 +1,6 @@ import { flushSync, + getSink, setContext, shutdown, track as trackEvent, @@ -16,6 +17,17 @@ export function setTelemetryContext(patch: TelemetryContextIds): void { setContext(patch); } +/** + * Reconcile the attached sink's model after the real session model is known + * (e.g. a resumed session whose stored model differs from the configured + * default). Applies to events accepted after the call; a no-op when undefined + * or when no sink is attached (telemetry disabled or not yet initialized). + */ +export function setTelemetryModel(model: string | undefined): void { + if (model === undefined) return; + getSink()?.setModel(model); +} + export function withTelemetryContext(patch: TelemetryContextIds): TelemetryClient { return withContext(patch); } @@ -30,7 +42,7 @@ export async function shutdownTelemetry( await shutdown(options); } -export { initializeTelemetry } from './bootstrap'; +export { initializeTelemetry, shouldEnableTelemetry } from './bootstrap'; export type { TelemetryBootstrapOptions } from './bootstrap'; export { installCrashHandlers, setCrashPhase } from './crash'; diff --git a/packages/telemetry/src/sink.ts b/packages/telemetry/src/sink.ts index ae51be6c1c7..5f5075332c9 100644 --- a/packages/telemetry/src/sink.ts +++ b/packages/telemetry/src/sink.ts @@ -55,6 +55,10 @@ export class EventSink { } } + setModel(model: string): void { + setPrimitive(this.context, 'model', model); + } + startPeriodicFlush(): void { if (this.flushTimer !== null) return; this.flushTimer = setInterval(() => { diff --git a/packages/telemetry/test/telemetry.test.ts b/packages/telemetry/test/telemetry.test.ts index cd548037bc1..46e82be7cec 100644 --- a/packages/telemetry/test/telemetry.test.ts +++ b/packages/telemetry/test/telemetry.test.ts @@ -7,7 +7,13 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { flushTelemetrySync, initializeTelemetry, shutdownTelemetry, track } from '../src'; +import { + flushTelemetrySync, + initializeTelemetry, + setTelemetryModel, + shutdownTelemetry, + track, +} from '../src'; import { isTelemetryDisabledByEnv } from '../src/bootstrap'; import { TelemetryClient, resetDefaultTelemetryClientForTests } from '../src/client'; import { installCrashHandlersForClient, setCrashPhase, uninstallCrashHandlers } from '../src/crash'; @@ -404,6 +410,27 @@ describe('EventSink', () => { expect(transport.retryCount).toBe(1); }); + + it('applies a reconciled model only to events accepted after setModel', () => { + const transport = new RecordingTransport(); + const sink = makeSink(transport); + const event = (id: string): TelemetryEvent => ({ + event_id: id, + device_id: 'dev', + session_id: 'ses', + event: 'test', + timestamp: 1, + properties: {}, + }); + + sink.accept(event('e1')); + sink.setModel('reconciled-model'); + sink.accept(event('e2')); + sink.flushSync(); + + expect(transport.saved[0]?.[0]?.context).toMatchObject({ model: 'kimi-k2' }); + expect(transport.saved[0]?.[1]?.context).toMatchObject({ model: 'reconciled-model' }); + }); }); describe('payload assembly', () => { @@ -890,6 +917,36 @@ describe('telemetry bootstrap', () => { expect(fetchImpl.mock.calls[0]?.[0]).toBe('https://mock.test/events'); }); + it('reconciles the singleton sink model for subsequently tracked events', async () => { + const fetchImpl = vi.fn(async () => new Response('', { status: 200 })); + vi.stubGlobal('fetch', fetchImpl); + + initializeTelemetry({ + homeDir: await tempHome(), + deviceId: 'dev', + appName: 'kimi-code-cli', + version: '1.2.3', + model: 'model-a', + }); + track('first'); + setTelemetryModel('model-b'); + track('second'); + // An unresolved (undefined) model leaves the sink untouched. + setTelemetryModel(undefined); + track('third'); + await shutdownTelemetry(); + + expect(fetchImpl).toHaveBeenCalledTimes(1); + const init = requestInitFrom(fetchImpl); + const payload = JSON.parse(init.body as string) as { + events: Array<{ event: string; context_model?: string }>; + }; + const byEvent = new Map(payload.events.map((event) => [event.event, event])); + expect(byEvent.get('kfc_first')?.context_model).toBe('model-a'); + expect(byEvent.get('kfc_second')?.context_model).toBe('model-b'); + expect(byEvent.get('kfc_third')?.context_model).toBe('model-b'); + }); + it('flushes the singleton synchronously to disk fallback', async () => { const homeDir = await tempHome(); initializeTelemetry({ From ca5cc76211b29760448f5d5ec35087a9e7c95035 Mon Sep 17 00:00:00 2001 From: Haozhe Date: Thu, 3 Sep 2026 15:28:11 +0800 Subject: [PATCH 03/19] fix(tree-sitter-bash): recognize heredocs in character-level balanced scanning (#3503) * fix(tree-sitter-bash): recognize heredocs in character-level balanced scanning scanBalancedStatements treated heredoc bodies as ordinary characters, so a stray quote, paren, or backtick inside a heredoc body (for example an apostrophe in a PR body passed through a command substitution) broke the scan and produced ERROR nodes; the resulting hasError made dangerous-command-ask judge the whole command unanalyzable and prompt for approval even in yolo mode. Parse << and <<- delimiters (excluding <<< herestrings) with the same unquoting rules as the token-level heredoc reader, queue pending bodies, and skip them line-wise at newlines. Skip arithmetic $(( ... )) regions via scanBalanced so a left-shift << is never mistaken for a heredoc operator. * fix(agent-core-v2): raise the bash parse wall-clock budget to 500ms A 20ms wall-clock budget could abort an otherwise fine parse under CPU contention, GC pauses, or cold-start JIT, flipping the permission verdict to unanalyzable (spurious approval prompts) or silently dropping AGENTS.md re-reminders. Normal commands parse in well under 1ms; maxNodes stays the deterministic cap, and 500ms remains a backstop against pathological parser loops. * fix(tree-sitter-bash): skip comments and legacy arithmetic during heredoc-aware scanning The heredoc-aware scan queued a heredoc for any << it encountered, including inside comments (echo $(printf x # <#bar)), where removing the continuation keeps the hash inside the preceding word instead of starting a comment. Both are valid bash that parsed cleanly before. Skip word-start [[ ... ]] as a balanced region (a << inside a conditional is never a heredoc operator; a bracket in argument position keeps the character scan), and walk back over \+newline pairs before classifying a # as a comment. The extglob conditional case joins the differential fixtures; the continuation case is unit-only because the reference parser errors on it. * fix(tree-sitter-bash): scan substitutions as part of heredoc delimiters A heredoc delimiter containing a substitution (echo $(cat <<$(foo)\nbody\n$(foo)\n)) was truncated at the first paren, so the queued delimiter never matched the body closing line and the scan swallowed the rest of the range, regressing valid bash to hasError and an unanalyzable permission verdict. scanHeredocDelimiter now scans $( ), ${ }, $[ ], and backtick regions wholesale as part of the delimiter word (recursing with the heredoc-aware statement scanner for $( )), mirroring how bash treats the whole word as the delimiter. The case stays unit-only because unquoted delimiters hit the already-registered heredoc-content-chunks structural difference with the reference parser. --- .../agentsMdReminderService.ts | 2 +- .../policies/dangerous-command-ask.ts | 2 +- .../permissionPolicyService.test.ts | 12 + packages/tree-sitter-bash/src/lexer.ts | 212 +++++++++++++++++- .../test/fixtures/differential/heredoc.txt | 45 ++++ .../test/parser-compound.test.ts | 75 +++++++ 6 files changed, 345 insertions(+), 3 deletions(-) diff --git a/packages/agent-core-v2/src/agent/agentsMdReminder/agentsMdReminderService.ts b/packages/agent-core-v2/src/agent/agentsMdReminder/agentsMdReminderService.ts index 42ead234a9d..a04756d971a 100644 --- a/packages/agent-core-v2/src/agent/agentsMdReminder/agentsMdReminderService.ts +++ b/packages/agent-core-v2/src/agent/agentsMdReminder/agentsMdReminderService.ts @@ -40,7 +40,7 @@ import { extractBashTargetDirs } from './bashTargets'; const AGENTS_MD_BASENAMES: ReadonlySet = new Set(AGENTS_MD_PLAIN_NAMES); -const BASH_PARSE_OPTIONS = { timeoutMs: 20, maxNodes: 10_000 } as const; +const BASH_PARSE_OPTIONS = { timeoutMs: 500, maxNodes: 10_000 } as const; const DISCOVERY_REMINDER_VARIANT = 'agents_md'; diff --git a/packages/agent-core-v2/src/agent/permissionPolicy/policies/dangerous-command-ask.ts b/packages/agent-core-v2/src/agent/permissionPolicy/policies/dangerous-command-ask.ts index d657541101b..f7c2a561ef7 100644 --- a/packages/agent-core-v2/src/agent/permissionPolicy/policies/dangerous-command-ask.ts +++ b/packages/agent-core-v2/src/agent/permissionPolicy/policies/dangerous-command-ask.ts @@ -12,7 +12,7 @@ import type { PermissionPolicyResult, } from '#/agent/permissionPolicy/types'; -const PARSE_OPTIONS = { timeoutMs: 20, maxNodes: 10_000 } as const; +const PARSE_OPTIONS = { timeoutMs: 500, maxNodes: 10_000 } as const; const MAX_NESTED_SHELL_DEPTH = 4; diff --git a/packages/agent-core-v2/test/agent/permissionPolicy/permissionPolicyService.test.ts b/packages/agent-core-v2/test/agent/permissionPolicy/permissionPolicyService.test.ts index 9491bc626bd..056b46eda88 100644 --- a/packages/agent-core-v2/test/agent/permissionPolicy/permissionPolicyService.test.ts +++ b/packages/agent-core-v2/test/agent/permissionPolicy/permissionPolicyService.test.ts @@ -357,6 +357,18 @@ describe('AgentPermissionPolicyService chain', () => { }, ); + it('approves a heredoc command containing a single quote in yolo mode', async () => { + mode = 'yolo'; + + await expect(evaluate({ + toolName: 'Bash', + args: { command: 'gh --body "$(cat <<\'EOF\'\nit\'s\nEOF\n)"', timeout: 60 }, + })).resolves.toMatchObject({ + policyName: 'yolo-mode-approve', + result: { kind: 'approve' }, + }); + }); + it.each(['$CMD --force', 'bash -c "echo $HOME"', 'env $FLAGS'])( 'denies unanalyzable command `%s` in auto mode', async (command) => { diff --git a/packages/tree-sitter-bash/src/lexer.ts b/packages/tree-sitter-bash/src/lexer.ts index 807deb7ee9c..003ed674a29 100644 --- a/packages/tree-sitter-bash/src/lexer.ts +++ b/packages/tree-sitter-bash/src/lexer.ts @@ -254,6 +254,19 @@ const CASE_ENABLING_WORDS: ReadonlySet = new Set(['if', 'then', 'elif', * keywords in CASE_ENABLING_WORDS — so `echo case` does not confuse the * scan. `esac` pops the innermost open case regardless of position (the * reference scanner emits the esac token even in argument position). + * + * Heredoc-aware: a `<<` / `<<-` operator queues its delimiter word, and the + * body lines of every pending heredoc are skipped wholesale right after + * the next newline — quotes, parens and substitutions inside a heredoc + * body must not affect the paren count. `((` opens an arithmetic region, + * skipped as one balanced unit so a left-shift `<<` is not mistaken for a + * heredoc operator. Comments (`#` at the start of a word, judged by the + * preceding character after looking through `\`+newline continuations) + * are skipped to end of line, `${ ... }` / `$[ ... ]` expansions, + * word-glued `[ ... ]` subscripts, and `[[ ... ]]` conditional regions + * are skipped as balanced units, so a `<<` inside any of these + * non-redirection contexts is likewise not mistaken for a heredoc + * operator. */ export function scanBalancedStatements( source: string, @@ -266,6 +279,8 @@ export function scanBalancedStatements( let nesting = 0; /** Paren depths at which each open case_statement started. */ const caseDepths: number[] = []; + /** Heredoc delimiters queued since the last newline. */ + const pendingHeredocs: { delimiter: string; stripTabs: boolean }[] = []; let j = i; /** What preceded the current position: 'start' | 'sep' | 'keyword' | 'word'. */ let previous: 'start' | 'sep' | 'keyword' | 'word' = 'start'; @@ -299,7 +314,16 @@ export function scanBalancedStatements( j++; continue; } - if (ch === '\n' || ch === ';' || ch === '&' || ch === '|') { + if (ch === '\n') { + j++; + if (pendingHeredocs.length > 0) { + j = skipHeredocBodies(source, budget, j, end, pendingHeredocs); + pendingHeredocs.length = 0; + } + previous = 'sep'; + continue; + } + if (ch === ';' || ch === '&' || ch === '|') { previous = 'sep'; j++; continue; @@ -309,7 +333,50 @@ export function scanBalancedStatements( j++; continue; } + if (ch === '#') { + let p = j - 1; + while (p - 1 >= i && source[p] === '\n' && source[p - 1] === '\\') p -= 2; + const prev = p >= i ? source[p] : undefined; + if (prev === undefined || isBlank(prev) || prev === '\n' || prev === ';' || prev === '&' || prev === '|' || prev === '(') { + while (j < end && source[j] !== '\n') j++; + continue; + } + } + if (ch === '$' && (source[j + 1] === '{' || source[j + 1] === '[')) { + const open = source[j + 1]!; + j = scanBalanced(source, budget, j + 1, end, open, open === '{' ? '}' : ']', depth + 1).end; + previous = 'word'; + continue; + } + if (ch === '[' && source[j + 1] === '[' && previous !== 'word') { + j = scanBalanced(source, budget, j, end, '[', ']', depth + 1).end; + previous = 'word'; + continue; + } + if (ch === '[' && j > i && isWordChar(source[j - 1])) { + j = scanBalanced(source, budget, j, end, '[', ']', depth + 1).end; + previous = 'word'; + continue; + } + if (ch === '<') { + const heredoc = scanHeredocDelimiter(source, budget, j, end, depth); + if (heredoc !== null) { + pendingHeredocs.push(heredoc); + j = heredoc.end; + } else { + j++; + } + previous = 'word'; + continue; + } if (ch === '(') { + if (source[j + 1] === '(') { + const arith = scanBalanced(source, budget, j, end, '(', ')', depth + 1); + if (j === i) return { end: arith.end, balanced: arith.balanced }; + j = arith.end; + previous = 'word'; + continue; + } nesting++; previous = 'sep'; j++; @@ -351,6 +418,149 @@ export function scanBalancedStatements( return { end, balanced: false }; } +/** Parse a heredoc operator (`<<` / `<<-`) and its delimiter word, starting + * at `i` (which points at the first `<`). Returns the delimiter with quotes + * and backslashes removed (mirroring the parser's extractHeredocSpec), + * whether `<<-` strips leading tabs, and the index just past the delimiter + * word — or null when this `<` does not open a heredoc with a non-empty + * delimiter (`<<<` herestring, another redirect, or malformed input). + * Substitution syntax inside the delimiter word (`$( )`, `${ }`, `$[ ]`, + * backticks) is scanned wholesale as part of the word. */ +function scanHeredocDelimiter( + source: string, + budget: ParseBudget, + i: number, + end: number, + depth: number, +): { delimiter: string; stripTabs: boolean; end: number } | null { + if (source[i + 1] !== '<') return null; + let j = i + 2; + if (source[j] === '<') return null; + let stripTabs = false; + if (source[j] === '-') { + stripTabs = true; + j++; + } + while (j < end && (source[j] === ' ' || source[j] === '\t' || source[j] === '\r')) j++; + let raw = ''; + while (j < end) { + const ch = source[j]!; + if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') break; + if (ch === '&' || ch === '|' || ch === ';' || ch === '(' || ch === ')' || ch === '<' || ch === '>') break; + if (ch === '$' && (source[j + 1] === '(' || source[j + 1] === '{' || source[j + 1] === '[')) { + const open = source[j + 1]!; + const region = + open === '(' + ? scanBalancedStatements(source, budget, j + 1, end, depth + 1) + : scanBalanced(source, budget, j + 1, end, open, open === '{' ? '}' : ']', depth + 1); + if (!region.balanced) return null; + raw += source.slice(j, region.end); + j = region.end; + continue; + } + if (ch === '`') { + const backtickEnd = skipBacktick(source, budget, j, end); + if (backtickEnd >= end) return null; + raw += source.slice(j, backtickEnd); + j = backtickEnd; + continue; + } + if (ch === '\\') { + if (j + 1 >= end || source[j + 1] === '\n') return null; + raw += ch + source[j + 1]; + j += 2; + continue; + } + if (ch === "'") { + const close = source.indexOf("'", j + 1); + if (close === -1 || close >= end) return null; + raw += source.slice(j, close + 1); + j = close + 1; + continue; + } + if (ch === '"') { + let k = j + 1; + for (;;) { + if (k >= end) return null; + if (source[k] === '\\') { + k += 2; + continue; + } + if (source[k] === '"') break; + k++; + } + raw += source.slice(j, k + 1); + j = k + 1; + continue; + } + raw += ch; + j++; + } + let delimiter = ''; + for (let k = 0; k < raw.length; k++) { + const ch = raw[k]!; + if (ch === '\\' && k + 1 < raw.length) { + delimiter += raw[k + 1]; + k++; + } else if (ch !== '"' && ch !== "'") { + delimiter += ch; + } + } + if (delimiter.length === 0) return null; + return { delimiter, stripTabs, end: j }; +} + +/** Skip the body lines of each queued heredoc, starting at `i` (just past + * the newline that ended the command line). Bodies are consumed in queue + * order, each up to its delimiter line (`<<-` allows leading tabs before + * the marker), mirroring readHeredocBody; a delimiter directly followed + * by `)` also closes the body — the paren belongs to the enclosing + * substitution and is left for the paren scan. A body whose delimiter + * never appears swallows the rest of the range. */ +function skipHeredocBodies( + source: string, + budget: ParseBudget, + i: number, + end: number, + specs: readonly { delimiter: string; stripTabs: boolean }[], +): number { + let j = i; + for (const spec of specs) { + let lineStart = j; + let closed = false; + while (lineStart < end) { + budget.progress(); + let marker = lineStart; + if (spec.stripTabs) { + while (marker < end && source[marker] === '\t') marker++; + } + if (source.startsWith(spec.delimiter, marker)) { + const after = marker + spec.delimiter.length; + if (after >= end) { + j = end; + closed = true; + break; + } + if (source[after] === '\n') { + j = after + 1; + closed = true; + break; + } + if (source[after] === ')') { + j = after; + closed = true; + break; + } + } + const newline = source.indexOf('\n', lineStart); + if (newline === -1 || newline >= end) break; + lineStart = newline + 1; + } + if (!closed) return end; + } + return j; +} + /** Skip a $-construct starting at `i` (which points at the `$`). Handles * $(...), $((...)), ${...}, $'...' (escape-aware: \' does not close), * $name and the single-character specials. A `$` followed by anything else diff --git a/packages/tree-sitter-bash/test/fixtures/differential/heredoc.txt b/packages/tree-sitter-bash/test/fixtures/differential/heredoc.txt index 1ac604b146e..7e46798f94e 100644 --- a/packages/tree-sitter-bash/test/fixtures/differential/heredoc.txt +++ b/packages/tree-sitter-bash/test/fixtures/differential/heredoc.txt @@ -595,3 +595,48 @@ program [0,18] "< { }); }); +describe('heredocs in substitutions', () => { + it('parses a quoted heredoc with a single quote in its body inside "$( )"', () => { + expectTree( + 'echo "$(cat <<\'EOF\'\nit\'s\nEOF\n)"', + `(program (command (command_name (word "echo")) (string "\\"" (command_substitution "$(" (redirected_statement (command (command_name (word "cat"))) (heredoc_redirect "<<" (heredoc_start "'EOF'") (heredoc_body "it's\\n") (heredoc_end "EOF"))) ")") "\\"")))`, + ); + }); + + it('parses the gh pr create shape that triggered the unanalyzable verdict', () => { + expectTree( + 'gh --body "$(cat <<\'EOF\'\nit\'s\nEOF\n)"', + `(program (command (command_name (word "gh")) (word "--body") (string "\\"" (command_substitution "$(" (redirected_statement (command (command_name (word "cat"))) (heredoc_redirect "<<" (heredoc_start "'EOF'") (heredoc_body "it's\\n") (heredoc_end "EOF"))) ")") "\\"")))`, + ); + }); + + it('parses a quoted heredoc with a single quote in its body inside bare $( )', () => { + expectTree( + 'echo $(cat <<\'EOF\'\nit\'s\nEOF\n)', + `(program (command (command_name (word "echo")) (command_substitution "$(" (redirected_statement (command (command_name (word "cat"))) (heredoc_redirect "<<" (heredoc_start "'EOF'") (heredoc_body "it's\\n") (heredoc_end "EOF"))) ")")))`, + ); + }); + + it('parses a heredoc body containing a paren inside $( )', () => { + expectTree( + 'echo $(cat < { + expectTree( + 'echo "$(cat <<\'EOF\'\nsay "hi"\nEOF\n)"', + `(program (command (command_name (word "echo")) (string "\\"" (command_substitution "$(" (redirected_statement (command (command_name (word "cat"))) (heredoc_redirect "<<" (heredoc_start "'EOF'") (heredoc_body "say \\"hi\\"\\n") (heredoc_end "EOF"))) ")") "\\"")))`, + ); + }); + + it('parses a heredoc inside a process substitution', () => { + expectTree( + 'cat <(cat <<\'EOF\'\nit\'s\nEOF\n)', + `(program (command (command_name (word "cat")) (process_substitution "<(" (redirected_statement (command (command_name (word "cat"))) (heredoc_redirect "<<" (heredoc_start "'EOF'") (heredoc_body "it's\\n") (heredoc_end "EOF"))) ")")))`, + ); + }); + + it('handles tricky << contexts inside substitutions (non-redirection contexts and substitution delimiters)', () => { + expectTree( + 'echo $(echo $((x << 2)))', + `(program (command (command_name (word "echo")) (command_substitution "$(" (command (command_name (word "echo")) (arithmetic_expansion "$((" (binary_expression (variable_name "x") "<<" (number "2")) "))")) ")")))`, + ); + expectTree( + 'echo $(echo $[x << 2]\n)', + `(program (command (command_name (word "echo")) (command_substitution "$(" (command (command_name (word "echo")) (arithmetic_expansion "$[" (binary_expression (variable_name "x") "<<" (number "2")) "]")) ")")))`, + ); + expectTree( + 'echo $(printf x # < { it('recovers unterminated compound commands without throwing', () => { for (const source of [ From 494df61ce9858c70a9f37a996614534bc9b1cd12 Mon Sep 17 00:00:00 2001 From: wenhua020201-arch Date: Thu, 3 Sep 2026 16:12:29 +0800 Subject: [PATCH 04/19] docs(zh,en): restyle configuration and customization sections (#3485) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs(zh): restyle configuration and customization sections Editorial pass across 11 pages: clear explanatory dashes, replace arrow cross-references with inline links, compress oversized table cells while keeping operational facts (value ranges, override precedence, activation conditions), split >5-sentence paragraphs by theme, fold interface contracts and low-frequency internals into details blocks, add map sentences to multi-paragraph sections, add subcommand overview table to kimi-command reference. Add /provider manager screenshot to media. * docs(zh): restore dangerous_command_guard, fix trust prompt default and secondary-model default - config-files: restore the dangerous_command_guard paragraph dropped during the style pass (regression, content from upstream #3290) - mcp: the trust prompt defaults to Trust this folder per trust-prompt.test.ts; docs had the direction reversed (pre-existing) - config-files: subagent model pool defaults on since #3334; KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=0 disables (pre-existing staleness) * docs(zh,en): sync en mirrors and fix anchor slugs Add restyled en mirrors for all 11 configuration/customization pages, mirroring the zh structure (section parity, map sentences, compressed cells, details folds) while keeping en phrasing. Fix anchor slugs in both locales (underscore kept, dots dropped per @mdit-vue slugify): loop_control, openai_responses, kimi_model_, systemmd variants; retarget renamed permission-mode section (yolo/auto -> The three permission modes / 三种权限模式). --- docs/en/configuration/config-files.md | 159 ++++++++++++------------ docs/en/configuration/data-locations.md | 6 +- docs/en/configuration/env-vars.md | 102 ++++++++------- docs/en/configuration/overrides.md | 26 ++-- docs/en/configuration/providers.md | 28 +++-- docs/en/customization/agents.md | 69 ++++++---- docs/en/customization/hooks.md | 51 ++++---- docs/en/customization/mcp.md | 8 +- docs/en/customization/plugins.md | 84 ++++++++----- docs/en/customization/skills.md | 14 +-- docs/en/customization/themes.md | 20 +-- docs/media/provider-manager.jpg | Bin 0 -> 211881 bytes docs/zh/configuration/config-files.md | 157 +++++++++++------------ docs/zh/configuration/data-locations.md | 6 +- docs/zh/configuration/env-vars.md | 88 +++++++------ docs/zh/configuration/overrides.md | 30 ++--- docs/zh/configuration/providers.md | 25 ++-- docs/zh/customization/agents.md | 81 ++++++++---- docs/zh/customization/hooks.md | 59 +++++---- docs/zh/customization/mcp.md | 18 +-- docs/zh/customization/plugins.md | 143 ++++++++++++--------- docs/zh/customization/skills.md | 28 ++--- docs/zh/customization/themes.md | 38 +++--- 23 files changed, 688 insertions(+), 552 deletions(-) create mode 100644 docs/media/provider-manager.jpg diff --git a/docs/en/configuration/config-files.md b/docs/en/configuration/config-files.md index 28957a03b1b..15119726b21 100644 --- a/docs/en/configuration/config-files.md +++ b/docs/en/configuration/config-files.md @@ -1,12 +1,10 @@ # Configuration files -Kimi Code CLI writes all long-term preferences — which model to use, which API key to fill in, how many steps an Agent can run per turn — into TOML (a plain-text configuration format with a clear structure) files. Change them once and they take effect on every startup. Agent and runtime settings live in `config.toml`; terminal-UI and client preferences (theme, editor, notifications, auto-update) live in a companion `tui.toml`. - -Default location: `~/.kimi-code/config.toml`, created automatically on first run. +Kimi Code CLI writes all long-term preferences into TOML (plain-text configuration) files under `~/.kimi-code/`: runtime settings live in `config.toml`, and terminal-UI preferences live in a companion `tui.toml`. ## Config file location -The CLI reads configuration from `~/.kimi-code/config.toml`. To relocate the data directory, override it with the `KIMI_CODE_HOME` environment variable: +The CLI reads configuration from `~/.kimi-code/config.toml`, created automatically on first run. To relocate the data directory, override it with the `KIMI_CODE_HOME` environment variable: ```sh export KIMI_CODE_HOME=/path/to/kimi-home @@ -15,7 +13,7 @@ export KIMI_CODE_HOME=/path/to/kimi-home The config file path then becomes `$KIMI_CODE_HOME/config.toml`. Regardless of where the directory lives, the file name is always `config.toml`. ::: tip -TOML field names always use snake_case, for example `default_model` and `max_context_size`. If a key contains `.`, you must quote it — for example `[models."gpt-4.1"]` — otherwise TOML treats `.` as a nested table separator. +TOML field names always use snake_case, for example `default_model` and `max_context_size`. If a key contains `.`, you must quote it (for example `[models."gpt-4.1"]`); otherwise TOML treats `.` as a nested table separator. ::: ## Complete example @@ -98,38 +96,36 @@ Fields in the config file fall into two categories: **top-level scalars** that d | Field | Type | Default | Description | | --- | --- | --- | --- | | `default_model` | `string` | — | Default model alias; must be defined in `models` | -| `default_permission_mode` | `string` | `manual` | Default permission mode for new sessions; one of `manual` (Always Ask: auto-read only; everything else needs your approval first), `yolo` (Ask When Needed: routine edits and commands run automatically; risky actions, questions, and plans still ask), or `auto` (Never Ask: never interrupts you; everything runs and is decided automatically, but dangerous commands are always blocked) | -| `default_plan_mode` | `boolean` | `false` | Whether new sessions start in Plan mode (produce a plan before executing) by default | +| `default_permission_mode` | `string` | `manual` | Default permission mode for new sessions: `manual`, `yolo`, or `auto`. See [the three permission modes](../guides/interaction.md#the-three-permission-modes) | +| `default_plan_mode` | `boolean` | `false` | Whether new sessions start in [Plan mode](../guides/interaction.md#plan-mode) by default | | `merge_all_available_skills` | `boolean` | `true` | Whether to merge Agent Skills from all available directories | | `extra_skill_dirs` | `array` | — | Extra skill search directories, layered on top of the default directories | | `extra_agent_dirs` | `array` | — | Extra custom agent search directories, layered on top of the default directories | -| `builtin_product_skills` | `boolean` | `true` | Whether the built-in skills that document Kimi Code itself are offered to the model: `update-config`, `custom-theme`, `mcp-config`, `check-kimi-code-docs`, and `import-from-cc-codex`. Turning them off trims their names and descriptions from the system prompt, at the cost of the guided flows for those tasks. Read by the default `agent-core-v2` engine; ignored when `KIMI_CODE_LEGACY_FLAG=1` selects the legacy engine | +| `builtin_product_skills` | `boolean` | `true` | Whether the built-in skills that document Kimi Code itself are offered to the model | | `telemetry` | `boolean` | `true` | Whether anonymous telemetry is enabled; disabled only when explicitly set to `false` | -| `providers` | `table` | `{}` | API provider table → [`providers`](#providers) | -| `models` | `table` | — | Model alias table → [`models`](#models) | -| `thinking` | `table` | — | Default parameters for Thinking mode → [`thinking`](#thinking) | -| `loop_control` | `table` | — | Agent loop control parameters → [`loop_control`](#loop-control) | -| `background` | `table` | — | Background task runtime parameters → [`background`](#background) | -| `tools` | `table` | — | Global tool switch → [`tools`](#tools) | -| `image` | `table` | — | Image compression parameters → [`image`](#image) | -| `services` | `table` | — | Built-in external service configuration → [`services`](#services) | -| `permission` | `table` | — | Initial permission rules → [`permission`](#permission) | -| `hooks` | `array` | — | Lifecycle hooks; see [Hooks](../customization/hooks.md) | -| `identity` | `table` | — | Custom agent identity → [`identity`](#identity) | - -The following sections cover each of the nested tables in turn: `providers`, `models`, `thinking`, `loop_control`, `background`, `tools`, `image`, `services`, and `permission`. +| [`providers`](#providers) | `table` | `{}` | API provider table | +| [`models`](#models) | `table` | — | Model alias table | +| [`thinking`](#thinking) | `table` | — | Default parameters for Thinking mode | +| [`loop_control`](#loop_control) | `table` | — | Agent loop control parameters | +| [`background`](#background) | `table` | — | Background task runtime parameters | +| [`tools`](#tools) | `table` | — | Global tool switch | +| [`image`](#image) | `table` | — | Image compression parameters | +| [`services`](#services) | `table` | — | Built-in external service configuration | +| [`permission`](#permission) | `table` | — | Initial permission rules | +| [`hooks`](../customization/hooks.md) | `array
` | — | Lifecycle hooks | +| [`identity`](#identity) | `table` | — | Custom agent identity | ## `providers` -Each entry in the `providers` table defines an API provider, keyed by a unique name. The CLI reads credentials only from here — it does **not** fall back to shell environment variables automatically. Running `export KIMI_API_KEY` in the terminal does not give any provider its key; you must write it explicitly in the config file (see [Config overrides](./overrides.md#provider-credentials)). +Each entry in the `providers` table defines an API provider, keyed by a unique name. The CLI reads credentials only from here. It does **not** fall back to shell environment variables automatically: running `export KIMI_API_KEY` in the terminal does not give any provider its key; you must write it explicitly in the config file (see [Config overrides](./overrides.md#provider-credentials)). | Field | Type | Required | Description | | --- | --- | --- | --- | | `type` | `string` | Yes | Provider type: `kimi`, `anthropic`, `openai`, `openai_responses`, `google-genai`, `vertexai` | | `api_key` | `string` | No | API key, written in plain text in the config file | | `base_url` | `string` | No | API base URL | -| `oauth` | `table` | No | OAuth credential reference (`storage` and `key` fields); injected automatically by the login flow — normally no need to write this by hand | -| `env` | `table` | No | Fallback source for provider credentials; see below | +| `oauth` | `table` | No | OAuth credential reference (`storage` and `key` fields); injected automatically by the login flow, so you normally never write this by hand | +| `env` | `table` | No | Fallback source for provider credentials; see the `env` sub-table | | `custom_headers` | `table` | No | Custom HTTP headers attached to each request | **`env` sub-table**: You can write provider-conventional key names (such as `KIMI_API_KEY`) inside `[providers..env]` as a fallback source for `api_key` / `base_url`. This sub-table is **read only from the config file** and does not modify the shell environment: @@ -151,16 +147,16 @@ Each entry in the `models` table defines a model alias (the name used in `defaul | `provider` | `string` | Yes | Name of the provider to use; must be defined in `providers` | | `model` | `string` | Yes | Model identifier sent to the server when calling the API | | `max_context_size` | `integer` | Yes | Maximum context length in tokens; must be at least 1 | -| `max_input_size` | `integer` | No | Declared per-request input limit when it sits below the total window (e.g. gpt-5: 400k window, 272k input). Compaction, context-overflow checks, and usage ratios prefer it; completion budgeting keeps the total window. Resolution clamps it to `max_context_size` | -| `max_output_size` | `integer` | No | Per-request output token cap (maps to `max_tokens`). Currently only the `anthropic` provider honors it. When set for a Claude model, this explicit value overrides the built-in server-side maximum | -| `capabilities` | `array` | No | Capability tags to add explicitly: `thinking`, `always_thinking`, `image_in`, `video_in`, `audio_in`, `tool_use`. Unioned with the capabilities auto-detected by the provider — entries can only be added, never removed | -| `support_efforts` | `array` | No | Thinking effort levels the model accepts. For `kimi`, selecting another value at runtime fails; when model resolution carries an unsupported configured or previous value, the session falls back to the target model's `default_effort` and reports that effective value to the UI. A Thinking-capable Kimi model without this field uses boolean `on` / `off`. Other providers pass concrete values unchanged when their protocol has a native effort field; protocols that expose only levels or token budgets perform the required format conversion. Managed and open-platform refreshes may rewrite this field; to pin it manually, set `[models."".overrides] support_efforts` instead | -| `default_effort` | `string` | No | Default thinking effort for the model. Managed and open-platform refreshes may rewrite this field; to pin it manually, set `[models."".overrides] default_effort` instead | -| `off_effort` | `string` | No | Effort value sent on the wire to disable thinking (e.g. `none` for xai grok). Only meaningful for models that declare such an encoding (catalog imports set it): turning thinking Off then sends this value instead of omitting the effort field — the only way to actually stop reasoning on models that reason by default | -| `base_url` | `string` | No | Per-model endpoint override (written by catalog imports for gateway models served away from the provider default). Resolution prefers it over the provider's `base_url`; only takes effect together with `protocol` | +| `max_input_size` | `integer` | No | Declared per-request input limit; compaction, context-overflow checks, and usage ratios prefer it, completion budgeting keeps the total window | +| `max_output_size` | `integer` | No | Per-request output token cap (maps to `max_tokens`); currently only the `anthropic` provider reads it | +| `capabilities` | `array` | No | Capability tags added explicitly: `thinking`, `always_thinking`, `image_in`, `video_in`, `audio_in`, `tool_use`; only ever added, never removed | +| `support_efforts` | `array` | No | Thinking effort levels the model accepts; unsupported values fall back to `default_effort`, out-of-list values fail; managed refreshes may rewrite it (pin via overrides) | +| `default_effort` | `string` | No | Default thinking effort for the model; managed and open-platform refreshes may rewrite it. Pin via [model overrides](#model-overrides) | +| `off_effort` | `string` | No | Effort value sent on the wire to disable thinking (e.g. `none` for xai grok); the only way to actually stop reasoning on models that reason by default | +| `base_url` | `string` | No | Per-model endpoint override (written by catalog imports); takes precedence over the provider's `base_url`, only effective together with `protocol` | | `display_name` | `string` | No | Name shown in the UI; falls back to `model` when unset | -| `reasoning_key` | `string` | No | `openai` provider only. Override the field name used for reasoning content when the gateway returns it under a non-standard name; by default `reasoning_content`, `reasoning_details`, and `reasoning` are auto-detected | -| `adaptive_thinking` | `boolean` | No | `anthropic` provider only. Force adaptive thinking on or off, overriding the version inference based on the model name. Omit to infer automatically (Claude ≥ 4.6 uses adaptive) | +| `reasoning_key` | `string` | No | `openai` provider only; set when the gateway returns reasoning content under a non-standard field name (`reasoning_content` and friends are auto-detected) | +| `adaptive_thinking` | `boolean` | No | `anthropic` provider only; force adaptive thinking on or off, omit to infer from the model name (Claude ≥ 4.6 uses adaptive) | When an alias contains `.`, use a quoted key: @@ -188,19 +184,17 @@ display_name = "Kimi for Coding (custom)" `[models."".overrides]` accepts ordinary model fields such as `max_context_size`, `max_input_size`, `max_output_size`, `capabilities`, `display_name`, `reasoning_key`, `adaptive_thinking`, `support_efforts`, `default_effort`, and `off_effort`. It does not accept identity / routing fields: `provider`, `model`, `protocol`, `beta_api`, and `base_url`. -You can also switch models temporarily without touching the config file — by setting `KIMI_MODEL_*` environment variables, the CLI synthesizes a temporary provider in memory that does not persist after restart. See [Define a model from environment variables](./env-vars.md#define-a-model-from-environment-variables-kimi-model). +You can also switch models temporarily without touching the config file: setting `KIMI_MODEL_*` environment variables synthesizes a temporary provider in memory that does not persist after restart. See [Define a model from environment variables](./env-vars.md#define-a-model-from-environment-variables-kimi_model_). ## `secondary_model` -Subagents inherit the model the main agent is running by default. The `[secondary_model]` section makes this configurable: it offers subagents a pool of candidate models plus a default binding — typically a cheaper model for subtasks that do not need the main model's capability. +Subagents inherit the model the main agent is running by default. The `[secondary_model]` section makes this configurable: it offers subagents a pool of candidate models plus a default binding. Typically that is a cheaper model for subtasks that do not need the main model's capability. ### Subagent model pool -Configured values take effect in every launch mode, including the interactive TUI. - -The pool is enabled by default in every launch mode, including the interactive TUI. To disable it, set `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=0` (or `secondary-model = false` under `[experimental]` in `config.toml`); while disabled, the pool keys stay inert: subagents inherit the caller's model and session startup skips the pool validation. +The pool is enabled by default and needs no configuration. Set `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=0` to disable it; while disabled, the pool keys stay inert, subagents inherit the caller's model, and session startup skips the pool validation. -The minimal configuration is one line — a lone `default_model` is a pool with a single entry: +The minimal configuration is one line. A lone `default_model` is a pool with a single entry: ```toml [secondary_model] @@ -210,7 +204,7 @@ default_model = "kimi-code/kimi-for-coding-highspeed" | Field | Type | Default | Description | | --- | --- | --- | --- | | `default_model` | `string` | — | The default model for subagents | -| `models` | `table` | — | Subagent model pool. Each key is the alias of a configured [`[models]`](#models) entry; each value is the selection hint shown to the main agent | +| `models` | `table` | — | Subagent model pool; each key is the alias of a configured [`[models]`](#models) entry, each value a selection hint | | `force` | `boolean` | `false` | Pin every subagent to `default_model`, taking the choice away from the main agent | | `default_effort` | `string` | — | The thinking effort every spawned subagent binds with; outranks the bound model entry's own `default_effort` | @@ -218,15 +212,15 @@ Constraints between the fields: - `default_model`: required when a `models` table is configured, and must be one of its keys. - `models`: values may be Chinese or English; an empty string lists the alias with no hint. -- `force`: requires `default_model` and cannot be combined with a `models` table — the table exists to offer a choice, and force removes it. +- `force`: requires `default_model` and cannot be combined with a `models` table: the table exists to offer a choice, and force removes it. - `default_effort` is section-wide: every spawn binds it regardless of the chosen pool entry (or the forced model). For per-entry efforts, leave it unset and use model variants (see below). - `primary` is a reserved alias (see below) and cannot be a pool key. -Pool aliases reference the current `[models]` table: if a provider is later deleted or logged out, or its refreshed model list no longer contains an alias, session startup fails with a configuration error naming the broken alias — fix or remove the entry to recover. The `[secondary_model]` section itself is never rewritten automatically. +Pool aliases reference the current `[models]` table: if a provider is later deleted or logged out, or its refreshed model list no longer contains an alias, session startup fails with a configuration error naming the broken alias. Fix or remove the entry to recover. The `[secondary_model]` section itself is never rewritten automatically. -In the interactive TUI, the [`/secondary-model`](../reference/slash-commands.md) command (alias `/subagent-model`) opens a model selector: the choice is written to `default_model` (when a models table exists and the picked alias is not in it, an entry with an empty description is added), and newly spawned subagents pick up the new default immediately — no session restart needed. +In the interactive TUI, the [`/secondary-model`](../reference/slash-commands.md) command (alias `/subagent-model`) opens a model selector: the choice is written to `default_model` (when a models table exists and the picked alias is not in it, an entry with an empty description is added), and newly spawned subagents pick up the new default immediately, no session restart needed. -A configured pool — an explicit `models` table or a lone `default_model` — enables model selection: the `Agent` / `AgentSwarm` tools gain a `model` parameter, and the tool description lists the pool (the default marked `[default]`) so the main agent can choose per spawn. Pool keys can only reference configured [`[models]`](#models) entries — the `kimi-code/*` aliases below are provisioned by `/login`: +A configured pool (an explicit `models` table or a lone `default_model`) enables model selection: the `Agent` / `AgentSwarm` tools gain a `model` parameter, and the tool description lists the pool (the default marked `[default]`) so the main agent can choose per spawn. Pool keys can only reference configured [`[models]`](#models) entries. The `kimi-code/*` aliases below are provisioned by `/login`: ```toml [secondary_model] @@ -244,7 +238,7 @@ A spawn resolves the subagent's model in this order: Rules for the `model` parameter: -- It accepts any pool alias, or `"primary"` — the model the caller itself is running, always valid even when not in the pool. +- It accepts any pool alias, or `"primary"`, the model the caller itself is running; always valid even when not in the pool. - When neither `default_model` nor `models` is configured, the parameter is not advertised and subagents inherit the caller's model. - Binding a pool alias does not inherit the caller's thinking effort. The section's `default_effort` wins when set. Otherwise, `[thinking].enabled = false` keeps Thinking off; when Thinking is enabled, resolution continues with the bound model entry's `default_effort`, the global `[thinking].effort`, then the middle of the bound model's `support_efforts`. - `"primary"` inherits both the model and the effort level from the caller. @@ -290,7 +284,7 @@ k3-max = "The same model at max thinking effort. Good for the hardest subtasks." Two prerequisites: - The underlying model must declare `support_efforts` (under `managed:kimi-code` only the k3 family currently declares effort levels). -- The variant is a standalone entry and does not inherit fields from the entry it points at — copy `capabilities`, `support_efforts`, and the other metadata over in full, otherwise `default_effort` has no effect (it must be a member of `support_efforts`). +- The variant is a standalone entry and does not inherit fields from the entry it points at: copy `capabilities`, `support_efforts`, and the other metadata over in full, otherwise `default_effort` has no effect (it must be a member of `support_efforts`). Note the asymmetry between the main agent and pool-bound subagents: for the main agent, a configured global `[thinking].effort` overrides the variant's `default_effort`; for subagents the variant's `default_effort` wins over the global value, and only `[secondary_model].default_effort` outranks it. Value and fallback rules follow the [`[models]` entry's `default_effort`](#models). @@ -308,10 +302,10 @@ Configuration errors fail loudly instead of falling back silently. Session creat | Field | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | Whether Thinking is enabled by default for new sessions; set to `false` to force Thinking off | -| `effort` | `string` | — | Thinking effort level (for example `low`, `medium`, `high`, `xhigh`, `max`). Non-Kimi providers do not remap concrete effort values when the upstream protocol accepts them; if the provider rejects the value, choose one that the model supports. Protocols that expose only levels or token budgets still require format conversion. Kimi models with `support_efforts` fall back to their model default when this configured value is not listed; Kimi models without that list treat every enabled value as boolean `on` | -| `keep` | `string` | `"all"` | Preserved Thinking passthrough. On `kimi` it is sent as `thinking.keep`; on `anthropic` (Claude and Kimi's Anthropic-compatible mode) it is sent as a `context_management` `clear_thinking_20251015` edit (enabling keep routes Anthropic requests to the beta Messages API; an off-value disables keep and returns to the standard endpoint). `"all"` preserves prior turns' reasoning (`reasoning_content` / Anthropic thinking blocks); set to an off-value (`false`/`0`/`no`/`off`/`none`/`null`) to disable. Overridden by `KIMI_MODEL_THINKING_KEEP`; only injected while Thinking is on | +| `effort` | `string` | — | Thinking effort: `low` / `medium` / `high` / `xhigh` / `max`; falls back to the model default when not in its supported list | +| `keep` | `string` | `"all"` | Preserved Thinking passthrough: `kimi` sends it as `thinking.keep`, `anthropic` as a `clear_thinking_20251015` edit (routes to the beta Messages API). An off-value disables it; overridden by `KIMI_MODEL_THINKING_KEEP`; injected only while Thinking is on | -### Deprecated fields +
Deprecated fields | Field | Deprecated in | Description | | --- | --- | --- | @@ -320,6 +314,8 @@ Configuration errors fail loudly instead of falling back silently. Session creat | `loop_control.max_retries_per_step` | 0.32.0 | Replaced by `loop_control.max_attempts_per_step` (the value was always a total-attempt limit, including the first try). The old key is ignored and reports a warning on startup; rename it in `config.toml`. | | `loop_control.max_steps_per_run` | 0.32.0 | Replaced by `loop_control.max_steps_per_turn`. The old key is ignored and reports a warning on startup; rename it in `config.toml`. | +
+ ## `loop_control` `loop_control` governs the step count limit, the per-step attempt limit, and the threshold that triggers automatic context compaction in the Agent execution loop. @@ -332,15 +328,15 @@ Configuration errors fail loudly instead of falling back silently. Session creat `max_steps_per_turn` can be overridden by the `KIMI_LOOP_MAX_STEPS_PER_TURN` environment variable, and `max_attempts_per_step` by `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP`; both take higher priority than the config file. The former `KIMI_LOOP_MAX_RETRIES_PER_STEP` variable is deprecated but still honored (with a startup warning) when the new one is unset. -Retries only apply to transient failures — connection errors, timeouts, HTTP 429 rate limits, and 5xx server errors. A 429 caused by an exhausted quota or insufficient account balance is not retried and fails immediately, since it cannot succeed until the account is recharged. +Retries only apply to transient failures: connection errors, timeouts, HTTP 429 rate limits, and 5xx server errors. A 429 caused by an exhausted quota or insufficient account balance is not retried and fails immediately, since it cannot succeed until the account is recharged. ## `token_counting` -`token_counting` selects which context token count is reported externally — the value behind the context-size display. Internal logic (automatic compaction triggers, budgets, and overflow backoff) always uses both provider-reported usage and estimates, regardless of this setting. +`token_counting` selects which context token count is reported externally, the value behind the context-size display. Internal logic (automatic compaction triggers, budgets, and overflow backoff) always uses both provider-reported usage and estimates, regardless of this setting. | Field | Type | Default | Description | | --- | --- | --- | --- | -| `strategy` | `"measured+estimated" \| "measured" \| "estimated"` | `"measured+estimated"` | `measured+estimated` reports the live size — the provider-reported usage of each exchange plus an estimate of the not-yet-measured tail — floored by the last measured total; `measured` reports provider usage alone, so the display only moves when an exchange completes; `estimated` reports a pure estimate with provider usage ignored — the fallback for providers that do not report usage or report it unreliably | +| `strategy` | `"measured+estimated" \| "measured" \| "estimated"` | `"measured+estimated"` | `measured+estimated` combines measured usage with an estimate of the unmeasured tail; `measured` reports provider usage alone, updated when a request completes; `estimated` is a pure estimate, for providers that do not report usage | `strategy` can be overridden by the `KIMI_TOKEN_COUNTING_STRATEGY` environment variable, which takes higher priority than `config.toml`. @@ -351,13 +347,13 @@ Retries only apply to transient failures — connection errors, timeouts, HTTP 4 | Field | Type | Default | Description | | --- | --- | --- | --- | | `max_running_tasks` | `integer` | — | Maximum number of background tasks running concurrently | -| `keep_alive_on_exit` | `boolean` | `false` | Whether to keep still-running background tasks when the session closes. By default, Kimi Code requests that all background tasks stop before the process exits; set this to `true` only when you want tasks to outlive the session. In print mode (`kimi -p`), this is only a legacy fallback used when `print_background_mode` is unset: `true` is equivalent to `print_background_mode = "drain"` | -| `kill_grace_period_ms` | `integer` | `5000` | Grace period in milliseconds after session close, a manual stop, or a task timeout requests graceful termination. If a task is still running after this period, Kimi Code attempts to force-stop it | -| `bash_auto_background_on_timeout` | `boolean` | `true` | When a foreground `Bash` command hits its timeout, move it to a background task instead of killing it — the agent is notified when it completes, and the backgrounded command is bounded by the `bash_task_timeout_s` default background timeout. Set to `false` to kill timed-out foreground commands instead | -| `bash_task_timeout_s` | `integer` | `600` | Default timeout (seconds) for background `Bash` tasks when the call omits `timeout`; also used to re-arm foreground commands moved to the background on timeout. `0` means no timeout — the task runs until it exits or the model stops it. Explicit per-call `timeout` values are unaffected. In print mode (`kimi -p`) the default is `0` unless explicitly set | -| `print_background_mode` | `"exit" \| "drain" \| "steer"` | `"steer"` | Print mode (`kimi -p`) only. Governs how pending background tasks are handled once the main agent's turn ends: `"exit"` exits immediately; `"drain"` waits for every background task to reach a terminal state before exiting (results are not fed back to the main agent); `"steer"` stays alive so a completing background task — like a background subagent — injects a synthetic user message that steers the main agent into a new turn, looping until a turn ends with no pending background tasks or a limit is hit. Takes precedence over the `keep_alive_on_exit` print fallback | -| `print_wait_ceiling_s` | `integer` | `2147483` | In print mode (`kimi -p`), the wall-clock ceiling (seconds) for the wait/steer loop when `print_background_mode` is `"drain"` or `"steer"` (the default is ~24.8 days — effectively unbounded). Has no effect outside print mode or when it is `"exit"` | -| `print_max_turns` | `integer` | `100000` | In print mode (`kimi -p`) with `print_background_mode = "steer"`, the maximum number of new turns that may be triggered by background-task completions, to keep the steering loop bounded (the default is effectively unbounded) | +| `keep_alive_on_exit` | `boolean` | `false` | Whether to keep still-running background tasks when the session closes; in print mode only a fallback when `print_background_mode` is unset (`true` = `drain`) | +| `kill_grace_period_ms` | `integer` | `5000` | Grace period in milliseconds after a task is asked to terminate; still-running tasks are force-stopped when it elapses | +| `bash_auto_background_on_timeout` | `boolean` | `true` | Move a foreground `Bash` command to a background task on timeout instead of killing it; set to `false` to kill timed-out foreground commands instead | +| `bash_task_timeout_s` | `integer` | `600` | Default timeout (seconds) for background `Bash` tasks when the call omits `timeout`; `0` means no timeout. Explicit per-call `timeout` values are unaffected; print mode defaults to `0` | +| `print_background_mode` | `"exit" \| "drain" \| "steer"` | `"steer"` | Print mode only: how pending background tasks are handled when the main agent's turn ends; `"exit"` exits immediately, `"drain"` waits for terminal states without feeding results back, `"steer"` injects completions as synthetic user messages steering new turns until none are pending | +| `print_wait_ceiling_s` | `integer` | `2147483` | Wall-clock ceiling (seconds) for the print-mode wait/steer loop; no effect outside print mode or with `"exit"` | +| `print_max_turns` | `integer` | `100000` | Maximum number of new turns triggered by background-task completions in `"steer"` mode; keeps the steering loop bounded | `keep_alive_on_exit` can be overridden by the `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` environment variable, and `max_running_tasks` by `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS`; both take higher priority than `config.toml`. @@ -369,7 +365,7 @@ In print mode (`kimi -p ""`), Kimi Code stays alive after the main agent | Field | Type | Default | Description | | --- | --- | --- | --- | -| `timeout_ms` | `integer` | `7200000` (2 hours) | Maximum wall-clock time (milliseconds) a single `Agent` subagent is allowed to run before it is settled as `timed_out`. `0` means no timeout — the subagent runs until it finishes or the model stops it. This is the background-task manager's per-task timeout for each subagent task, so it applies to both foreground and background subagents. In print mode (`kimi -p`) the default is `0` unless explicitly set. Note: any value above `2147483647` (about 24.8 days) is clamped to roughly 24.8 days by the runtime | +| `timeout_ms` | `integer` | `7200000` (2 hours) | Maximum wall-clock time (milliseconds) a single `Agent` subagent may run before it is settled as `timed_out`; `0` means no timeout | `timeout_ms` can be overridden by the `KIMI_SUBAGENT_TIMEOUT_MS` environment variable, which takes higher priority than `config.toml`. @@ -379,7 +375,7 @@ In print mode (`kimi -p ""`), Kimi Code stays alive after the main agent | Field | Type | Default | Description | | --- | --- | --- | --- | -| `timeout_ms` | `integer` | `7200000` (2 hours) | Maximum wall-clock time (milliseconds) a single `AgentSwarm` subagent is allowed to run. On timeout that subagent is aborted and marked as failed in the aggregated report (`Subagent timed out.`); the other subagents are unaffected. `0` means no timeout — the subagent runs until it finishes or the model stops it. In print mode (`kimi -p`) the default is `0` unless explicitly set. Note: any value above `2147483647` (about 24.8 days) is clamped to roughly 24.8 days by the runtime | +| `timeout_ms` | `integer` | `7200000` (2 hours) | Maximum wall-clock time (milliseconds) a single `AgentSwarm` subagent may run; on timeout it is aborted and the aggregated report marks `Subagent timed out.`; `0` means no timeout | `timeout_ms` can be overridden by the `KIMI_CODE_SWARM_TIMEOUT_MS` environment variable, which takes higher priority than `config.toml`. @@ -387,8 +383,8 @@ In print mode (`kimi -p ""`), Kimi Code stays alive after the main agent | Field | Type | Default | Description | | --- | --- | --- | --- | -| `startup_timeout_ms` | `integer` | `30000` (30 seconds) | Global default connection (startup + tool discovery) timeout in milliseconds for all MCP servers. Accepts `1`–`2147483647`. A per-server `startupTimeoutMs` in `mcp.json` always wins over this section and the environment variable; when neither is set, the default applies | -| `tool_timeout_ms` | `integer` | `60000` (60 seconds) | Global default single tool-call timeout in milliseconds for all MCP servers. Accepts `1`–`2147483647`. A per-server `toolTimeoutMs` in `mcp.json` always wins over this section and the environment variable; when neither is set, the client built-in default applies | +| `startup_timeout_ms` | `integer` | `30000` (30 seconds) | Global default connection (startup + tool discovery) timeout in milliseconds for all MCP servers; a per-server `startupTimeoutMs` in `mcp.json` wins | +| `tool_timeout_ms` | `integer` | `60000` (60 seconds) | Global default single tool-call timeout in milliseconds for all MCP servers; a per-server `toolTimeoutMs` in `mcp.json` wins | `startup_timeout_ms` and `tool_timeout_ms` can be overridden by the `KIMI_MCP_STARTUP_TIMEOUT_MS` and `KIMI_MCP_TOOL_TIMEOUT_MS` environment variables respectively, which take higher priority than `config.toml`. See [MCP](../customization/mcp.md) for the full MCP server configuration. @@ -399,7 +395,7 @@ Customizes how the agent identifies itself. Leave it unset and nothing changes. | Field | Type | Default | Description | | --- | --- | --- | --- | | `name` | `string` | — | Display name the agent calls itself in the system prompt (fills the `${product_name}` slot, including in your own `SYSTEM.md` and agent files) | -| `slug` | `string` | derived from `name` | Machine identifier used in protocol fields: the `User-Agent` product token sent to third-party providers, and the client name announced to MCP servers. Derived from `name` when omitted: lowercased, with every run of non-alphanumeric characters folded to `-` | +| `slug` | `string` | derived from `name` | Machine identifier in protocol fields (`User-Agent` product token, MCP client name); derived from `name` when omitted: lowercased, non-alphanumeric runs folded to `-` | ```toml [identity] @@ -407,11 +403,11 @@ name = "Acme Dev Agent" slug = "acme-dev" # optional ``` -Both fields can be set through the `KIMI_CODE_IDENTITY_NAME` and `KIMI_CODE_IDENTITY_SLUG` environment variables, which take higher priority than `config.toml` and are never written back to it — convenient for containers and CI, where writing a config file is awkward. +Both fields can be set through the `KIMI_CODE_IDENTITY_NAME` and `KIMI_CODE_IDENTITY_SLUG` environment variables, which take higher priority than `config.toml` and are never written back to it, making them convenient for containers and CI, where writing a config file is awkward. A name that contains no ASCII letters or digits (for example a purely Chinese name) leaves nothing to derive a slug from and falls back to `agent`; write `slug` explicitly if you need a specific protocol token. -The identity is resolved once at startup and holds for the life of the process — it is announced to MCP servers and providers when connections are made, so it cannot change midway. Edits to this section take effect on the next start, for new sessions: a resumed session keeps the system prompt it was recorded with, since its past turns already speak under that identity. Likewise, an MCP OAuth authorization keeps the client registration it was granted under; reset that server's authentication to register under the new identity. +The identity is resolved once at startup and holds for the life of the process: it is announced to MCP servers and providers when connections are made, so it cannot change midway. Edits to this section take effect on the next start, for new sessions: a resumed session keeps the system prompt it was recorded with, since its past turns already speak under that identity. Likewise, an MCP OAuth authorization keeps the client registration it was granted under; reset that server's authentication to register under the new identity. This section is read by the default `agent-core-v2` engine. It is ignored by the legacy `kimi` / `kimi -p` path selected with `KIMI_CODE_LEGACY_FLAG=1`; `kimi web` always uses `agent-core-v2`. @@ -424,7 +420,7 @@ This section is read by the default `agent-core-v2` engine. It is ignored by the | `enabled` | `array` | — | Global allowlist: when non-empty, only the listed tools are available; omitting the field or setting an empty array imposes no constraint | | `disabled` | `array` | — | Global denylist, applied after `enabled` | -Name matching follows the same rules as the same-named fields in an agent file: built-in tools match by exact name (such as `Read`), and MCP tools match with globs (such as `mcp__github__*`). Three entry shapes never match anything and are reported with a warning: a wildcard outside an `mcp__` pattern (`enabled = ["*"]` disables every tool, `disabled = ["*"]` disables none), an `mcp__` literal missing the tool segment (`mcp__github` — use `mcp__github__*` for a whole server), and a name no registered or built-in tool has (matching is case-sensitive). +Name matching follows the same rules as the same-named fields in an agent file: built-in tools match by exact name (such as `Read`), and MCP tools match with globs (such as `mcp__github__*`). Three entry shapes never match anything and are reported with a warning: a wildcard outside an `mcp__` pattern (`enabled = ["*"]` disables every tool, `disabled = ["*"]` disables none), an `mcp__` literal missing the tool segment (`mcp__github`; use `mcp__github__*` for a whole server), and a name no registered or built-in tool has (matching is case-sensitive). ```toml [tools] @@ -441,8 +437,8 @@ Like the `tools` / `disallowedTools` fields of an agent file, this section shape | Field | Type | Default | Description | | --- | --- | --- | --- | -| `max_edge_px` | `integer` | `2000` | Longest-edge ceiling in pixels. Larger images are scaled down proportionally to fit; raising it preserves more detail at the cost of larger request bodies | -| `read_byte_budget` | `integer` | `262144` (256 KB) | Per-image byte budget for images the model reads for itself (`ReadMediaFile` default reads). It bounds the accumulated request-body size when the model keeps screenshotting and reading images; fine detail stays reachable through the `region` parameter, which reads a crop back at full fidelity (`region` and `full_resolution` are not subject to this budget) | +| `max_edge_px` | `integer` | `2000` | Longest-edge ceiling in pixels; larger images scale down proportionally. Raising it preserves more detail at the cost of larger request bodies | +| `read_byte_budget` | `integer` | `262144` (256 KB) | Per-image byte budget for images the model reads for itself (`ReadMediaFile` default reads); `region` and `full_resolution` read-backs are exempt | `max_edge_px` can be overridden by the `KIMI_IMAGE_MAX_EDGE_PX` environment variable and `read_byte_budget` by `KIMI_IMAGE_READ_BYTE_BUDGET`; both take higher priority than `config.toml`. @@ -481,7 +477,7 @@ api_key = "sk-xxx" ## `permission` -`permission` sets permission rules that are automatically loaded when a session starts, controlling whether the Agent needs user confirmation before calling a tool. Rules are written as a `[[permission.rules]]` array of tables, matched in order — the first matching rule takes effect. +`permission` sets permission rules that are automatically loaded when a session starts, controlling whether the Agent needs user confirmation before calling a tool. Rules are written as a `[[permission.rules]]` array of tables, matched in order; the first matching rule takes effect. You can also set `dangerous_command_guard = false` under `[permission]` to turn off the built-in dangerous-command policy entirely (no dangerous-command ask or auto-mode deny); the default is `true`. An environment variable `KIMI_CODE_DANGEROUS_COMMAND_GUARD=false` overrides the file setting and restores the behavior before the policy was introduced. Use this switch only for environments that already gate commands outside the agent. @@ -492,7 +488,7 @@ You can also set `dangerous_command_guard = false` under `[permission]` to turn | `pattern` | `string` | Yes | Match pattern in the form `ToolName` or `ToolName(arg-pattern)`, e.g. `Read` or `Bash(rm -rf*)` | | `reason` | `string` | No | Rule description for debugging and auditing | -Built-in tool names are listed in [Built-in tools](../reference/tools.md). Most built-in tools that accept rule arguments define their own matching subject, such as `Bash(command-pattern)` or `Read(path-pattern)`. `AgentSwarm`, MCP tools, and custom tools can only be matched by tool name — argument patterns are not supported for them. +Built-in tool names are listed in [Built-in tools](../reference/tools.md). Most built-in tools that accept rule arguments define their own matching subject, such as `Bash(command-pattern)` or `Read(path-pattern)`. `AgentSwarm`, MCP tools, and custom tools can only be matched by tool name; argument patterns are not supported for them. ```toml [[permission.rules]] @@ -518,20 +514,27 @@ MCP server declarations are configured in `~/.kimi-code/mcp.json` or the project ## `tui.toml` -Alongside `config.toml`, the CLI keeps terminal-UI and client preferences in a companion `tui.toml` in the same directory (`~/.kimi-code/tui.toml`, or `$KIMI_CODE_HOME/tui.toml` when overridden). It is created with defaults on first run, and the interactive commands `/config`, `/theme`, and `/editor` write to it for you — so you rarely need to edit it by hand. If the file is malformed, the CLI falls back to defaults and shows a notice instead of failing to start. +Alongside `config.toml`, the CLI keeps terminal-UI and client preferences in a companion `tui.toml` in the same directory (`~/.kimi-code/tui.toml`, or `$KIMI_CODE_HOME/tui.toml` when overridden). It is created with defaults on first run, and the interactive commands `/config`, `/theme`, and `/editor` write to it for you, so you rarely need to edit it by hand. If the file is malformed, the CLI falls back to defaults and shows a notice instead of failing to start. | Field | Type | Default | Description | | --- | --- | --- | --- | -| `theme` | `string` | `auto` | Color theme: `auto` (follow the terminal), `dark`, `light`, or the name of a [custom theme](../customization/themes.md) | -| `render_latex` | `boolean` | `true` | Render LaTeX math expressions (`$…$`, `$$…$$`) in Markdown messages as Unicode text; `false` keeps the raw source | +| `theme` | `string` | `auto` | Color theme: `auto`, `dark`, `light`, or the name of a [custom theme](../customization/themes.md) | +| `render_latex` | `boolean` | `true` | Render LaTeX math expressions in Markdown messages as Unicode text; `false` keeps the raw source | | `disable_paste_burst` | `boolean` | `false` | Disable the non-bracketed paste-burst fallback that keeps rapid multi-line pastes from submitting line by line | -| `cache_expiry_hint` | `boolean` | `true` | Show a dialog when resuming a long-idle session or submitting after a long idle stretch, warning that the context cache has likely expired and offering to compact or start a new session (v2 engine only) | +| `cache_expiry_hint` | `boolean` | `true` | On resume or when submitting after a long idle stretch, warn that the context cache may have expired and offer to compact or start a new session (v2 engine only) | | `[editor].command` | `string` | `""` | External editor command for composing long input; empty falls back to `$VISUAL` / `$EDITOR` | | `[notifications].enabled` | `boolean` | `true` | Whether desktop notifications are sent | | `[notifications].notification_condition` | `string` | `unfocused` | When to notify: `unfocused` (only when the terminal is not focused) or `always` | | `[upgrade].auto_install` | `boolean` | `true` | Whether new versions are installed automatically | -| `[status_line].items` | `string[]` | `[]` | Built-in slots to show on the first footer line and their order: `mode`, `goal`, `model`, `tasks`, `cwd`, `git`, `tips`. Unset keeps the default layout; unknown ids are skipped with a warning | -| `[status_line].command` | `string` | `""` | Custom status line command. Its first stdout line replaces the first footer line, with a JSON snapshot (model, cwd, git branch, permission mode, plan mode, context usage, session id, version) passed on stdin. Runs are capped at 300ms and throttled to once per second; failures fall back to the built-in layout | +| `[status_line].items` | `string[]` | `[]` | Built-in slots on the first footer line and their order: `mode`, `goal`, `model`, `tasks`, `cwd`, `git`, `tips`; unknown ids are skipped with a warning | +| `[status_line].command` | `string` | `""` | Custom status line command: its first stdout line replaces the footer, and a JSON snapshot is passed on stdin; capped at 300ms, throttled to once per second, failures fall back to the built-in layout | + +
+Fields in the stdin JSON snapshot + +Model, cwd, git branch, permission mode, plan mode, context usage, session id, version. + +
```toml # ~/.kimi-code/tui.toml @@ -569,7 +572,7 @@ The `[workspace]` table groups project-level workspace settings: | Field | Type | Required | Description | | --- | --- | --- | --- | -| `additional_dir` | `array` | No | Additional workspace directories, stored as absolute paths. Written automatically when you confirm "remember this directory" in `/add-dir`; read back on startup so the directories are available in every session of this project | +| `additional_dir` | `array` | No | Additional workspace directories (absolute paths); written automatically when you confirm "remember this directory" in `/add-dir`, and available in every session of this project | ```toml [workspace] diff --git a/docs/en/configuration/data-locations.md b/docs/en/configuration/data-locations.md index fa7bb446437..2d51482e06a 100644 --- a/docs/en/configuration/data-locations.md +++ b/docs/en/configuration/data-locations.md @@ -1,6 +1,6 @@ # Data locations -Kimi Code CLI stores all runtime data — the config file, session history, login credentials, and diagnostic logs — under `~/.kimi-code/`. This page helps you understand where each type of data lives, what it is for, and how to clean up or relocate it when needed. +Kimi Code CLI stores the config file, session history, login credentials, diagnostic logs, and other runtime data under `~/.kimi-code/`. This page helps you understand where each type of data lives, what it is for, and how to clean up or relocate it when needed. ## Data root directory @@ -16,7 +16,7 @@ If you need to move the data directory elsewhere (for example, to isolate config export KIMI_CODE_HOME="$HOME/.config/kimi-code" ``` -Once set, **all** Kimi Code data — config, sessions, logs, OAuth credentials, Kimi-specific user Skills, global `AGENTS.md`, and more — lands under the new path. For the full reference on `KIMI_CODE_HOME`, see [Environment variables](./env-vars.md). +Once set, **all** Kimi Code data lands under the new path: config, sessions, logs, OAuth credentials, Kimi-specific user Skills, global `AGENTS.md`, and more. For the full reference on `KIMI_CODE_HOME`, see [Environment variables](./env-vars.md). ::: tip Note @@ -80,7 +80,7 @@ Inside each session directory: - **`agents/main/plans/`**: plan files written in Plan mode, named by plan id (`.md`). - **`agents/agent-0/` etc.**: sub-Agent instance directories, each containing their own `wire.jsonl`. - **`logs/kimi-code.log`**: diagnostic log for this session; only present when a diagnostic event occurs. -- **`tasks/`**: background task persistence — `tasks/.json` stores status/pid/exit code; `tasks//output.log` stores output. +- **`tasks/`**: background task persistence. `tasks/.json` stores status/pid/exit code; `tasks//output.log` stores output. - **`cron/`**: scheduled task persistence; reloaded into the scheduler when the session is resumed with `kimi --session`. See [Scheduled tasks](../reference/tools.md#scheduled-tasks). ## Built-in tool cache diff --git a/docs/en/configuration/env-vars.md b/docs/en/configuration/env-vars.md index a3914764e4f..4ee6487890d 100644 --- a/docs/en/configuration/env-vars.md +++ b/docs/en/configuration/env-vars.md @@ -1,11 +1,11 @@ # Environment variables -Kimi Code CLI uses environment variables to control a small number of runtime behaviors — relocating the data directory, turning off telemetry, and temporarily switching models without touching the config file. +Kimi Code CLI uses environment variables to control a small number of runtime behaviors: relocating the data directory, turning off telemetry, and temporarily switching models without touching the config file. ::: warning Important: API keys are not configured here -Credential variables such as `KIMI_API_KEY`, `ANTHROPIC_API_KEY`, and `OPENAI_API_KEY` are **not** read automatically from shell environment variables. Running `export KIMI_API_KEY=xxx` in the terminal does not give any provider its key — they must be written in `config.toml` under `[providers.]` or the `[providers..env]` sub-table. +Credential variables such as `KIMI_API_KEY`, `ANTHROPIC_API_KEY`, and `OPENAI_API_KEY` are **not** read automatically from shell environment variables. Running `export KIMI_API_KEY=xxx` in the terminal does not give any provider its key. They must be written in `config.toml` under `[providers.]` or the `[providers..env]` sub-table. -The only exception is the `KIMI_MODEL_*` family, which is an explicit channel that *does* read credentials from the shell — see [Define a model from environment variables](#define-a-model-from-environment-variables-kimi-model). +The only exception is the `KIMI_MODEL_*` family, an explicit channel that *does* read credentials from the shell. See [Define a model from environment variables](#define-a-model-from-environment-variables-kimi_model_). For background, see [Config overrides: provider credentials](./overrides.md#provider-credentials). ::: @@ -34,11 +34,15 @@ export KIMI_DISABLE_TELEMETRY=1 ### `KIMI_MODEL_*` family -Switch models temporarily without modifying `config.toml` — when `KIMI_MODEL_NAME` is set, the CLI synthesizes a temporary provider in memory; the change does not persist after restart. See [Define a model from environment variables](#define-a-model-from-environment-variables-kimi-model). +Switch models temporarily without modifying `config.toml`: when `KIMI_MODEL_NAME` is set, the CLI synthesizes a temporary provider in memory, and the change does not persist after restart. See [Define a model from environment variables](#define-a-model-from-environment-variables-kimi_model_). ### `KIMI_CODE_CUSTOM_HEADERS` -Attaches custom HTTP headers to every outbound model request — both LLM chat requests (across all provider protocols) and `/models` listing requests. Useful when a gateway routes by header, for example to pin a specific cluster: +::: info Added +Added in 0.20.2. +::: + +Attaches custom HTTP headers to every outbound model request: both LLM chat requests (across all provider protocols) and `/models` listing requests carry them. Useful when a gateway routes by header, for example to pin a specific cluster: ```sh export KIMI_CODE_CUSTOM_HEADERS=$'X-Gateway-Cluster: my-cluster\nX-Custom-Tag: debug' @@ -46,15 +50,11 @@ export KIMI_CODE_CUSTOM_HEADERS=$'X-Gateway-Cluster: my-cluster\nX-Custom-Tag: d The format mirrors `ANTHROPIC_CUSTOM_HEADERS`: newline-separated `Name: Value` lines. Names and values are trimmed, and lines without a colon are ignored. -::: info Added -Added in 0.20.2. -::: - -> Precedence: the Kimi identity headers (`User-Agent`, `X-Msh-*`) and a provider's `custom_headers` in `config.toml` (see [Config files](./config-files.md#providers)) override same-named entries here. Authentication is protocol-dependent: on the `kimi`, `openai`, and `openai_responses` protocols an exact `Authorization` entry replaces the generated bearer token, while `/models` listing requests keep their own authentication. A case variant such as `authorization` is never treated as the same name — it is combined with the real header, which can break requests. Do not use this variable for authentication or other reserved headers. Use `custom_headers` when headers need to differ per provider. +> Precedence: the Kimi identity headers (`User-Agent`, `X-Msh-*`) and a provider's `custom_headers` in `config.toml` (see [Config files](./config-files.md#providers)) override same-named entries here. Authentication is protocol-dependent: on the `kimi`, `openai`, and `openai_responses` protocols an exact `Authorization` entry replaces the generated bearer token, while `/models` listing requests keep their own authentication. A case variant such as `authorization` is never treated as the same name. It merges with the real header, which can break requests. Do not use this variable for authentication or other reserved headers. Use `custom_headers` when headers need to differ per provider. ## Provider credential key names (written in config.toml) -The key names below are not read directly from the shell — they are key names written inside the `[providers..env]` sub-table of `config.toml`, serving as fallback values for `api_key` / `base_url`. The CLI reads only from the config file, not from `process.env`. +The key names below are not read directly from the shell. They are key names written inside the `[providers..env]` sub-table of `config.toml`, serving as fallback values for `api_key` / `base_url`. The CLI reads only from the config file, not from `process.env`. This design lets you keep familiar key name conventions while centralizing secret management in the config file: @@ -80,7 +80,7 @@ Key names per provider: | `GOOGLE_CLOUD_LOCATION` | Vertex AI | None | ::: warning -`GOOGLE_APPLICATION_CREDENTIALS` (path to a service account JSON file) is the only exception that goes through the system environment variable mechanism — it is read by the Google SDK directly via the standard ADC flow, and the CLI does not participate. All other key names must be placed in the `[providers..env]` sub-table to take effect. +`GOOGLE_APPLICATION_CREDENTIALS` (path to a service account JSON file) is the only exception that goes through the system environment variable mechanism. It is read by the Google SDK directly via the standard ADC flow; the CLI does not participate. All other key names must be placed in the `[providers..env]` sub-table to take effect. ::: For the full provider type and field reference, see [Providers and models](./providers.md). @@ -101,7 +101,7 @@ This group of variables redirects OAuth authentication and managed service endpo ## Define a model from environment variables (`KIMI_MODEL_*`) -Want to switch models for testing without touching `config.toml`? When `KIMI_MODEL_NAME` is set, the CLI synthesizes a temporary provider and model alias from the `KIMI_MODEL_*` variables in memory — nothing is written back to the config file. These variables take priority over `default_model` in `config.toml`, but the `-m ` option at startup still has the highest priority. +Want to switch models for testing without touching `config.toml`? When `KIMI_MODEL_NAME` is set, the CLI synthesizes a temporary provider and model alias from the `KIMI_MODEL_*` variables in memory; nothing is written back to the config file. These variables take priority over `default_model` in `config.toml`, but the `-m ` option at startup still has the highest priority. ```sh export KIMI_MODEL_NAME="kimi-for-coding" @@ -137,40 +137,40 @@ Switches that control the behavior of subsystems such as telemetry, background t | Variable | Purpose | Valid values | | --- | --- | --- | | `KIMI_DISABLE_TELEMETRY` | Disable anonymous telemetry reporting | `1`, `true`, `yes`, `y` (case-insensitive) | -| `KIMI_CODE_PASSWORD` | Set a parallel auth credential for the `kimi web` local server, valid alongside the bearer token; recommended when binding the server beyond loopback — see [Using Kimi Code in the browser: Security notes](../guides/web.md#security-notes) | Any non-empty string; when unset, only the token is valid | -| `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` | Whether to keep background tasks when the session closes; takes higher priority than `config.toml`. The default is to stop them on exit | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | -| `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS` | Cap on concurrently running background tasks; takes higher priority than `[background] max_running_tasks` in `config.toml` (unset means no cap) | Positive integer; invalid values are ignored | -| `KIMI_IMAGE_MAX_EDGE_PX` | Longest-edge ceiling (px) for image compression; takes higher priority than `[image] max_edge_px` in `config.toml` (default `2000`) | Positive integer; invalid values are ignored | -| `KIMI_IMAGE_READ_BYTE_BUDGET` | Per-image byte budget for model-initiated image reads (`ReadMediaFile` default reads); takes higher priority than `[image] read_byte_budget` in `config.toml` (default `262144`, i.e. 256 KB) | Positive integer; invalid values are ignored | -| `KIMI_CODE_PLUGIN_MARKETPLACE_URL` | Override the plugin marketplace JSON loaded by `/plugins`; useful for dev loopback servers, staging CDN files, or alternate marketplace directories | `https://code.kimi.com/kimi-code/plugins/marketplace.json`; also accepts `http://`, `file://` URLs, and local paths | -| `KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY` | Cap how many AgentSwarm subagents run concurrently during the initial ramp; leave unset for no cap | Positive integer; invalid values fail fast | -| `KIMI_SUBAGENT_TIMEOUT_MS` | Maximum wall-clock time (ms) a single `Agent` subagent may run; takes higher priority than `[subagent] timeout_ms` in `config.toml` (default `7200000`, i.e. 2 hours) | Positive integer; invalid values fall back to the config or default | -| `KIMI_CODE_SWARM_TIMEOUT_MS` | Maximum wall-clock time (ms) a single `AgentSwarm` subagent may run; takes higher priority than `[swarm] timeout_ms` in `config.toml` (default `7200000`, i.e. 2 hours) | Positive integer; invalid values fall back to the config or default | -| `KIMI_CODE_IDENTITY_NAME` | Display name the agent calls itself in the system prompt; takes higher priority than `[identity] name` in `config.toml` and is never written back to it | Any non-empty string; blank values read as unset | -| `KIMI_CODE_IDENTITY_SLUG` | Protocol identifier for the `User-Agent` product token sent to third-party providers and the MCP client name; takes higher priority than `[identity] slug`. Derived from the name when unset | Any non-empty string; normalized to lowercase with non-alphanumeric runs folded to `-` | -| `KIMI_CODE_BUILTIN_PRODUCT_SKILLS` | Whether the built-in skills documenting Kimi Code itself are offered to the model; takes higher priority than `builtin_product_skills` in `config.toml` (default enabled) | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | -| `KIMI_CODE_TUI_FULL_SCREEN` | Enable the experimental fullscreen alternate-screen UI: scrollable transcript viewport, mouse text selection, clickable links, and Ctrl-Shift-F transcript search | `1` enables it; anything else keeps the regular inline UI | -| `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL` | The [subagent model pool](./config-files.md#subagent-model-pool) is enabled by default in every launch mode, including the interactive TUI; set a falsy value to disable it; the master `KIMI_CODE_EXPERIMENTAL_FLAG=1` also enables it | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | -| `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK` | Enable the experimental `fork` parameter on the `Agent` and `AgentSwarm` tools, letting the model start a subagent with a snapshot of the calling agent's conversation history instead of an empty context; the master `KIMI_CODE_EXPERIMENTAL_FLAG=1` also enables it | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | -| `KIMI_MCP_STARTUP_TIMEOUT_MS` | Global default connection timeout (ms) for all MCP servers; takes higher priority than `[mcp] startup_timeout_ms` in `config.toml`, but a per-server `startupTimeoutMs` in `mcp.json` still wins (default `30000`) | Integer from `1` to `2147483647`; invalid values are ignored | -| `KIMI_MCP_TOOL_TIMEOUT_MS` | Global default single tool-call timeout (ms) for all MCP servers; takes higher priority than `[mcp] tool_timeout_ms` in `config.toml`, but a per-server `toolTimeoutMs` in `mcp.json` still wins (default `60000`) | Integer from `1` to `2147483647`; invalid values are ignored | -| `KIMI_LOOP_MAX_STEPS_PER_TURN` | Maximum Agent steps per turn; takes higher priority than `[loop_control] max_steps_per_turn` in `config.toml` (unset or `0` means unlimited) | Non-negative integer; invalid values are ignored | -| `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP` | Maximum total attempts for a failing step (including the initial attempt); takes higher priority than `[loop_control] max_attempts_per_step` in `config.toml` (default `10`). The deprecated `KIMI_LOOP_MAX_RETRIES_PER_STEP` is still honored with a warning when this variable is unset | Non-negative integer; invalid values are ignored | -| `KIMI_CODE_INFINITE_RETRY` | Retry every failed LLM request indefinitely — turn steps and background operations such as compaction alike — instead of failing the task; waits use exponential backoff (capped at 32 s) and honor the server's `Retry-After` header, and aborting still cancels immediately. Intended for long-running unattended evaluations against endpoints that may fail temporarily | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | -| `KIMI_TOKEN_COUNTING_STRATEGY` | Which context token count is reported externally (the context-size display); takes higher priority than `[token_counting] strategy` in `config.toml` (default `measured+estimated`) | `measured+estimated`, `measured`, `estimated` (case-insensitive); invalid values are ignored | -| `KIMI_WEB_SEARCH_BASE_URL` | API URL of the web search (`WebSearch`) service; takes higher priority than `[services.moonshot_search] base_url` in `config.toml`, and enables the service without that config section. Persisted credentials and custom headers are not forwarded to an env-selected endpoint | Non-blank string; blank values are ignored | -| `KIMI_WEB_SEARCH_API_KEY` | API key of the web search (`WebSearch`) service; replaces both the configured API key and OAuth credential when set | Non-blank string; blank values are ignored | -| `KIMI_WEB_FETCH_BASE_URL` | API URL of the web fetch (`FetchURL`) service; takes higher priority than `[services.moonshot_fetch] base_url`. Persisted credentials and custom headers are not forwarded to an env-selected endpoint. Without an env or config endpoint, signed-in users try the managed Kimi OAuth fetch service before direct local requests | Non-blank string; blank values are ignored | -| `KIMI_WEB_FETCH_API_KEY` | API key of the web fetch (`FetchURL`) service; replaces both the configured API key and OAuth credential when set | Non-blank string; blank values are ignored | -| `KIMI_CODE_EXPERIMENTAL_FLAG` | Enable all registered experimental features for this process; a per-feature `KIMI_CODE_EXPERIMENTAL_` variable or an explicit entry in the `[experimental]` section of `config.toml` takes precedence over it; it does not select the agent engine | `1`, `true`, `yes`, `on` | -| `KIMI_CODE_LEGACY_FLAG` | Use the legacy `agent-core` engine for `kimi`, `kimi -p`, `kimi doctor`, `kimi export`, and `kimi provider`; these commands use `agent-core-v2` by default | `1`, `true`, `yes`, `on` | +| `KIMI_CODE_PASSWORD` | Parallel auth credential for `kimi web`, recommended when binding beyond loopback (see [Security notes](../guides/web.md#security-notes)) | Any non-empty string; when unset, only the token is valid | +| `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` | Keep background tasks when the session closes; higher priority than `config.toml` (default: stop them on exit) | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | +| `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS` | Cap on concurrently running background tasks; higher priority than `[background] max_running_tasks` (unset = no cap) | Positive integer; invalid values are ignored | +| `KIMI_IMAGE_MAX_EDGE_PX` | Longest-edge ceiling (px) for image compression; higher priority than `[image] max_edge_px` (default `2000`) | Positive integer; invalid values are ignored | +| `KIMI_IMAGE_READ_BYTE_BUDGET` | Per-image byte budget for model-initiated image reads; higher priority than `[image] read_byte_budget` (default `262144`) | Positive integer; invalid values are ignored | +| `KIMI_CODE_PLUGIN_MARKETPLACE_URL` | Override the marketplace JSON loaded by `/plugins`; default `https://code.kimi.com/kimi-code/plugins/marketplace.json` | Also accepts `http://`, `file://` URLs, and local paths | +| `KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY` | Cap on AgentSwarm subagents running concurrently during the initial ramp; unset = no cap | Positive integer; invalid values fail fast | +| `KIMI_SUBAGENT_TIMEOUT_MS` | Max wall-clock time (ms) a single `Agent` subagent may run; higher priority than `[subagent] timeout_ms` | Positive integer; invalid values fall back to the config or default | +| `KIMI_CODE_SWARM_TIMEOUT_MS` | Max wall-clock time (ms) an `AgentSwarm` subagent may run; higher priority than `[swarm] timeout_ms` | Positive integer; invalid values fall back to the config or default | +| `KIMI_CODE_IDENTITY_NAME` | Name the agent calls itself in the system prompt; higher priority than `[identity] name`, never written back | Any non-empty string; blank values read as unset | +| `KIMI_CODE_IDENTITY_SLUG` | `User-Agent` product token and MCP client name; higher priority than `[identity] slug`; derived from the name when unset | Any non-empty string; normalized to lowercase with non-alphanumeric runs folded to `-` | +| `KIMI_CODE_BUILTIN_PRODUCT_SKILLS` | Offer the built-in skills documenting Kimi Code itself to the model; higher priority than `builtin_product_skills` | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | +| `KIMI_CODE_TUI_FULL_SCREEN` | Experimental fullscreen UI: scrollable transcript, mouse selection, clickable links, Ctrl-Shift-F search | `1` enables it; anything else keeps the regular inline UI | +| `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL` | The [subagent model pool](./config-files.md#subagent-model-pool) is enabled by default in all launch modes; set a falsy value to disable it; `KIMI_CODE_EXPERIMENTAL_FLAG=1` also enables it | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | +| `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK` | Experimental `fork` parameter on `Agent`/`AgentSwarm`: start the subagent from a snapshot of the caller's history instead of an empty context; `KIMI_CODE_EXPERIMENTAL_FLAG=1` also enables it | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | +| `KIMI_MCP_STARTUP_TIMEOUT_MS` | Global default connection timeout (ms) for MCP servers; overrides the config file, but `mcp.json` `startupTimeoutMs` still wins | Integer from `1` to `2147483647`; invalid values are ignored | +| `KIMI_MCP_TOOL_TIMEOUT_MS` | Global default single tool-call timeout (ms) for MCP servers; overrides the config file, but `mcp.json` `toolTimeoutMs` still wins | Integer from `1` to `2147483647`; invalid values are ignored | +| `KIMI_LOOP_MAX_STEPS_PER_TURN` | Max Agent steps per turn; higher priority than `[loop_control] max_steps_per_turn` (`0` = unlimited) | Non-negative integer; invalid values are ignored | +| `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP` | Max total attempts for a failing step (including the first); higher priority than `[loop_control] max_attempts_per_step` | Non-negative integer; invalid values are ignored | +| `KIMI_CODE_INFINITE_RETRY` | Retry failed LLM requests indefinitely; exponential backoff (32 s cap) honoring `Retry-After`; aborting still cancels immediately | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` | +| `KIMI_TOKEN_COUNTING_STRATEGY` | Context token count reported externally; higher priority than `[token_counting] strategy` | `measured+estimated`, `measured`, `estimated` (case-insensitive); invalid values are ignored | +| `KIMI_WEB_SEARCH_BASE_URL` | Web search (`WebSearch`) service API URL; higher priority than the config file; credentials and custom headers not forwarded | Non-blank string; blank values are ignored | +| `KIMI_WEB_SEARCH_API_KEY` | Web search (`WebSearch`) service API key; replaces both the configured key and the OAuth credential | Non-blank string; blank values are ignored | +| `KIMI_WEB_FETCH_BASE_URL` | Web fetch (`FetchURL`) service API URL; higher priority than the config file; credentials not forwarded. Without an endpoint, signed-in users get the managed Kimi OAuth fetch service before direct local requests | Non-blank string; blank values are ignored | +| `KIMI_WEB_FETCH_API_KEY` | Web fetch (`FetchURL`) service API key; replaces both the configured key and the OAuth credential | Non-blank string; blank values are ignored | +| `KIMI_CODE_EXPERIMENTAL_FLAG` | Enable all registered experimental features for this process; does not select the agent engine | `1`, `true`, `yes`, `on` | +| `KIMI_CODE_LEGACY_FLAG` | Legacy `agent-core` engine for `kimi`, `kimi -p`, `kimi doctor`, `kimi export`, and `kimi provider` (default: `agent-core-v2`) | `1`, `true`, `yes`, `on` | | `KIMI_SHELL_PATH` | Override the Git Bash path on Windows (used when auto-detection fails) | Absolute path | | `KIMI_MODEL_MAX_COMPLETION_TOKENS` | Hard cap on `max_completion_tokens` per LLM step; applies to the `kimi` provider only | Positive integer; `0` or negative disables clamping | -| `KIMI_MODEL_TEMPERATURE` | Sampling temperature for every request; applies to the `kimi` provider only (global — independent of `KIMI_MODEL_NAME`) | Number, e.g. `0.3` | -| `KIMI_MODEL_TOP_P` | Nucleus-sampling `top_p` for every request; applies to the `kimi` provider only (global) | Number, e.g. `0.95` | -| `KIMI_MODEL_THINKING_EFFORT` | Force a specific thinking effort on the wire (`thinking.effort`), bypassing the model's declared `support_efforts`; applies to the `kimi` provider only, and only while Thinking is on | An effort value, e.g. `max` | -| `KIMI_MODEL_THINKING_KEEP` | Preserved-thinking passthrough; on `kimi` sent as `thinking.keep`, on `anthropic` (Claude and Kimi's Anthropic-compatible mode) sent as a `context_management` `clear_thinking_20251015` edit (enabling keep routes Anthropic requests to the beta Messages API); overrides `[thinking] keep` (which defaults to `"all"`); only injected while Thinking is on | A value the API accepts, e.g. `all`; an off-value (`false`/`0`/`no`/`off`/`none`/`null`) disables it | -| `KIMI_CODE_NO_AUTO_UPDATE` | Fully disable the update preflight — no check, background install, or prompt. Legacy alias `KIMI_CLI_NO_AUTO_UPDATE` is also honored | Truthy: `1`/`true`/`yes`/`on` | +| `KIMI_MODEL_TEMPERATURE` | Sampling temperature for every request; `kimi` provider only (global, independent of `KIMI_MODEL_NAME`) | Number, e.g. `0.3` | +| `KIMI_MODEL_TOP_P` | Nucleus-sampling `top_p` for every request; `kimi` provider only (global) | Number, e.g. `0.95` | +| `KIMI_MODEL_THINKING_EFFORT` | Force a thinking effort (`thinking.effort`), bypassing the model's declared `support_efforts`; `kimi` provider only | An effort value, e.g. `max` | +| `KIMI_MODEL_THINKING_KEEP` | Preserved-thinking passthrough: `thinking.keep` on `kimi`, a `clear_thinking_20251015` edit on `anthropic`; overrides `[thinking] keep` | A value the API accepts, e.g. `all`; an off-value (`false`/`0`/`no`/`off`/`none`/`null`) disables it | +| `KIMI_CODE_NO_AUTO_UPDATE` | Fully disable the update preflight: no check, background install, or prompt. Legacy alias `KIMI_CLI_NO_AUTO_UPDATE` also honored | Truthy: `1`/`true`/`yes`/`on` | | `KIMI_DISABLE_CRON` | Disable the scheduled-task tool (`CronCreate` rejects new schedules; existing tasks do not fire) | `1` to disable | The `KIMI_CODE_INFINITE_RETRY`, `KIMI_CODE_IDENTITY_*`, and `KIMI_CODE_BUILTIN_PRODUCT_SKILLS` variables are read by the default `agent-core-v2` engine. The legacy `kimi` / `kimi -p` path selected with `KIMI_CODE_LEGACY_FLAG=1` ignores them. @@ -203,16 +203,22 @@ The CLI also reads several standard system variables to detect the runtime envir ## HTTP proxy -Kimi Code honors the standard proxy environment variables for all outbound traffic — model API calls, MCP servers, web tools, telemetry, sign-in, and update checks: +Kimi Code honors the standard proxy environment variables for all outbound traffic: model API calls, MCP servers, web tools, telemetry, sign-in, and update checks: - `HTTP_PROXY` / `http_proxy`: proxy for `http://` requests - `HTTPS_PROXY` / `https_proxy`: proxy for `https://` requests - `ALL_PROXY` / `all_proxy`: fallback proxy used when the scheme-specific variable is unset; this is where a SOCKS proxy is usually set - `NO_PROXY` / `no_proxy`: comma-separated hosts that bypass the proxy -Both HTTP(S) and SOCKS proxies are supported. A SOCKS proxy is recognized by its scheme — `socks5://`, `socks5h://`, `socks4://`, or `socks://` (an alias for `socks5://`) — and is typically set via `ALL_PROXY` (the form used by tools like Clash and V2RayN). An HTTP(S) proxy takes precedence over `ALL_PROXY` for HTTP/HTTPS traffic. +### Proxy types and precedence + +Both HTTP(S) and SOCKS proxies are supported. A SOCKS proxy is recognized by its scheme: `socks5://`, `socks5h://`, `socks4://`, or `socks://` (an alias for `socks5://`). It is typically set via `ALL_PROXY` (the form used by tools like Clash and V2RayN). An HTTP(S) proxy takes precedence over `ALL_PROXY` for HTTP/HTTPS traffic. + +### Activation conditions and loopback addresses + +The proxy is applied only when one of these variables is set; otherwise connections are made directly. Loopback hosts (`localhost`, `127.0.0.1`, `::1`) always bypass the proxy, so a local server such as a localhost MCP server keeps working when a proxy is configured. Add your own internal hosts to `NO_PROXY` to exempt them too. -The proxy is applied only when one of these variables is set; otherwise connections are made directly. Loopback hosts (`localhost`, `127.0.0.1`, `::1`) always bypass the proxy, so a local server such as a localhost MCP server keeps working when a proxy is configured — add your own internal hosts to `NO_PROXY` to exempt them too. +### MCP child processes Stdio MCP servers that run as Node child processes honor `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` automatically when the child's Node version supports `NODE_USE_ENV_PROXY` (Node ≥ 22.21 or ≥ 24.5); SOCKS proxying applies to Kimi Code's own traffic only. diff --git a/docs/en/configuration/overrides.md b/docs/en/configuration/overrides.md index 94e126c77fc..14eb6889105 100644 --- a/docs/en/configuration/overrides.md +++ b/docs/en/configuration/overrides.md @@ -1,10 +1,10 @@ # Config overrides -Kimi Code CLI has three places where runtime parameters can be influenced: the config file, command-line options, and environment variables. They are not a simple "whoever has higher priority wins" relationship — the three serve different scenarios and have non-overlapping scopes: +Kimi Code CLI has three places where runtime parameters can be influenced: the config file, command-line options, and environment variables. They are not a simple priority stack: the three serve different scenarios and have non-overlapping scopes: - **Config file** stores long-term preferences (model, keys, loop control, etc.); takes effect on every startup - **Command-line options** make one-off changes for the current startup; discarded after exit -- **Environment variables** primarily handle data directory location, OAuth endpoint switching, and a small number of runtime switches — **not a general fallback mechanism for config fields** +- **Environment variables** primarily handle data directory location, OAuth endpoint switching, and a small number of runtime switches. They are **not a general fallback mechanism for config fields**. This distinction matters: many users run `export KIMI_API_KEY=xxx` in the shell expecting the CLI to pick it up automatically, but it does not. See [Provider credentials](#provider-credentials) below for why. @@ -13,7 +13,7 @@ This distinction matters: many users run `export KIMI_API_KEY=xxx` in the shell Environment variables fall into three categories by function and cannot be collapsed into a single linear priority order: 1. **Locating the config file**: `KIMI_CODE_HOME` sets the data root directory, making the config file path `$KIMI_CODE_HOME/config.toml`. This step runs before all other resolution and is not a fallback for individual parameters. -2. **Runtime switches**: A small set of variables like `KIMI_DISABLE_TELEMETRY` directly shut down the corresponding subsystem — even if `config.toml` has `telemetry = true`, setting this variable to a truthy value disables telemetry. The semantics are "additionally disable", not "ordinary override". +2. **Runtime switches**: A small set of variables like `KIMI_DISABLE_TELEMETRY` directly shut down the corresponding subsystem. Even if `config.toml` has `telemetry = true`, a truthy value for this variable disables telemetry. The semantics are "additionally disable", not "ordinary override". 3. **Runtime endpoints and diagnostics**: Variables like `KIMI_CODE_OAUTH_HOST`, `KIMI_CODE_BASE_URL`, and `KIMI_LOG_LEVEL` are read when the OAuth or logging subsystems initialize. For the full list, see [Environment variables](./env-vars.md). ## Priority for ordinary runtime parameters @@ -23,13 +23,13 @@ For ordinary runtime parameters such as model alias, Plan mode, permission mode, 1. **Command-line options** (`-m`, `--plan`, `--yolo`, etc.): apply only to the current startup 2. **User config file** (`~/.kimi-code/config.toml`): stores long-term preferences -A small number of environment variables explicitly override specific config file fields — for example, `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` has higher priority than `[background].keep_alive_on_exit`. These exceptions are noted in [Environment variables](./env-vars.md) and in the relevant field descriptions in [Configuration files](./config-files.md). +A small number of environment variables explicitly override specific config file fields. For example, `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` has higher priority than `[background].keep_alive_on_exit`. These exceptions are noted in [Environment variables](./env-vars.md) and in the relevant field descriptions in [Configuration files](./config-files.md). ::: warning -**Ordinary runtime parameters do not fall back to shell environment variables.** Provider `api_key` / `base_url` are read only from `config.toml` (including the `[providers..env]` sub-table) and do not fall back to `export`-ed shell variables. The only exception is the explicit `KIMI_MODEL_*` channel — see [Define a model from environment variables](./env-vars.md#define-a-model-from-environment-variables-kimi-model). +**Ordinary runtime parameters do not fall back to shell environment variables.** Provider `api_key` / `base_url` are read only from `config.toml` (including the `[providers..env]` sub-table) and do not fall back to `export`-ed shell variables. The only exception is the explicit `KIMI_MODEL_*` channel; see [Define a model from environment variables](./env-vars.md#define-a-model-from-environment-variables-kimi_model_). ::: -The CLI currently reads a single user-level config file and has no project-level config file mechanism. To isolate config between different projects, point `KIMI_CODE_HOME` at different data directories — see [Common scenarios](#common-scenarios) below. +The CLI currently reads a single user-level config file and has no project-level config file mechanism. To isolate config between different projects, point `KIMI_CODE_HOME` at different data directories; see [Common scenarios](#common-scenarios) below. ## Provider credentials @@ -37,15 +37,15 @@ Provider credentials (`api_key`, `base_url`) follow their own resolution rules, For a single provider, credentials are resolved in this order: -1. `[providers.].api_key` — key written directly in the config file; highest priority -2. The matching key inside the `[providers..env]` sub-table (`KIMI_API_KEY`, `ANTHROPIC_API_KEY`, etc.) — consulted only when `api_key` is empty -3. If both are absent — startup fails with an error indicating the provider is missing credentials +1. `[providers.].api_key`: key written directly in the config file; highest priority +2. The matching key inside the `[providers..env]` sub-table (`KIMI_API_KEY`, `ANTHROPIC_API_KEY`, etc.): consulted only when `api_key` is empty +3. If both are absent, startup fails with an error indicating the provider is missing credentials `base_url` is resolved the same way: first `[providers.].base_url`, then the `*_BASE_URL` key in `[providers..env]`. -> The `[providers..env]` sub-table is just a TOML section in the config file — it does not write anything into the shell environment. It is only consulted when the corresponding direct field (`api_key` / `base_url`) is empty. +> The `[providers..env]` sub-table is just a TOML section in the config file and does not write anything into the shell environment. It is only consulted when the corresponding direct field (`api_key` / `base_url`) is empty. -For the full list of credential key names, see [Environment variables: provider credential key names](./env-vars.md#provider-credential-key-names-written-in-config-toml). +For the full list of credential key names, see [Environment variables: provider credential key names](./env-vars.md#provider-credential-key-names-written-in-configtoml). ## Command-line options @@ -76,13 +76,13 @@ Mutual exclusion rules (startup fails if violated): ## Common scenarios -**Isolated test environment** — use a separate data directory to avoid polluting the main config and sessions: +**Isolated test environment**: use a separate data directory to avoid polluting the main config and sessions: ```sh KIMI_CODE_HOME="$PWD/.kimi-sandbox" kimi ``` -**One-off test key** — since provider credentials are read only from the config file, write a test key into the `env` sub-table: +**One-off test key**: since provider credentials are read only from the config file, write a test key into the `env` sub-table: ```toml [providers.kimi.env] diff --git a/docs/en/configuration/providers.md b/docs/en/configuration/providers.md index 43aeabb4427..ba7324c349e 100644 --- a/docs/en/configuration/providers.md +++ b/docs/en/configuration/providers.md @@ -1,6 +1,6 @@ # Providers and models -Kimi Code CLI supports connecting to multiple LLM platforms simultaneously — one-click login via the Kimi Code managed service, connecting Claude with an Anthropic API key, or connecting third-party inference services via the OpenAI-compatible protocol. Each provider corresponds to a specific API protocol; models are declared on top of providers with their own name, context length, and capabilities. This page explains how to configure each type of provider in `config.toml`. +Kimi Code CLI supports connecting to multiple LLM platforms simultaneously: one-click login via the Kimi Code managed service, connecting Claude with an Anthropic API key, or connecting third-party inference services via the OpenAI-compatible protocol. Each provider corresponds to a specific API protocol; models are declared on top of providers with their own name, context length, and capabilities. This page explains how to configure each type of provider in `config.toml`. ## Supported provider types @@ -8,21 +8,23 @@ The `type` field in the `providers` table determines which protocol implementati | Type | Protocol | Typical use | | --- | --- | --- | -| `kimi` | OpenAI-compatible | Kimi Code managed service, Kimi Platform API key | -| `anthropic` | Anthropic Messages | Claude model family | -| `openai` | OpenAI Chat Completions | OpenAI and compatible services, DeepSeek, Qwen, etc. | -| `openai_responses` | OpenAI Responses API | OpenAI's newer Responses interface | -| `google-genai` | Google GenAI | Gemini API | -| `vertexai` | Google GenAI on Vertex | Google Cloud Vertex AI | +| [`kimi`](#kimi) | OpenAI-compatible | Kimi Code managed service, Kimi Platform API key | +| [`anthropic`](#anthropic) | Anthropic Messages | Claude model family | +| [`openai`](#openai) | OpenAI Chat Completions | OpenAI and compatible services, DeepSeek, Qwen, etc. | +| [`openai_responses`](#openai_responses) | OpenAI Responses API | OpenAI's newer Responses interface | +| [`google-genai`](#google-genai) | Google GenAI | Gemini API | +| [`vertexai`](#vertexai) | Google GenAI on Vertex | Google Cloud Vertex AI | -All providers communicate with models in streaming mode by default. Capabilities such as thinking, vision, and tool use are matched automatically by model name prefix — you typically do not need to declare them manually. +All providers communicate with models in streaming mode by default. Capabilities such as thinking, vision, and tool use are matched automatically by model name prefix, so you typically do not need to declare them manually. -**Credential priority**: `api_key` direct field > `[providers..env]` sub-table key > if both are absent, startup fails with an error. The CLI does not fall back to shell environment variables for credentials — see [Config overrides: provider credentials](./overrides.md#provider-credentials). +**Credential priority**: `api_key` direct field > `[providers..env]` sub-table key > if both are absent, startup fails with an error. The CLI does not fall back to shell environment variables for credentials. See [Config overrides: provider credentials](./overrides.md#provider-credentials). ## `/provider` — interactive provider management Prefer not to edit TOML by hand? Type `/provider` in the TUI to open the **provider manager**, where you can interactively add or remove providers. +![The /provider provider manager](../../media/provider-manager.jpg) + The manager displays providers as a list of entries grouped by source. Navigation: - ↑/↓ to move the cursor, ←/→ to page @@ -55,7 +57,7 @@ base_url = "https://api.moonshot.ai/v1" api_key = "sk-xxxxx" ``` -> When using the Kimi Code managed service, running `/login` automatically configures `base_url` and credentials — no manual setup needed. +> When using the Kimi Code managed service, running `/login` automatically configures `base_url` and credentials, so no manual setup is needed. ## `anthropic` @@ -134,7 +136,7 @@ base_url = "https://your-gateway.example" Shares the same implementation as `google-genai`; setting `type = "vertexai"` switches to the Vertex AI access path. -Authentication follows the standard Google Cloud ADC flow (`gcloud auth application-default login` or a `GOOGLE_APPLICATION_CREDENTIALS` service account JSON) — this part is unrelated to Kimi Code. **The project ID and region must be written in the `[providers.vertexai.env]` sub-table** — simply `export GOOGLE_CLOUD_PROJECT` in the shell will not be read by the CLI. +Authentication follows the standard Google Cloud ADC flow (`gcloud auth application-default login` or a `GOOGLE_APPLICATION_CREDENTIALS` service account JSON); this part is unrelated to Kimi Code. **The project ID and region must be written in the `[providers.vertexai.env]` sub-table**. Simply `export GOOGLE_CLOUD_PROJECT` in the shell will not be read by the CLI. ```toml [providers.vertexai] @@ -150,11 +152,11 @@ gcloud auth application-default login # one-time authentication kimi ``` -To route Vertex requests through a custom (e.g. proxied) endpoint, set `base_url` (or the `GOOGLE_VERTEX_BASE_URL` env var); when omitted, the SDK default regional `*-aiplatform.googleapis.com` host is used. As with `google-genai`, give the host root only — the SDK appends `/v1beta1/publishers/google/models/…` itself. +To route Vertex requests through a custom (e.g. proxied) endpoint, set `base_url` (or the `GOOGLE_VERTEX_BASE_URL` env var); when omitted, the SDK default regional `*-aiplatform.googleapis.com` host is used. As with `google-genai`, give the host root only. The SDK appends `/v1beta1/publishers/google/models/…` itself. ## OAuth and credential injection -The Kimi Code managed service uses OAuth rather than static API keys. After running `/login`, the built-in authentication toolchain automatically writes and refreshes credentials — no manual configuration is needed in `config.toml` for this. +The Kimi Code managed service uses OAuth rather than static API keys. After running `/login`, the built-in authentication toolchain automatically writes and refreshes credentials, so no manual configuration is needed in `config.toml` for this. ## Next steps diff --git a/docs/en/customization/agents.md b/docs/en/customization/agents.md index f3e0d3d1a6f..743ab92f8a8 100644 --- a/docs/en/customization/agents.md +++ b/docs/en/customization/agents.md @@ -1,6 +1,6 @@ # Agents and Sub-Agents -Every session in Kimi Code CLI is driven by a **main Agent**. The main Agent understands the user's intent, plans steps, calls tools, and when needed dispatches **sub-agents** to handle more focused sub-tasks — for example, exploring an unfamiliar codebase, reviewing multiple implementations in parallel, or planning a large refactor without touching the main context. +Every session in Kimi Code CLI is driven by a **main Agent**. The main Agent understands the user's intent, plans steps, calls tools, and when needed dispatches **sub-agents** to handle more focused sub-tasks, such as exploring an unfamiliar codebase, reviewing multiple implementations in parallel, or planning a large refactor without touching the main context. A sub-agent receives a task description from the main Agent, works in its own isolated context, and then returns its conclusions. It does not communicate with the user directly, and its intermediate reasoning and tool call records do not mix into the main Agent's history. @@ -8,15 +8,23 @@ A sub-agent receives a task description from the main Agent, works in its own is Kimi Code CLI includes three built-in sub-agents, ready to use out of the box, each aimed at a different task shape: -- **`coder`**: The default sub-agent — a general-purpose software engineering assistant that can read and write files, execute commands, search code, and land concrete changes. +- **`coder`**: The default sub-agent, a general-purpose software engineering assistant that can read and write files, execute commands, search code, and land concrete changes. - **`explore`**: Dedicated to codebase exploration; performs read-only operations only and does not modify any files. Ideal for quickly searching, reading, and summarizing a repository without touching files. - **`plan`**: Dedicated to implementation planning and architecture design; even shell commands are not available, keeping the focus on "figuring out how to do something" rather than "actually doing it." -A `coder` sub-agent shares most of the main Agent's tool set: it can run shell commands in the background, maintain todo lists, enter Plan mode, and invoke Agent Skills. Built-in sub-agents cannot dispatch further sub-agents. By default a custom agent inherits the built-in delegation allowlist (`coder`, `explore`, `plan`), whose members cannot dispatch further either, so delegation chains always terminate — unbounded recursive spawning is impossible without an explicit opt-in. A custom agent can opt into deeper chains by declaring an explicit [`subagents`](#agent-file-format) allowlist. If a sub-agent finishes its turn while background tasks are still running, its run only reports completion after those tasks settle, so the parent receives the result after the underlying work has actually finished. +Beyond the three types, three conventions govern how sub-agents work: tool boundaries, delegation depth, and completion timing. + +A `coder` sub-agent shares most of the main Agent's tool set: it can run shell commands in the background, maintain todo lists, enter Plan mode, and invoke Agent Skills. The three built-in sub-agents cannot dispatch further sub-agents. + +By default a custom agent inherits the built-in delegation allowlist (`coder`, `explore`, `plan`), whose members cannot dispatch further either, so delegation chains always terminate and unbounded recursive spawning is impossible without an explicit opt-in. A custom agent can opt into deeper chains by declaring an explicit [`subagents`](#agent-file-format) allowlist. + +If a sub-agent finishes its turn while background tasks are still running, its run only reports completion after those tasks settle, so the parent receives the result after the underlying work has actually finished. ## How to Invoke -Sub-agents are scheduled automatically by the main Agent — based on task complexity, context consumption, and sub-task independence, they are dispatched at the right moment without the user having to specify one. +The full pipeline has only three stages (dispatch, approval, and collection), and none of them require manual management. + +Sub-agents are scheduled automatically by the main Agent, based on task complexity, context consumption, and sub-task independence. They are dispatched at the right moment without the user having to specify one. Each dispatch is presented in the terminal as an approval request (unless it matches an allow rule or Ask When Needed mode is active), giving you a chance to review the task description. You can also instruct the main Agent directly in conversation to use a specific sub-agent, for example: "Use explore to map out the relevant files before making any changes." @@ -31,7 +39,7 @@ This isolation provides two benefits: - **The main Agent's context stays lean** and is not filled with large volumes of exploratory logs during long sessions. - **Multiple sub-agents can run in parallel** without interfering with each other. -Note that each sub-agent independently consumes model tokens. For simple tasks, there is no need to dispatch a sub-agent — the main Agent handles them more economically. +Note that each sub-agent independently consumes model tokens. For simple tasks, there is no need to dispatch a sub-agent; the main Agent handles them more economically. ## Permission Inheritance @@ -41,7 +49,7 @@ If you need a particular type of tool to be permanently unavailable inside sub-a ## Custom Agents -Beyond the three built-in sub-agents, you can define your own agents as Markdown files. Each file describes one agent: the frontmatter (YAML metadata at the top of the file) declares its name, description, and tool access, and the file body is its system prompt. Custom agents can be delegated to as sub-agents — the main Agent discovers them automatically alongside the built-in ones — or selected as the main Agent at startup. +Beyond the three built-in sub-agents, you can define your own agents as Markdown files. Each file describes one agent: the frontmatter (YAML metadata at the top of the file) declares its name, description, and tool access, and the file body is its system prompt. The main Agent discovers custom agents automatically alongside the built-in ones, so they can be delegated to as sub-agents. They can also be selected as the main Agent at startup. ### Agent Locations @@ -65,10 +73,12 @@ extra_agent_dirs = ["~/team-agents", ".agents/team-agents"] **Plugin level**: directories declared in an enabled plugin's manifest `agents` field (when omitted, the `agents/` directory under the plugin root is picked up automatically); see [Plugin Agents](./plugins.md#plugin-agents). Plugin agents outrank only the built-in agents. -**Built-in agents** are distributed with the CLI and have the lowest priority. A directory-discovered file does not override a same-name built-in Agent unless its frontmatter declares `override: true`. A file loaded through `--agent-file` is treated as explicit launch intent, may override a same-name built-in Agent, outranks every directory scope, and applies to the current launch only. Separately, `$KIMI_CODE_HOME/SYSTEM.md` permanently overrides the default main agent's system prompt (it is not part of agent-file discovery); its precedence interactions are covered in the SYSTEM.md section below. +**Built-in agents** are distributed with the CLI and have the lowest priority. A directory-discovered file does not override a same-name built-in Agent unless its frontmatter declares `override: true`. A file loaded through `--agent-file` is treated as explicit launch intent, may override a same-name built-in Agent, outranks every directory scope, and applies to the current launch only. + +Separately, `$KIMI_CODE_HOME/SYSTEM.md` permanently overrides the default main agent's system prompt; it is not part of agent-file discovery. Its precedence interactions are covered in the [SYSTEM.md section](#overriding-the-main-agents-system-prompt-with-systemmd). ::: warning Trust model -Agent files are prompt configuration, and project-level files come from the repository itself — including repositories you have just cloned and do not trust yet. A project-scoped file can take over a built-in agent entirely: naming it `agent.md` with `override: true` replaces the **default main agent's whole system prompt**, and `coder.md` with `override: true` replaces the default sub-agent type. Unlike `AGENTS.md` content — which is injected into the prompt as reference data — an override file *is* the system prompt, and a file without a `tools` list keeps every tool. Review `.kimi-code/agents/` and `.agents/agents/` in unfamiliar repositories with the same caution you would apply to scripts, before running Kimi Code inside them. +Agent files are prompt configuration, and project-level files come from the repository itself, including repositories you have just cloned and do not trust yet. A project-scoped file can take over a built-in agent entirely: naming it `agent.md` with `override: true` replaces the **default main agent's whole system prompt**, and `coder.md` with `override: true` replaces the default sub-agent type. Unlike `AGENTS.md` content, which is injected into the prompt as reference data, an override file *is* the system prompt, and a file without a `tools` list keeps every tool. Review `.kimi-code/agents/` and `.agents/agents/` in unfamiliar repositories with the same caution you would apply to scripts, before running Kimi Code inside them. ::: ### Agent File Format @@ -93,23 +103,29 @@ disallowedTools: You are a strict code reviewer. Read the diff, then report findings grouped by severity… ``` +Frontmatter fields: + | Field | Required | Description | | --- | --- | --- | -| `name` | no | Unique identifier in kebab-case. Defaults to the file name without its extension (`review.md` → `review`); a file whose resolved name is missing or not kebab-case is skipped with a warning | -| `description` | yes | What the agent does. Shown to the main Agent when it picks a sub-agent, so write it to guide delegation decisions | +| `name` | no | Unique kebab-case identifier; defaults to the file name without its extension. A file with a missing or non-kebab-case name is skipped with a warning | +| `description` | yes | What the agent does, shown to the main Agent when it picks a sub-agent. Write it to guide delegation decisions | | `whenToUse` | no | Extra hint describing when the agent should be used | -| `override` | no | Whether this file may replace a same-name built-in Agent. Defaults to `false`; `--agent-file` is already explicit and does not require this field | -| `tools` | no | Allowlist of tool names such as `Read` or `Bash`; MCP tools are matched with globs such as `mcp__github__*`. Accepts a YAML list or a comma-separated string (`tools: Read, Grep`). Omit to allow all tools; a lone `*` also allows all tools; an empty list (`tools: []`) disables all tools | +| `override` | no | Whether the file may replace a same-name built-in Agent; defaults to `false`. `--agent-file` does not need it | +| `tools` | no | Tool allowlist (`Read`, `Bash`); MCP tools match as globs (`mcp__github__*`). YAML list or comma-separated string; omit or use a lone `*` to allow all tools, `tools: []` disables all tools | | `disallowedTools` | no | Denylist with the same syntax and matching rules, applied after `tools` | -| `subagents` | no | Allowlist of sub-agent names this agent may delegate to, with the same syntax as `tools` (YAML list or comma-separated string). Omit to inherit the default agent's allowlist (built-in default: `coder`, `explore`, `plan`, whose members cannot delegate further, so inherited chains always terminate); a lone `*` allows every type. The main agent's effective allowlist additionally includes every discovered custom agent, so custom agents stay delegatable by default | +| `subagents` | no | Sub-agent allowlist, same syntax as `tools`. Omit to inherit the built-in default (`coder`, `explore`, `plan`); a lone `*` allows every type. The main agent's effective list also includes every discovered custom agent | + +Built-in and user tools match by exact, case-sensitive name; entries starting with `mcp__` match MCP tools as globs. Three entry shapes never match anything and are reported with a warning when the profile takes effect: -Built-in and user tools match by exact, case-sensitive name; entries starting with `mcp__` match MCP tools as globs. Three entry shapes never match anything and are reported with a warning when the profile takes effect: a wildcard outside an `mcp__` pattern (a bare `*` in `disallowedTools` disables nothing), an `mcp__` literal that is not a full `mcp____` name (`mcp__github` matches nothing — use `mcp__github__*` for the whole server), and a name no registered or built-in tool has (usually a typo, such as `read` instead of `Read`). +- A wildcard outside an `mcp__` pattern: a bare `*` in `disallowedTools` disables nothing. +- An incomplete `mcp__` literal: `mcp__github` matches nothing; use `mcp__github__*` for the whole server. +- A name no registered or built-in tool has, usually a typo such as `read` instead of `Read`. -The body is the agent's system prompt, and it is rendered as a template each time the prompt is built: `${var}` placeholders substitute live context values — unknown variables stay verbatim, a bare `$` is never special, and a variable with no context value renders as an empty string. `${base_prompt}` embeds the effective default system prompt (the built-in default, or your `SYSTEM.md` override when present), so a file can wrap the default behavior instead of replacing it. If the file replaces the default prompt but should still honor instructions contributed by enabled plugins, place `${plugin_sections}` where those instructions should appear. The available variables are listed in the SYSTEM.md section below. +The body is the agent's system prompt, and it is rendered as a template each time the prompt is built: `${var}` placeholders substitute live context values. Unknown variables stay verbatim, a bare `$` is never special, and a variable with no context value renders as an empty string. `${base_prompt}` embeds the effective default system prompt (the built-in default, or your `SYSTEM.md` override when present), so a file can wrap the default behavior instead of replacing it. If the file replaces the default prompt but should still honor instructions contributed by enabled plugins, place `${plugin_sections}` where those instructions should appear. The available variables are listed in the [SYSTEM.md section](#overriding-the-main-agents-system-prompt-with-systemmd). -Unknown fields are ignored, so newer files stay readable by older versions. Fields from other agent tools (such as Claude Code's `model` or OpenCode's `mode`) are ignored the same way, the comma-separated `tools` form keeps Claude Code-style agent files loadable, and a missing `name` falls back to the file name so OpenCode-style files load too — a minimal file with `description` and a body works across tools. +Unknown fields are ignored, so newer files stay readable by older versions. Fields from other agent tools (such as Claude Code's `model` or OpenCode's `mode`) are ignored the same way, the comma-separated `tools` form keeps Claude Code-style agent files loadable, and a missing `name` falls back to the file name so OpenCode-style files load too. A minimal file with `description` and a body works across tools. -A file with invalid content discovered in a directory is skipped with a warning and does not affect other files. A file passed explicitly via `--agent-file` must be valid — otherwise the CLI reports the error and exits. +A file with invalid content discovered in a directory is skipped with a warning and does not affect other files. A file passed explicitly via `--agent-file` must be valid, otherwise the CLI reports the error and exits. ::: warning Note `tools` and `disallowedTools` shape the tools shown to the model and are enforced again before execution. `subagents` works the same way: the `Agent` tool lists only the sub-agent types the caller may delegate to, and both `Agent` and `AgentSwarm` re-check the allowlist before dispatching; resuming an existing sub-agent is exempt. Permission rules remain a separate control for operations that require approval. @@ -124,7 +140,7 @@ Two CLI flags select which agent drives a new session, in both print mode (`kimi - **`--agent `**: Start the session with the named agent as the main Agent. The name can refer to a built-in agent or to any discovered file; an unknown name fails with an error listing the available agents. - **`--agent-file `**: Load one agent file at the highest priority for this launch and start with it. The flag accepts exactly one file: it cannot be repeated, and it cannot be combined with `--agent`. -Both flags only apply when starting a new session — neither can be combined with `--session`/`--continue`. The agent is bound at session creation, and resuming restores the bound agent automatically, so no flag is needed (or allowed) on resume. +Both flags only apply when starting a new session: neither can be combined with `--session`/`--continue`. The agent is bound at session creation, and resuming restores the bound agent automatically, so no flag is needed (or allowed) on resume. For example: @@ -139,11 +155,17 @@ For main-agent customization, reference `${base_prompt}` in the body so the envi ### Overriding the main agent's system prompt with SYSTEM.md -To override the main agent's system prompt permanently — without passing `--agent` or `--agent-file` on every launch — write a `$KIMI_CODE_HOME/SYSTEM.md` file (default: `~/.kimi-code/SYSTEM.md`; it moves with `KIMI_CODE_HOME`). While the file exists and is non-empty, it replaces the built-in default main agent's system prompt in full — and only the prompt: the description, tool set, and sub-agent delegation allowlist are inherited from the built-in defaults. SYSTEM.md takes effect in every launch mode, including interactive TUI sessions. +To override the main agent's system prompt permanently, without passing `--agent` or `--agent-file` on every launch, write a `$KIMI_CODE_HOME/SYSTEM.md` file (default: `~/.kimi-code/SYSTEM.md`; it moves with `KIMI_CODE_HOME`). While the file exists and is non-empty, it fully replaces the built-in default main agent's system prompt (and only the prompt: the description, tool set, and sub-agent delegation allowlist are inherited from the built-in defaults). SYSTEM.md takes effect in every launch mode, including interactive TUI sessions. + +SYSTEM.md is a plain Markdown body; no frontmatter is required or read. A missing or empty file has no effect, and a read failure falls back to the built-in prompt with a warning. + +Explicit intent still outranks it: -SYSTEM.md is a plain Markdown body — no frontmatter is required or read. A missing or empty file has no effect, and a read failure falls back to the built-in prompt with a warning. Explicit intent still outranks it: a project-scoped same-name agent file declaring `override: true` and any file passed via `--agent-file` take precedence, and selecting another agent with `--agent` bypasses it entirely. Within the user scope itself, SYSTEM.md wins over a same-name file discovered in the `agents/` directories. +- A project-scoped same-name agent file declaring `override: true`, and any file passed via `--agent-file`, rank ahead of SYSTEM.md. +- Selecting another agent with `--agent` bypasses SYSTEM.md entirely. +- Within the user scope itself, SYSTEM.md wins over a same-name file discovered in the `agents/` directories. -Like the body of a regular agent file, SYSTEM.md is rendered as a template each time the prompt is built — `${var}` placeholders in the body are substituted from the live context: +Like the body of a regular agent file, SYSTEM.md is rendered as a template each time the prompt is built, and `${var}` placeholders in the body are substituted from the live context: | Variable | Content | | --- | --- | @@ -153,11 +175,12 @@ Like the body of a regular agent file, SYSTEM.md is rendered as a template each | `${cwd_listing}` | Listing of the working directory | | `${os}` | Operating system kind | | `${shell}` | Shell name and path, for example `bash (\`/bin/bash\`)` | +| `${now}` | Current time (ISO format) | | `${additional_dirs_info}` | Additional directories added to the workspace; empty when there are none | -| `${base_prompt}` | The default system prompt. Inside `SYSTEM.md` itself this is the built-in default; inside an agent file it is the effective default — the built-in default, or your `SYSTEM.md` override when present | +| `${base_prompt}` | The default system prompt. Inside `SYSTEM.md` itself this is the built-in default; inside an agent file it is the effective default (the built-in default, or your `SYSTEM.md` override when present) | | `${plugin_sections}` | A complete Plugin Instructions block contributed by enabled plugins; empty when no enabled plugin contributes instructions | -Unknown variables stay verbatim, a bare `$` is never special, and a variable with no context value renders as an empty string. Four pre-composed blocks — `${windows_notes}`, `${additional_dirs_section}`, `${skills_section}`, and `${plugin_sections}` — render the matching built-in prompt section, or an empty string when it does not apply. The built-in default prompt already includes `${plugin_sections}`, so do not add it again when `${base_prompt}` already expands to that prompt. The variables are enough to rebuild the skeleton of the built-in prompt, for example: +Unknown variables stay verbatim, a bare `$` is never special, and a variable with no context value renders as an empty string. Four pre-composed blocks (`${windows_notes}`, `${additional_dirs_section}`, `${skills_section}`, and `${plugin_sections}`) render the matching built-in prompt section, or an empty string when it does not apply. The built-in default prompt already includes `${plugin_sections}`, so do not add it again when `${base_prompt}` already expands to that prompt. The variables are enough to rebuild the skeleton of the built-in prompt, for example: ```markdown You are Kimi, running at ${cwd} on ${os}. diff --git a/docs/en/customization/hooks.md b/docs/en/customization/hooks.md index 680b1b9817e..72ac0d77a7c 100644 --- a/docs/en/customization/hooks.md +++ b/docs/en/customization/hooks.md @@ -17,7 +17,7 @@ The script's response is determined by two things: - **Exit code**: `0` means allow, `2` means block, other non-zero values default to allow - **Standard output** (stdout): can include explanatory text -Even if the script errors or times out, the CLI **will not interrupt your work** as a result — this "allow on failure" design is called fail-open, preventing hook errors from becoming blockers. +Even if the script errors or times out, the CLI **will not interrupt your work** as a result. This "allow on failure" design is called fail-open, preventing hook errors from becoming blockers. ::: warning Note Precisely because of fail-open, Hooks are suitable for alerts and lightweight interception, but **should not be used as the sole security barrier**. For truly high-risk operations, rely on permission approvals and manual confirmation. @@ -43,7 +43,7 @@ All hook rules are written in the `[[hooks]]` array in `~/.kimi-code/config.toml | Field | Type | Required | Description | | --- | --- | --- | --- | -| `event` | `string` | Yes | Trigger event name; must be one of the entries in the "Event Reference" table below | +| `event` | `string` | Yes | Trigger event name; must be one of the events in the [event reference](#event-reference) | | `matcher` | `string` | No | A regular expression to filter event targets; if omitted, matches all | | `command` | `string` | Yes | The shell command to run when triggered | | `timeout` | `integer` | No | Timeout in seconds, range 1–600; defaults to 30 seconds | @@ -52,7 +52,14 @@ All hook rules are written in the `[[hooks]]` array in `~/.kimi-code/config.toml **When multiple rules match the same event**, all matching hooks run in parallel; multiple rules with identical `command` values run only once. -The working directory for hook commands is the current session's project directory. On non-Windows platforms, hook processes are placed in a separate process group; on timeout, a signal is sent first to give the process a chance to clean up, then it is forcibly terminated. +The working directory for hook commands is the current session's project directory. + +
+Process group and timeout handling + +On non-Windows platforms, hook processes run in a separate process group; on timeout, the CLI first sends a signal to give the script a chance to clean up, then forcibly terminates it. + +
### Event Data Format @@ -68,7 +75,7 @@ Each time a hook triggers, the CLI passes the following base information to the } ``` -Specific events will also include additional fields (such as tool name and command content); see the event reference below. All field names use snake_case. +Specific events will also include additional fields (such as tool name and command content); see the [event reference](#event-reference). All field names use snake_case. ## Return Values @@ -93,33 +100,33 @@ You can also return a JSON object via stdout to block: ``` ::: info Which events support blocking? -Only **blockable events** (`PreToolUse`, `Stop`, `UserPromptSubmit`) have return values that affect the main flow. All other events are **observation-only events** — they fire and forget; the main flow is unaffected regardless of what the script returns. +Only **blockable events** (`PreToolUse`, `Stop`, `UserPromptSubmit`) have return values that affect the main flow. All other events are **observation-only events**: they fire and forget, and the main flow is unaffected regardless of what the script returns. ::: ## Event Reference | Event | Matcher matches | Supports blocking? | Description | | --- | --- | --- | --- | -| `UserPromptSubmit` | The text submitted by the user | ✓ | Triggered when the user sends a message; returned text is appended to context; if blocked, the model is not called for this turn | -| `UserPromptQueued` | The queued prompt text | — | Triggered when a message is queued while a turn is still running; the payload includes `prompt_id`, `prompt`, and `queue_length` (observation only) | +| `UserPromptSubmit` | The text submitted by the user | ✓ | Triggered when the user sends a message; returned text is appended to context; blocking skips the model call this turn | +| `UserPromptQueued` | The queued prompt text | — | Triggered when a message is queued while a turn is still running; payload includes `prompt_id`, `prompt`, `queue_length` | | `PreToolUse` | Tool name | ✓ | Triggered before a tool call (before permission checks); the tool will not execute if blocked | -| `Stop` | Empty string | ✓ | Triggered when the model is about to end the current turn; if blocked, a message can be appended to let the model continue | -| `TurnStarted` | Turn origin kind (e.g. `user`, `task`, `system_trigger`) | — | Triggered when a new turn begins; the payload includes `turn_id`, `origin_kind`, `origin_name`, and `prompt` (observation only) | -| `PostToolUse` | Tool name | — | Triggered after a tool executes successfully (observation only) | -| `PostToolUseFailure` | Tool name | — | Triggered after a tool fails or is blocked (observation only) | -| `PermissionRequest` | Tool name | — | Triggered just before waiting for user approval (observation only) | -| `PermissionResult` | Tool name | — | Triggered after approval completes (observation only) | -| `SessionStart` | `startup` or `resume` | — | Triggered after a new session starts or a previous session resumes; the payload includes `source`, `model`, and `profile` | +| `Stop` | Empty string | ✓ | Triggered when the model is about to end the turn; if blocked, a message can be appended to let the model continue | +| `TurnStarted` | Turn origin kind (e.g. `user`, `task`, `system_trigger`) | — | Triggered when a new turn begins; payload includes `turn_id`, `origin_kind`, `origin_name`, `prompt` | +| `PostToolUse` | Tool name | — | Triggered after a tool executes successfully | +| `PostToolUseFailure` | Tool name | — | Triggered after a tool fails or is blocked | +| `PermissionRequest` | Tool name | — | Triggered just before waiting for user approval | +| `PermissionResult` | Tool name | — | Triggered after approval completes | +| `SessionStart` | `startup` or `resume` | — | Triggered after a session starts or resumes; payload includes `source`, `model`, `profile` | | `SessionEnd` | `exit` or `archive` | — | Triggered after a session closes; `archive` means the session was archived rather than exited | -| `SessionHeartbeat` | Empty string | — | Triggered every 60 seconds while the session is alive; the timer only runs when this event is configured. The payload includes `uptime_ms` (observation only) | +| `SessionHeartbeat` | Empty string | — | Triggered every 60 seconds while the session is alive; the timer runs only when this event is configured; payload includes `uptime_ms` | | `SubagentStart` | Sub-agent name | — | Triggered before a sub-agent starts running | -| `SubagentStop` | Sub-agent name | — | Triggered after a sub-agent completes successfully (observation only) | -| `TaskStarted` | Task kind (`agent`, `process`, or `question`) | — | Triggered when a background task starts; the payload includes `task_id`, `description`, and `detached` (observation only) | -| `StopFailure` | Error type | — | Triggered after the current turn fails due to an error (observation only) | -| `Interrupt` | Empty string | — | Triggered when the user interrupts the current turn (e.g. pressing Esc); not fired for timeouts or other programmatic aborts. `Stop` does not fire on interrupts, so this event fires instead. The payload includes a `reason` field (observation only) | +| `SubagentStop` | Sub-agent name | — | Triggered after a sub-agent completes successfully | +| `TaskStarted` | Task kind (`agent`, `process`, or `question`) | — | Triggered when a background task starts; payload includes `task_id`, `description`, `detached` | +| `StopFailure` | Error type | — | Triggered after the current turn fails due to an error | +| `Interrupt` | Empty string | — | Triggered when the user interrupts the turn (e.g. pressing Esc); not fired for timeouts or programmatic aborts; fires in place of `Stop`; payload includes `reason` | | `PreCompact` | `manual` or `auto` | — | Triggered before context compaction begins; return values are completely ignored | -| `PostCompact` | `manual` or `auto` | — | Triggered after context compaction completes (observation only) | -| `Notification` | Notification type (e.g. `task.completed`) | — | Triggered when a background task status changes (observation only) | +| `PostCompact` | `manual` or `auto` | — | Triggered after context compaction completes | +| `Notification` | Notification type (e.g. `task.completed`) | — | Triggered when a background task status changes | ## Example: Blocking Dangerous Shell Commands @@ -154,7 +161,7 @@ process.stdin.on('end', () => { After blocking, Kimi Code CLI writes the blocking reason back into the context, and the model can use this to choose a safer alternative. ::: warning Note -This example only demonstrates the blocking mechanism — it is not a production-grade security parser. Real scenarios are better served by whitelists, or a dedicated shell parser to handle quoting, variable expansion, and multi-command sequences. +This example only demonstrates the blocking mechanism and is not a production-grade security parser. Real scenarios are better served by whitelists, or a dedicated shell parser to handle quoting, variable expansion, and multi-command sequences. ::: ## Next steps diff --git a/docs/en/customization/mcp.md b/docs/en/customization/mcp.md index be65fd48b49..1ef81c5cdd8 100644 --- a/docs/en/customization/mcp.md +++ b/docs/en/customization/mcp.md @@ -1,6 +1,6 @@ # Model Context Protocol -[Model Context Protocol (MCP)](https://modelcontextprotocol.io/) is an open protocol that lets models safely call tools exposed by external processes or services — for example, reading GitHub issues, querying databases, or operating the local file system. Kimi Code CLI acts as an MCP client to connect these external tools and exposes them to the Agent alongside built-in tools (`Read`, `Bash`, `Grep`, etc.) with no behavioral difference. +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/) is an open protocol that lets models safely call tools exposed by external processes or services: reading GitHub issues, querying databases, or operating the local file system. Kimi Code CLI acts as an MCP client to connect these external tools and exposes them to the Agent alongside built-in tools (`Read`, `Bash`, `Grep`, etc.) with no behavioral difference. ## Connection Methods @@ -21,7 +21,7 @@ Entries with the same name: the project-level entry takes precedence and overrid Run `/mcp-config` in the TUI to interactively add, edit, or delete servers without manually editing the JSON file. Run `/mcp` to view the connection status of all current servers. -Deleting a server from the configuration does not interrupt open sessions: the server stays listed in `/mcp` as `removed`, its tools remain visible there, and calls to them fail with a removal notice, while new sessions do not register the tools at all. Conversely, a server added mid-session — by editing `mcp.json` or installing a plugin — is not registered in already-open sessions; it only joins sessions created later. +Deleting a server from the configuration does not interrupt open sessions: the server stays listed in `/mcp` as `removed`, its tools remain visible there, and calls to them fail with a removal notice, while new sessions do not register the tools at all. Conversely, a server added mid-session by editing `mcp.json` or installing a plugin is not registered in already-open sessions; it only joins sessions created later. When Kimi Code finds project-level MCP servers in an untrusted folder, it shows each server's transport and launch target in the workspace trust prompt. The prompt defaults to `Trust this folder`; review the listed command and arguments or remote URL before confirming. Trusting the folder enables the project-level MCP servers for that workspace. @@ -65,7 +65,7 @@ You do not have to set the connection timeout or the single tool-call timeout pe HTTP and SSE servers support providing static credentials via `headers` or `bearerTokenEnvVar`. When OAuth is needed, run `/mcp-config login ` to complete browser-based authorization. -Plugins can also declare MCP servers in their manifest. Servers declared by a plugin are enabled by default and can be disabled or re-enabled in `/plugins`: disabling or removing stops the tools in open sessions — calls fail with a removal notice — and adding or enabling a server connects it in open sessions right away. See [Plugins](./plugins.md#mcp-servers-in-plugins) for details. +Plugins can also declare MCP servers in their manifest. Servers declared by a plugin are enabled by default and can be disabled or re-enabled in `/plugins`: disabling or removing one makes calls from open sessions fail with a removal notice, and adding or enabling a server connects it in open sessions right away. See [Plugins](./plugins.md#mcp-servers-in-plugins) for details. ::: warning Note stdio entries in a project-level `.kimi-code/mcp.json` execute local commands when a session starts. Only enable these in repositories you trust. @@ -100,7 +100,7 @@ When connecting to external MCP servers, be aware of: - Keep manual approval for high-risk tools (file writes, command execution, etc.); avoid using `mcp__*` wildcards to allow all tools at once ::: warning Note -In Ask When Needed mode, MCP tool calls are automatically approved. Only use this mode when you fully trust the MCP servers you have connected. +In [Ask When Needed mode](../guides/interaction.md#the-three-permission-modes), MCP tool calls are automatically approved. Only use this mode when you fully trust the MCP servers you have connected. ::: ## Next steps diff --git a/docs/en/customization/plugins.md b/docs/en/customization/plugins.md index 760e0155aa5..c3e8018298e 100644 --- a/docs/en/customization/plugins.md +++ b/docs/en/customization/plugins.md @@ -1,6 +1,6 @@ # Plugins -Plugins package reusable Kimi Code CLI capabilities into installable units — they can add [Agent Skills](./skills.md), custom [agents](./agents.md), automatically load a specified Skill at session start, contribute system-prompt instructions, and declare MCP servers to provide real tool capabilities. They are ideal for sharing workflows with a team, connecting to external services, or installing extensions from the [official plugins](#official-plugins). +Plugins package reusable Kimi Code CLI capabilities into installable units: they can add [Agent Skills](./skills.md), custom [agents](./agents.md), automatically load a specified Skill at session start, contribute system-prompt instructions, and declare MCP servers to provide real tool capabilities. They are ideal for sharing workflows with a team, connecting to external services, or installing extensions from the [official plugins](#official-plugins). ## Installation and Management @@ -20,7 +20,7 @@ Common keys: | `D` | Remove the selected installed plugin (Installed tab) | | `M` | Manage MCP servers for the selected plugin (Installed tab) | | `R` | Reload `installed.json` and all manifests (Installed tab) | -| `Enter` | Installed tab: install the available update, or view details if up to date · Official/Curated tab: install or update · Custom tab: install | +| `Enter` | Installed: update if available, or view details · Official/Curated: install or update · Custom: install | | `I` | View plugin details (Installed tab) | | `Esc` | Go back or cancel | @@ -95,13 +95,13 @@ All official plugins share the same installation and upgrade flow: Kimi WebBridge installs in two parts: after the steps above, you also need to [install the browser extension](#install-the-browser-extension) before it works. ::: -Official plugins do not update automatically — when an update is available, you'll be prompted the next time you use the old version. To upgrade, repeat the installation steps above. +Official plugins do not update automatically. When an update is available, you'll be prompted the next time you use the old version. To upgrade, repeat the installation steps above. ### Kimi Datasource -Kimi Datasource is the official Kimi Code data plugin, letting you query financial market data, financial news, macroeconomic indicators, corporate registration records, academic literature, Chinese laws and regulations, and official data from intergovernmental organizations in natural language — no manual API calls or data accounts required. +Kimi Datasource is the official Kimi Code data plugin, letting you query financial market data, financial news, macroeconomic indicators, corporate registration records, academic literature, Chinese laws and regulations, and official data from intergovernmental organizations in natural language. No manual API calls or data accounts required. -Sources include authoritative institutions and leading databases such as the World Bank, IMF, OECD, FRED, WHO, FAO, the National Bureau of Statistics of China, Wind, S&P Capital IQ, SEC EDGAR, Caixin, Xinhua Finance, and Hundsun Juyuan — all traceable to their original publishers. +Sources include authoritative institutions and leading databases such as the World Bank, IMF, OECD, FRED, WHO, FAO, the National Bureau of Statistics of China, Wind, S&P Capital IQ, SEC EDGAR, Caixin, Xinhua Finance, and Hundsun Juyuan, all traceable to their original publishers. You must first complete OAuth login with a Kimi Code account via `/login`; data queries consume your Kimi Code plan quota. @@ -137,7 +137,7 @@ Pull the annual report, standardized financial metrics, top-50 holders, and cons ::: ::: details **Financial news and industry data** — Tracking market hotspots or policy moves? -Query Caixin's market news, bond/fund/futures data, and listed-company supply-chain relationships, plus news, policies, announcements, and market flashes from the Xinhua Finance national financial information platform — authoritative and traceable sources. +Query Caixin's market news, bond/fund/futures data, and listed-company supply-chain relationships, plus news, policies, announcements, and market flashes from the Xinhua Finance national financial information platform. All sources are authoritative and traceable. ::: ::: details **Standards lookup** — Need to check compliance against Chinese standards? @@ -148,14 +148,14 @@ Look up national (GB), industry, local, and association standards by number or t | Category | Scope | |---|---| -| Stocks & financial markets | Well-known databases such as Wind, S&P Capital IQ, and SEC EDGAR, covering prices, technical indicators, financials and valuation, and consensus estimates across A-shares, HK, US, and other major markets, plus official filings for 8,000+ US-listed companies | -| Financial news & industry data | Well-known data platforms such as Caixin and Xinhua Finance, covering market news and flashes, listed-company announcements, regulatory policies, bond/fund/futures data, corporate credit violation records, and listed-company supply-chain relationships | -| Macroeconomics | Well-known databases such as the World Bank, IMF, OECD, FRED, and China's National Bureau of Statistics, plus official statistics from IGOs such as WHO and FAO, covering 50+ years of time series for 189 countries and China indicators at national/provincial/municipal levels: GDP, trade, population, exchange rates, CPI, balance of payments, GDP forecasts, and more | -| China standards | National (GB), industry, local, and association standards — numbers, titles, status, and details, with official full-text entry points for some national and public association standards | -| Corporate data | Business registration, equity chain, legal risk, and related-entity graph for mainland Chinese companies | -| Academic literature | Millions of papers across physics, mathematics, CS, quantitative finance, economics — including preprints | -| Legal | Yuandian Legal and other leading legal databases, covering Chinese laws, regulations, and judicial cases — statute search and detail lookup across all authority levels, plus ordinary and authoritative case search | -| Smart screening | Well-known databases such as Gildata, covering natural-language screening for stocks, funds, and fund managers, plus macro-industry data, research reports, announcements, and news | +| Stocks & financial markets | Wind, S&P Capital IQ, SEC EDGAR; A-share/HK/US quotes, indicators, financials, valuation, estimates; 8,000+ US-listed filings | +| Financial news & industry data | Caixin, Xinhua Finance; market news and flashes, company announcements, regulatory policy, bond/fund/futures data, credit-violation records, supply-chain ties | +| Macroeconomics | World Bank, IMF, OECD, FRED, China's NBS, WHO, FAO; 50+ years, 189 countries; national/provincial/municipal China indicators (GDP, trade, population, exchange rates, CPI, balance of payments) | +| China standards | National (GB), industry, local, and association standards: IDs, titles, status, details; official full text for some GB and public association standards | +| Corporate data | Registration, equity chain, legal risk, and related-entity graph for mainland Chinese companies | +| Academic literature | Millions of papers in physics, mathematics, CS, quantitative finance, economics, including preprints | +| Legal | Yuandian Legal and other leading legal databases: Chinese laws, regulations, judicial cases; statute search across authority levels; ordinary and authoritative case search | +| Smart screening | Gildata and other well-known databases: natural-language screening of stocks, funds, and fund managers; macro-industry data, research reports, announcements, news | #### Billing and limitations @@ -166,7 +166,7 @@ Look up national (GB), industry, local, and association standards by number or t ### Kimi WebBridge -Kimi WebBridge lets AI drive your browser directly — not an emulator, not a crawler, but the browser you use every day, with your login sessions and cookies. AI can open pages, read content, click buttons, fill in forms, and take screenshots just like you do, taking repetitive web operations off your hands. See the [Kimi WebBridge site](https://www.kimi.com/features/webbridge) for a product overview. +Kimi WebBridge lets AI drive your browser directly: not an emulator, not a crawler, but the browser you use every day, with your login sessions and cookies. AI can open pages, read content, click buttons, fill in forms, and take screenshots just like you do, taking repetitive web operations off your hands. See the [Kimi WebBridge site](https://www.kimi.com/features/webbridge) for a product overview. #### Install the browser extension @@ -195,7 +195,7 @@ Use this when you can't reach the stores: #### What you can do -- **Web automation**: Just say what you need — AI clicks through pages, fills in forms, reads content, and takes screenshots for you +- **Web automation**: Just say what you need, and AI clicks through pages, fills in forms, reads content, and takes screenshots for you - **Social trending research**: Automatically browse trending topics on X (Twitter), Weibo, and Xiaohongshu, open the top-liked posts one by one to screenshot and extract key viewpoints, then organize everything into a research library with topic suggestions - **Job listing collection**: Filter positions on recruiting sites by keyword, city, and job type, and organize titles, links, companies, salaries, and application methods into a table - **Competitive analysis**: Batch-question multiple AI products and collect their answers to build side-by-side comparison reports @@ -207,9 +207,9 @@ Kimi Computer Use lets AI operate your desktop apps directly, clicking, dragging #### Authorization (macOS) -The first time you use Kimi Computer Use after installation, it shows an authorization window — just follow the prompts: +The first time you use Kimi Computer Use after installation, it shows an authorization window. Just follow the prompts: -1. Click **Authorize** next to **Accessibility** and **Screen Recording**, and enable both permissions in System Settings — the former lets it perform clicks, typing, and scrolling; the latter lets it read screen content and locate UI elements +1. Click **Authorize** next to **Accessibility** and **Screen Recording**, and enable both permissions in System Settings: the former lets it perform clicks, typing, and scrolling; the latter lets it read screen content and locate UI elements 2. Turn on the **Kimi Code** switch under "Connect local agents", then restart Kimi Code for it to take effect
@@ -275,21 +275,25 @@ Supported fields: | --- | --- | | `name` | Required; serves as the plugin id. Must match `[a-z0-9][a-z0-9_-]{0,63}` | | `version`, `description`, `keywords`, `author`, `homepage`, `license` | Display metadata | -| `interface` | Fields shown in `/plugins`: `displayName`, `shortDescription`, `longDescription`, `developerName`, `websiteURL` | -| `skills` | One or more `./` paths; must be within the plugin root directory. When omitted, the `SKILL.md` in the root directory is treated as a single Skill root | -| `agents` | One or more `./` paths; must be within the plugin root directory and point to directories containing [agent files](./agents.md#custom-agents). When omitted, the `agents/` directory under the plugin root (if present) is picked up automatically | +| `interface` | Shown in `/plugins`: `displayName`, `shortDescription`, `longDescription`, `developerName`, `websiteURL` | +| `skills` | One or more `./` paths within the plugin root; if omitted, root `SKILL.md` is the single Skill root | +| `agents` | One or more `./` paths within the plugin root, pointing to [agent files](./agents.md#custom-agents); if omitted, `agents/` is auto-discovered | | `sessionStart.skill` | Loads the specified plugin Skill into the main Agent when a new or resumed session starts | | `skillInstructions` | Additional instructions appended whenever a Skill from this plugin is loaded | | `systemPrompt` | Inline instructions contributed to the agent's system prompt while the plugin is enabled | -| `systemPromptPath` | A `./` path to a UTF-8 text file containing system-prompt instructions; combined after `systemPrompt` when both are present | +| `systemPromptPath` | A `./` path to a UTF-8 text file; content is appended after `systemPrompt` when both are present | | `mcpServers` | MCP server declarations; enabled by default, can be disabled from `/plugins` | -| `hooks` | Hook rules run on lifecycle events while the plugin is enabled; see [Hooks in Plugins](#hooks-in-plugins) | -| `commands` | One or more `./` paths pointing to a directory or `.md` file; registers the Markdown files within as slash commands. See [Plugin Slash Commands](#plugin-slash-commands) | +| `hooks` | Hook rules run on lifecycle events while enabled; see [Hooks in Plugins](#hooks-in-plugins) | +| `commands` | One or more `./` paths to a directory or `.md` file; registers the Markdown files inside as slash commands. See [Plugin Slash Commands](#plugin-slash-commands) | Unsupported runtime fields such as `tools`, `apps`, `inject`, and `configFile` appear as diagnostics and are ignored. ### System-prompt instructions +Plugins inject instructions into the agent's system prompt through the `systemPrompt` and `systemPromptPath` fields. This section covers three parts: writing format and read timing, size limits, and the differences between the two engines. + +### Writing format and read timing + Use `systemPrompt` for a short inline instruction, or `systemPromptPath` to keep longer instructions in a file inside the plugin root. If both fields are present, the inline text appears first, followed by the file content. The file content is read when the plugin is installed or reloaded, so edits take effect only after `/plugins reload`. For example: ```json @@ -299,13 +303,24 @@ Use `systemPrompt` for a short inline instruction, or `systemPromptPath` to keep } ``` +The built-in agent prompt includes instructions from enabled plugins automatically. A custom `SYSTEM.md` or agent file owns its template, so include `${plugin_sections}` where plugin-contributed instructions should appear. If the custom template includes `${base_prompt}` and that effective default already contains the plugin block, do not add `${plugin_sections}` again. See [Custom agents and SYSTEM.md](./agents.md#overriding-the-main-agents-system-prompt-with-systemmd) for the complete variable table. + +### Size limits + +Each field (the inline `systemPrompt` and the `systemPromptPath` file) is limited to 32 KB (UTF-8 bytes): oversized content is ignored and reported in the plugin diagnostics. Across all enabled plugins, one prompt build injects at most 64 KB of instructions; contributions beyond the budget are skipped with a warning, including a single plugin whose inline text and file together exceed that budget. + +### Differences between the two engines + System-prompt contributions take effect on both agent engines. The interactive TUI, `kimi -p`, and `kimi web` use the v2 engine by default; setting `KIMI_CODE_LEGACY_FLAG=1` routes the local CLI surfaces to the legacy engine. -Each field — the inline `systemPrompt` and the `systemPromptPath` file — is limited to 32 KB (UTF-8 bytes): oversized content is ignored and reported in the plugin diagnostics. Across all enabled plugins, one prompt build injects at most 64 KB of instructions; contributions beyond the budget are skipped with a warning, including a single plugin whose inline text and file together exceed that budget. +
+Instruction refresh behavior under the two engines + +New sessions and newly created agents read the contributions from the plugins currently enabled. An in-flight request keeps its existing system prompt. `/plugins reload` refreshes the plugin skill list and requests prompt rebuilds for live agents; use it when you need the change to converge deliberately before the next turn. -New sessions and newly created agents read the contributions from the plugins currently enabled. An in-flight request keeps its existing system prompt. `/plugins reload` refreshes the plugin skill list and requests prompt rebuilds for live agents; use it when you need the change to converge deliberately before the next turn. On the v2 engine, installing, enabling, disabling, or removing a plugin updates the catalog immediately and a later prompt rebuild — for example after compaction or a tool-policy change — may pick up the new sections. The legacy engine keeps each live session's plugin snapshot until `/plugins reload` or a new session. A resumed session starts from its persisted prompt, and later rebuilds follow the engine-specific behavior above. Toggling a plugin's MCP server does not change system-prompt sections. +On the v2 engine, installing, enabling, disabling, or removing a plugin updates the catalog immediately, and a later prompt rebuild (for example after compaction or a tool-policy change) may pick up the new sections. The legacy engine keeps each live session's plugin snapshot until `/plugins reload` or a new session. A resumed session starts from its persisted prompt, and later rebuilds follow the engine-specific behavior above. Toggling a plugin's MCP server does not change system-prompt sections. -The built-in agent prompt includes instructions from enabled plugins automatically. A custom `SYSTEM.md` or agent file owns its template, so include `${plugin_sections}` where plugin-contributed instructions should appear. If the custom template includes `${base_prompt}` and that effective default already contains the plugin block, do not add `${plugin_sections}` again. See [Custom agents and SYSTEM.md](./agents.md#overriding-the-main-agent-s-system-prompt-with-system-md) for the complete variable table. +
## Plugin Slash Commands @@ -365,9 +380,9 @@ A command file has two parts: an optional **frontmatter** (the metadata between ### Running Commands and Passing Arguments -Commands are prefixed with the plugin id (their namespace) and registered as `:`, so the command above is actually `/kimi-finance:report` — this keeps same-named commands from different plugins from colliding. +Commands are prefixed with the plugin id (their namespace) and registered as `:`, so the command above is actually `/kimi-finance:report`. This keeps same-named commands from different plugins from colliding. -Whatever you type after the command replaces `$ARGUMENTS` in the body (above, `TSLA` replaces `$ARGUMENTS`). If the body has no `$ARGUMENTS` but you pass arguments anyway, they are not dropped — they are appended to the end of the body as `ARGUMENTS: `. +Whatever you type after the command replaces `$ARGUMENTS` in the body (above, `TSLA` replaces `$ARGUMENTS`). If the body has no `$ARGUMENTS` but you pass arguments anyway, they are not dropped; they are appended to the end of the body as `ARGUMENTS: `. ## Skills and Session Start @@ -458,13 +473,13 @@ A plugin can declare hook rules in its manifest that run on lifecycle events whi } ``` -Plugin hooks reuse the same mechanism as global hooks — see [Hooks](./hooks.md) for the event list, the stdin JSON payload, and how exit codes and return values affect the main flow. The differences are: +Plugin hooks reuse the same mechanism as global hooks. See [Hooks](./hooks.md) for the event list, the stdin JSON payload, and how exit codes and return values affect the main flow. The differences are: - A plugin's hooks are active only while the plugin is **enabled**; disabling the plugin stops its hooks. - Each hook runs with its working directory set to the plugin root, so `command` can use `./` paths inside the plugin. - The hook process receives two extra environment variables: `KIMI_CODE_HOME` and `KIMI_PLUGIN_ROOT` (the plugin root directory). -Installing a plugin never runs its hooks by itself — they only fire when their matching event occurs while the plugin is enabled. +Installing a plugin never runs its hooks by itself. They only fire when their matching event occurs while the plugin is enabled. ## Security Model @@ -474,3 +489,10 @@ Plugins have a limited loading scope. The following operations do not occur duri - All paths must remain within the plugin root directory after symbolic link resolution - MCP servers of enabled plugins start after `/reload` or in new sessions and can be disabled at any time from `/plugins` - Broken manifests or unsafe paths appear in `/plugins info ` diagnostics and do not affect other sessions + +## Next steps + +- [Agent Skills](./skills.md) — Learn the `SKILL.md` format and write Skills that ship with your plugins +- [Custom agents](./agents.md) — Agent file format and directory-scope precedence +- [MCP](./mcp.md) — The schema that MCP server declarations in plugins reuse +- [Hooks](./hooks.md) — The global hook mechanism that plugin hooks reuse diff --git a/docs/en/customization/skills.md b/docs/en/customization/skills.md index b905e98180b..2cf84553f3b 100644 --- a/docs/en/customization/skills.md +++ b/docs/en/customization/skills.md @@ -1,6 +1,6 @@ # Agent Skills -Agent Skills are a lightweight mechanism for extending model capabilities in Kimi Code CLI. A Skill is a Markdown document with YAML frontmatter that describes a specialized area of knowledge or a workflow — for example, a project's code style guidelines, a PR review process, or a commit message format. +Agent Skills are a lightweight mechanism for extending model capabilities in Kimi Code CLI. A Skill is a Markdown document with YAML frontmatter that describes a specialized area of knowledge or a workflow: a project's code style guidelines, a PR review process, or a commit message format. Compared to pasting the same instructions into a prompt every time, Skills offer the advantage of keeping content in a file, enabling reuse across projects and teams, allowing instant loading via a slash command, and letting the model invoke them automatically when needed. @@ -39,12 +39,12 @@ Please handle code according to the following guidelines: | Field | Description | | --- | --- | -| `name` | Skill name. Required in a directory-form `SKILL.md`; when omitted in a flat `.md` file, the filename is used. Names are case-insensitive | -| `description` | A one-line summary; the model uses this to decide when to use the Skill. Required in a directory-form `SKILL.md`; when omitted in a flat `.md` file, falls back to the first non-empty line of the body (up to 240 characters) | -| `type` | Skill type: `prompt` (default), `inline` (same semantics as `prompt`), `flow` (manual invocation only; not available for automatic model invocation). Other values are skipped | +| `name` | Skill name (case-insensitive). Required in directory-form `SKILL.md`; flat `.md` uses the filename | +| `description` | One-line summary the model uses to decide when to invoke. Required in directory-form `SKILL.md`; flat `.md` falls back to the first non-empty body line (up to 240 characters) | +| `type` | Skill type: `prompt` (default), `inline` (same as `prompt`), `flow` (manual invocation only). Other values are skipped | | `whenToUse` | Description of when the Skill should be triggered. Also accepts `when-to-use` and `when_to_use` | -| `disableModelInvocation` | When set to `true`, prevents the model from invoking this Skill automatically. Also accepts `disable-model-invocation` and `disable_model_invocation` | -| `arguments` | List of named parameters; can be written as a string array or a whitespace-separated string (e.g., `arguments: target mode`). Once declared, parameters can be read in the body with `$` | +| `disableModelInvocation` | If `true`, blocks automatic model invocation. Also accepts `disable-model-invocation`, `disable_model_invocation` | +| `arguments` | Named parameters; a string array or whitespace-separated string (e.g., `arguments: target mode`). Once declared, readable in the body as `$` | ::: warning Note In a directory-form `SKILL.md`, both `name` and `description` **must** be explicitly provided. Omitting either one will cause parsing to fail. @@ -81,7 +81,7 @@ The Kimi-specific user Skill directory moves with `KIMI_CODE_HOME`, so isolated extra_skill_dirs = ["~/team-skills", ".agents/team-skills"] ``` -**Built-in Skills** are distributed with the CLI and have the lowest priority. They provide out-of-the-box workflows for common tasks — for example, configuring MCP servers, customizing the TUI theme, and editing config files. See [Built-in skill commands](../reference/slash-commands.md#built-in-skill-commands) for the full list. Those describing Kimi Code itself can be turned off with the top-level [`builtin_product_skills`](../configuration/config-files.md#top-level-fields) field. +**Built-in Skills** are distributed with the CLI and have the lowest priority. They provide out-of-the-box workflows for common tasks: configuring MCP servers, customizing the TUI theme, and editing config files. See [Built-in skill commands](../reference/slash-commands.md#built-in-skill-commands) for the full list. Those describing Kimi Code itself can be turned off with the top-level [`builtin_product_skills`](../configuration/config-files.md#top-level-fields) field. ## Invoking a Skill diff --git a/docs/en/customization/themes.md b/docs/en/customization/themes.md index ffa5399d359..c91203ba678 100644 --- a/docs/en/customization/themes.md +++ b/docs/en/customization/themes.md @@ -8,12 +8,12 @@ Custom themes can override the tokens below. The `dark` and `light` columns show | Token | `dark` | `light` | What it controls | | --- | --- | --- | --- | -| `primary` | `#4FA8FF` | `#1565C0` | The most-used color. Links, inline code, the selected item in nearly every dialog, the focused editor border, Plan/"running" badges, spinners | -| `accent` | `#5BC0BE` | `#00838F` | Secondary highlight. Approval `▶` prefix, device-code box, image placeholder, BTW / queue panes, registry import | -| `text` | `#E0E0E0` | `#1A1A1A` | Body text. Dialog bodies, todo titles, footer model label, Markdown headings, assistant/tool message bullets, list bullets | +| `primary` | `#4FA8FF` | `#1565C0` | The most-used color. Links, inline code, selected items in dialogs, focus borders, badges, spinners | +| `accent` | `#5BC0BE` | `#00838F` | Secondary highlight. Approval `▶` prefix, device-code box, image placeholder, panes, registry import | +| `text` | `#E0E0E0` | `#1A1A1A` | Body text. Dialog bodies, todo titles, footer model label, Markdown headings, list bullets | | `textStrong` | `#F5F5F5` | `#1A1A1A` | Emphasized / bold text. Input dialogs, status messages | -| `textDim` | `#888888` | `#454545` | Secondary, dimmed text. Thinking, hints, descriptions, completed todos, Markdown quotes, footer status bar | -| `textMuted` | `#6B6B6B` | `#5F5F5F` | Faintest text. Counters, scroll info, descriptions, Markdown link URLs, code-block borders | +| `textDim` | `#888888` | `#454545` | Secondary, dimmed text. Thinking, hints, completed todos, Markdown quotes, footer status bar | +| `textMuted` | `#6B6B6B` | `#5F5F5F` | Faintest text. Counters, scroll info, Markdown link URLs, code-block borders | | `border` | `#5A5A5A` | `#737373` | Pane and editor borders, Markdown horizontal rule | | `borderFocus` | `#E8A838` | `#92660A` | Focus / attention border, currently only the approval panel | | `success` | `#4EC87E` | `#0E7A38` | Success state. `✓`, "enabled", completed | @@ -65,7 +65,7 @@ Fields: - `name` (required): the theme identifier. - `displayName` (optional): a human-readable name. -- `base` (optional): the built-in palette that unspecified tokens inherit — `"dark"` (default) or `"light"`. Set `"base": "light"` when you are building a **light** theme so the tokens you leave out stay readable on a light background (otherwise they fall back to the dark palette). +- `base` (optional): the built-in palette that unspecified tokens inherit, `"dark"` (default) or `"light"`. Set `"base": "light"` when you are building a **light** theme so the tokens you leave out stay readable on a light background (otherwise they fall back to the dark palette). - `colors` (optional): the color tokens to override, each a 6-digit hex value (e.g. `#FE8019`). Use the token names from [Built-in color tokens](#built-in-color-tokens). Any token you omit falls back to the selected base palette, so partial themes are fine: @@ -85,7 +85,7 @@ Use the token names from [Built-in color tokens](#built-in-color-tokens). Any to Two ways: 1. **The `/theme` command** (recommended): opens the theme picker, where custom themes appear as `Custom: `. The picker **re-scans the themes directory every time it opens**, so a theme file you just added shows up **without a restart**. -2. **`tui.toml`**: set `theme` to your theme name: +2. **[`tui.toml`](../configuration/config-files.md#tuitoml)**: set `theme` to your theme name: ```toml # ~/.kimi-code/tui.toml @@ -104,9 +104,13 @@ Custom themes are designed to never get in your way: If you edit the theme file that is **currently active**, the change is not reloaded automatically. To apply the new colors: -- run `/reload-tui` — it reloads `tui.toml` and re-applies the current theme (including re-reading the theme file); or +- run `/reload-tui`, which reloads `tui.toml` and re-applies the current theme (including re-reading the theme file); or - switch to another theme in `/theme` and back. ::: warning Note Re-selecting the **same** theme in `/theme` does not reload it (you get a "Theme unchanged" message). To reload changes to the active theme, use one of the two methods above. ::: + +## Next steps + +- [Configuration files](../configuration/config-files.md#tuitoml) — Full field reference for `tui.toml`, including the `theme` option diff --git a/docs/media/provider-manager.jpg b/docs/media/provider-manager.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bb5edf808377a3a619addf57114df0ca0a94c6b4 GIT binary patch literal 211881 zcmeFacU)85wk{lsAcFMXf`Eclr6VO+Xz~i8^s0i=M5ISRLhl^`MFFJqWt}nnwt6)%^4b+Q>SPcPSeqzVPs%pWMnvdmWhRv zjft6qLo(23u59I zB@`5ulvPx(T)&~MqpPQX^R9`hnYo3fm4oBMM^4TzuHHVre*VyB0pSsmQPDB6acSu< zGBUGXzRJ!oC@gwkT=L=L=c?+O+PeCN#*WUe?w;Ph{x73rWiaCP^Sv2~iC;{EGy7 zF#sXT>k<^fy&gw`u-#WqBv6lApLjv0M%d;)aFYM@+r?Ls?=@+_h`h;5btg=a!#}D> zpd|%Zr!m2g1bVkh0$t365gs*%#i=@cmmy!|zqpTNOOkz(+;PZ55P6*Z*Yh2DoFtEv z}KTlCwo}w)lS}Tdc^BlZaq9)&`L`vJJ>SK=uK$50HJ}{|+CpHILNf zgD&;5^vgyP)VyH~PHsjG4`KxC=T}Vf9cR|q zd!m{yK_1=%IbtJ$cHg;?K)tRF_732(+eF`kf`K*oZ9t*ui|-|YuEB^V(lGoM7&C<6 zCV|$B0EJ>CoCFdm$iOj?cPCqh>;&ZQK^_UnV49Qq388#*Z>SXSK%&L$HBr>%|W)aE!Dw#?qlk8+Y0a3D4u;6-CpFpXn-Sc(Zzs{}R7PRCK=M0(-+(I2dOnRmGV*sVYRDlSEDCw#UNej4t0QnZyj zvvmGrlL%X(HTcEq`xT5ETS4Ul{4wf4*#zgiFXzuwg8QPvnpKgzZU(nm`M z9r6;3Ik%f+3T=owRpKA601LhiyZc)|lA0cRJ7}n{%&33js*P2S<-r<$DnMKa#t6_vGk=C-%8#eI7PE)m_RS z$`4sdcDVV!WTUra6a8myL^jcX+SAA;BAbXj7LkW*@{C5F^vQ7%IdmjP*MG@C$Z-)l zE+WT8iIW8gtvt;a=4DXW}5Hd+b=F!MhBbkl;GhU}cm0)$FGTb6Cgu72 z^yoi0|N80tGj&QD@6L+#ILsHEQ8*3>X-C9Mm4;kMWl>8m&R*y@TDMa+l}<%Q-<1Er zQ9}aV0JI$X;wO?4+QLV*dK~4a3D6>n1~Vk%cdI$I@oe@kQoV7@dvQJ z)nuxvM(S5xe1?Yka#$Rob-ETO{+9A@+duZi$yD>t!J`|G5j@h`RZVc5cC7)dt&#*v z+9LeS9Q^Tt01bc)V;jZu3)jzx=ZBn;bko7W;?=dC4+3bTYM$RYy)f|Xahd2V(+b8> z6K2NKDhFkkt0^TJ#{C4I?r9OE2RwX}whMumeoX?! z7D4EVqT$JStsnyuC~OLW&z9=m`alB79S<4CZP0cAyND4T!K@_EVyy@9LOPKnx-0pJ z`R{vo&fFzFJa|*YF#+p<!`q|0(Hquu`rCaG6}?{{W8!M zHrV>>MSdglpRN<~j~ACes8Iv?VgKxlv8_oS15vn>uU|G)T_+}_>hjq8HmVOp(Z0%%nS63HKw`3ePV^4UVg*=Ku%8X%C2~& zjOQ)w7Rw=HZFY8cb7NF;w4DMrH!H9N?{xL`?b^@iXDlOrZ=68#l)VC3V#Q@%dlnfg zwW9&QFIXIqo80`LUmtBMAXyiJG-8sN2O9Dh3; ze4p44+10PfJEpHA#>TY}o2hX6Ku~n66gbKjvG<4R&i*&1NH7?Pl%RPf#@bf{pSmjy zye_)kBc82Q+)APHQKf$ko=fBi9-dz9Vv3yz=4!b;(c?@<9^JtCGGkU{xd!JN!L?2nc_6EI4<9idVSS+DlkN$LF znJ8I8go&&oV(n=O2AIxG|H%W+#;Dgm$M;)n#GVjXIYRkaDMU(y1fhz1vK^2(!Snbm z3?SW2!zVtzZZUHzezTGr4_z7ZG7MfTS3~2&Wz6dnCg;|rbs3AeVMuCa7eY+YTqLQ*SI-<8efK*^40SQx+hZ{ zXWa)D*3YJlxy}qpv~i-MDIw4U=8sW7hq3R?5|kVBP?%Fi`5RcTSzS1H4yIUJ%XnH` ze!*Rl+Tkvb>CIdEF79fxOV#ixhpy@OdBqE|vDGDSo2$7bZmK?%`uOGL&Ow7l<$Ohu z{jnyrpgoWN2R5qc!*{)jq5L0T_^WhEQ4|ZqZ$2+Ogak|?JUp@HiygH0iglX5tcDX~ zx$x#!#<~!vG$jXuX112FHN7vvDaI36!q+8rn3!NPV^=#U%NS@17#MW{$v}DvUoynWct>2Y*Wcc@-4w zXrk+lU@u%Z$e8-Rj|Ad3N`d_yW++l;yctroo{59G*vcsEzB&DlFYIIaY~>x@ayKMV zkZ=kso78+s-9V|xA>Vnk+o7Sk-$hGB>Z8g`YC@Xoy7fY}e|V6&a*wTjmmg7Jym<6% zwH)7?`xIJRFT^S=ER?xi^6=!EUmZ+e?%vM-JtICi&gWW1UQFO#TvVl`D0Omr#> z9^y0$i0=I)>2|Cq^G>NMogW)*6S266wSyNBlrRTTL}4frjYyW3-m2!KKTh7)oFt7jpm5fQid)&2(Nwab{+gx_ZV zW!{y9K)=vTJ~<<==PHFK?;aCi#rW_WHQ0sN(*5FN`IgG+I_A=Q6=zdG{c7fUuIT7a z4}NRt=)sNXPTr#Zp)8+Do7a-&ukMOTOc{?v4>Eav4UFCbB370Sy9*;8dx^An5H&TG zDM*d7sxPVccm3tUX!(ELoZq-&Q^26DkiAk>JMFSC_~SqAjm_4_8bEJcU?{@+6@9eO zo7feeow}ZRSyDx7=7=rRCgCZQ)xq4hrUZdoYml96y z0vg&u$WnZu9cF9L?}!**;^KX?X;f{-KQhNVA*9XmQNFGow%QJtW3AlGOIaISRyGa5uV`Vq{ zmteFO17O?>q}K<&OW=*N3=y$mP8}XxK3~?${*PDGT;Xdj&cT{^OKd@h)lf3}MC3ZA zdKgq&WovsQiHc@M)Uf^17hMUJWnb#JT`-71iIq(xT$vZnGa1{n1qX`yo8PE>Nmczh zv}ZO(gCFJ!!H9nW{rM4R!aJ zyQ!8=;YG$E-AQgOjZq#9!C&(jeRg<0B;lmJjc6|R@Sf*7)sYgw5y1iZ!xWaNNrMGu zi(m-e$P%+sG&sSzL0LBVn9{PZs!FX+{i(@n>*eV@39I;xjEByu=UZDg?*)$qaDG60 zB-pVH`&gSbAeyS2(J}mvhY@M|Yar_M?^G7%;LllcOJk15%5e&6Id>F(@wOY3>!?ul z?F>KEI)FQ2r6wwf--GG7&Qs|Z+KQe>Ab$BAwB5&l)8F1!fG17o%*SGMO`0bxlzc~m z9)$gnd+QWP+3erukGZta7#L_Y;12%x#x(Q_eq}1qp}Cv==t*rmw%mJ1vwQxn~X2tk%c%9 z93waVYFnQ>%DW7Isk)Rk$fGr|Tg8bq{Ly4T?QQ(61|sM@_A{5Sb;NJ|Sj6CiaQfik z_cUIm`#oABs)W;}!~uZ@N#XfwqtjzhyqhroaK-a9YI<>~^UKU%SWAcT|Z`j7d?J)CV zn9)dSw17Ab&z&br%K=GlsD)?34~ zy+j^KH0=p(vmyxuD<*-KOsgMCJ`N&Eo{i41ylMLQ*y0F5WQ8-Zg`zb?NFXX;09=?3 zV1{kLeB9G|8~oY4i}C0n3bC_C0ufx3@s98q$esXZ@`MO1^`B_cn=LVM#nZF%fz!~> znd=*1ygos}K}P+0kvr|F)=5E%y^T$`6~uI>$(SO98Tzn#PG=Nzz8UqkdEmnAX9pEA z4ujvOpn)uFpn%ML(uD-Ve*e2?S_)zTqvaE|d$Z#Ke@t`a5nXbpG71 zG{gybl-Z2!M)qSiQ8}6<>lbGB^N8Dq+5t>JBe=z=x&m~GG`d8^-DrZGc^A_W6V#1J z0vY|T;RIGlxrq-4vgd`fu!Z&C->7);d}YQTnw;L=xTeF09Sx}p;-6YVWzv?T$OSOj~X1y6Qz~WTnP%vRQ6Cc!wD+^&cmE?_n?~2dq(-2QPH&c5O5ELX+ag zbS++Fy0VvL$cshG=6FdF@TyMjAP2x#I!U05faAC}x5laFdD#i3>#KZ{6)C}rbs6#C z>+CBh_P6{j_vx8Wl?@sfHFZYKo;h@FUVXD)o@qbLgkGM$IyTc?{?YvYE9rNZo<#f~ z;oGVQaJe!VJ>JP2n;c)-toXJq{ikyI9qxIp(3m^DQc!*>U3tFFQ5P|e;uI2y5#Q9+ z$~u`;gPMDQ?l}xKe|6g95?dPgrE^iwmIdAXyJ1|d=kSyISIlFAbfs{jQEtxpN$g&# ze6`|pNELM_jxVm$wm)Lg^jloU3A)c5JkOV|m2ykPbX!oWsE7A`^s!AG4bPH~YnXv` z%;KX@%JP50Fe!O8&M7Ued16!dPP(3iayvZYlK>4+LO*&3>0t|r{1eqYzWLL^HPC~j z2#8b6vtMeG^4l{R{n{u!exGu)CL?Bo{G_@(X0p>x?wic!9a$DGC9`ugTYOwZt4osA z7f)6VN)hP9wj_@ojbN@N*_m6S@;BO-GLzI%z~&HK5`KaaV6`Cg>Js4T}1^SmLSj2BX$_iZ6iPlB!!Cq{fBcs--( zYCXFJqx8*+V6?JU!sV*78K8%u>ZTre%T^U)=eKIuRwqu{?y!b$t@SI@PB~A;!0IFO z7k49tJjcqsOpN`^D~k!Awl%I3c_o*?Cyd}jBY<*VGVQ}R_1Z~b=LLnK3JVUedG`tGWR_>xL|@$uJvTY>BCJ#+Mls9RT`^~G!v74Xv!nCe z)gd0k)5viXlf?5J=O0z80h|)S6`zhi;k+ech2^VB_{eD?jY?t>CxM*v!*pvsw=CzG z@p(&ml-B+3sKfwk0~hZM`BUlH&49WBXCbUE}2yvn_{otW#36<Wm@trGpylB}OUir(9w zj-yP#4#_>$kbJJG5@eFx`5|96e!I0VMufVXC*7I5J*E8D;UrI)3)egtd*R(X*VIz; zS}scL%pG7$ConG8!5-u6>V@y-Xw$r{;um3BHm1dStto2#h0uS`K+fH*_8Xk1_!%3~RGoeH)R>XvQc~P87 zbRV)PnG+{3wa)zT&L)@l8;aaz9LE}%OOwq$NEAzxQ?vl&m!Isd=!*jXNPLrWm9|!w z7EvR)r|>l1^_FY0`oB?JQaOQ1rMg}lL*oe;WKNRQWH`R@p>(f^h+HQSlo$g6 zbd1lV$(dW&!kcN%7$do&mMMp&tvb3P>UN3hT*IuWav(N?Vv)k{-i=mL6Wnzn^U=B?wyA3%D`+3FpuZo#jAu^6=THiD|~DC;j{)O3kz%kEB|; zpWCB_MaBXNP7q%)l&TZK+RE>0mDn3q^E#?3ZRXAlE?&Q9sUm~Bhb2n&xZzaj(un#q z3=;PQZ@SdyW6$wZP^LK(r;w&*t)ycujvV-LbCxZWLCfY1QzKMNcIoS6R}(n8kue!7 zkLJuMan0fy@FDVl{v2ub&D4g@&KZ!LaQDzTg!xT~ZTVb1DUx~W4Ml5CBVF#Bd?Fq z{Dk(I+uGkm+_+xqu;g=>gr67o0|>RE*%A#32&=w{5ES=Yp%%_^|k!r zW6{T3N*%owQtXZxWk;+9f&t=W!~*5QC5#bnmAPHH=B!jFR}-<}qdu^^)}d&!(R4Nq zGNppFGN<~n69?Y4Q3q1Q`!hQy;sGm?pYVCeUM3zEAnTi1`28D+VFBgNh0`|pU+Ca? zl%#Fj!fdJ6l_ZClpiv0n6cxCmX<-`Njhh$6|D4uLtx>RN6n4g4);(aq@pKv1_PJr3 z#SOM-CDyqUp{azQ^oy%A!w7)2=QZ~SU(U7()?d)fi3n?EyeN3<>iLYRxk84)UeUB? zqN6`)zb^<@?}VB`_%-LSKzHo&56CU>IBjiv-uS`ih_hk(`f9PFmk+(3YVKSMg7ttY z5LF0Q0eMt(w6A&EfJKs8lUh?~3pzABOS+CCE~c>O@*BnsCtQQ-Nzs#rA%)*}Y4SaO zvipiXkm0%`q8hiWyfSfgr~&AOoFUG0;tdJ%f^A&Xxt$l%s4}YX9>=QqX!NPxjxu^n ztdF2*;*Yv;%lgZTrIV)_?}8i?KEckca-Z!(4mD0>_`ZXt-yYrxi~mIbO8Nr*SkPnB zN_@Dz=Ym!6C{?fWfjy?OS+xi+s-AUeW7OJ8@52+X{tO8^p?j=)0)|WWQtNq)1aE9I z8XN}?lE6U2oIUIUUmrMcb`c*Z*WOOhvYoNm61Z~vr2uTplmrq%gdsNXRFOa<>85i` zsOa_21Kwnz^rUzPYR z16*wQM>fKBiQrd7&q2RnarO+&^iG)9y7*!Y!eqQ$fp4S0!Q1J>y{~Rc+(}y8;B(ac z`*-MQnyp&X@Hqv&m|~pHXfU_im7Etuv2n%ZErZu;F6ziC9p)q>6!*dT$`pBfrEfyY zL4ri)>{!$l?w2L5YO!bfOyxc;^{(H&Wb%Y2IYiDS_afc_ONEl|fxEnS&E8}F`d(w~g?>>? zrnu3#7?s$m7+Q`oymec4R-0@@D`b**&Tf6eDyp(bztAQ7u|K7yn7-;p0XL#UOPhM&YLfe~p&^zqb-+QEdzta5Z zy!9HX<@n~Z4aboAkGuVCa0={XCz6ApJo$E{*|xa%;WLf;hD27Mm)rw#;V(oPP3sFv z_*(+On}GX?nW7K}G9=JmrWN)J4l?B!dTa`HI~hQnoX>pyo$1;bQ80LDUJPGZ5~P%D zg*73H=RTV}w!Puv{DjNQifo5gl<_#3GeNN2=TbJN~t*uhZLyK zoe|9`1y>@Ig+kN$awD)Ia$e{0I#*9>eX4RB=a7(ynx6}&3Ab>NL;wp@7b$kD4N#6z z%(=O;=k}@My}Y{jET~ZFI@^znJ#=l4sp70DRu4!ZCQWAiFO+?(x-lkmwabq;D+`x zfaCSFz8g)RKt}2A&xhY$^hAQDQUVfE=v27jnkPBI%=nGl*qsQX=!{E+a`b~{7vAOB z9=_9-e9J>S&8OG3_oxPmQY9YKY&~%S0>K#AvOnAtAByS4x#KODoPCTqTawsV$eRe3Y7x~ zWR5XU*R#zEk1`WWEZ@H?p3@Ke%9eJi3q*IyNQfbfk;c=`!*1o+XoFXZr~$+mkv_L> zO6x$*u2rm8&31V)d^9u{NrgEM&8p!V}X-w}b2&0JF~Nm}>SYD97G> zQ+q-r%NRy3;4uDKz_($>F$xf;u-O?CPfl z=FT7un_iJ zanx($C;_d*6zOBt%codAx6b9sg{Lvn2TaCTL$9~N*n<_IfgKQfKs}(8<&55a4jV{C zf9IJ>(dlw{@P<;yBI(sv52#);-hZ`=A~kPo#{T5Yd;@H1sk_lU9O7)tW=T_8HhbU-|mE6og720H*Sw zTdub+RBbmc!jg^gzq)wmlie4;Uif+IriR5Fd}oR870B-G-dwJVigeF2`^Y1u8Y~3Y z(TY8Y+8lKk9_Rv3o6D(x;z^=A@69va#VLAmk?Bi(C>*^*N&E_7P~5uSsVO$Du3ze= zmaCQNo>8eYa3e`)wsy2(V^Rf#u2F|zt}nj85vfLen|4@=V}kC#(+vbgIqu%i>SJxn z%MuYydAl4`e*pB)d`)iX(p7vo8Vq*3^4N1NAhTlK%}d6?>-a$KY-k-*29t4*{rEnkWFWx&;n2P6rm~-vJx`wOJ<_hJ@E3A_oPdFf{ZMxdO_9`k znY=lMeXG}dA8VslyWcyVRTSvg;IylM|Hf4lePt!UHbRKs8! z?@2#@mVTh~R-yAKp<*ciEfyHcNZ?l4Pdom)1bzN&`^-8+!Am2n&*ATK@Bi2Q3IV+ddc1>THZS&}v-Rj%0Ge5RWfw_D&q9xjFA@**U z|LOss^+hBiXj*vz?KG3j-dCMlBG=<@wN?cdCFwcdNHns$^2w2(|6an6ynE_u9bAyp z=O$}1u|0X{fkeeZKs;@=?r}PU%^Oxe-{$lL*|eb8fIVol0)@fzKrEH}hCOIBhvcyvP=r+XzWv|4s z(Ut>TB3^!p1Y((AYZV^#slPC`XV0MR5h!A-6Di0h*#{Ek>`3j~(B7vS3KGFApx%dK z?i%6quwEpPRpwc%mBlfIMDT+Fi2}JQ)yMvKf_FnM_e+7^VIipGaG#y%MnEJUHC)~Bxp(+0#111?yqOECakTi& zjUE03Jzwcwt!NER{E*IBqu2>fAVoktl06%AVZ6p#63%8+DqwdsJz;do>b=0V^zXX` zvr#=-U%9C4d-E7bphr8AcIwgESi5)VjeZXYeUX|f$A_O22(6A~?W*^>PW87P7l#GK zFGY6-LLwJ9mWLIZraTk|;+=O&mtTev?`Cp808vNjEHmmzmYWS6wh(N>WD)fax;>7m0Uqw1#&1yPAL><% z9KDT+=Z#Dcg#aOlVG01y{(xN^S!ob}yPcZ#=uGO7$a5P%wEYM3E==zRS;W2B)Tb6k^4JJtQu_w%xDe|$N@|BMm z!&|Qi^$K~IaR@zRwH6M99X4Ilrub5ykNS5*!ynvAn%Ft)>TaDDdAPq#|bG?NWtE0BfKj(@)ZeW z{|P9G0d(kgt)ltKuH7fe*O5D#W8)-{3q11Ix_@THtZVu14eUEkM@l^*Uq$Rgc9SoL z);Z9}qL&Vqe*zU&K+)dYjC)swlCHA9xJ_L(J3FT*+EAbAMCI(lUr9BV{Xnf(C{5YX zSCyfd`mXcaQ;!}!7}OVCP9GmN2C9>aUcHdKEaXGISNIoDT!AiX8)`$wz=02BqLY9@H4E%LT8uhV!maXQjFQ8emxBzF(a~LpL6$D>ZxxA5 z_ddSoLg?HLPp_wFNB;5qtNw9xWt3T=}b_T-_FB3L;Kj!xRC?MR-{j_^ko82Vm z+@EXO?3#{s0Xfut0A{ba1qWbuKp^#xVE>(|H{T$MOu9#c+W&O?pU*}9{4eSS$sOc> zR|omO>3e9)3Fm>jF%7IWvHjBTC(77q+x=72^{<$>DTqs;Q!T#VwY;xuowIjEb-e+W zosDhWUzmmv4bCD?!rWndY=0LYrW*f6d>C-Bxq|uC31icgn#04oS!Vkma=wxtEo*+S zH2?WVLFx=6^xYb5%80#VFNO){i_JuQ!b3U)rN%c22JfpYzEWho>=nMO^W|pvpy~ag z9>TM)P?=YlEcAs8tRD$vFs3dd8zU2Rxuj##Q|E2B_*|>{D&Enw52sL0`_kC%@Yo37 z+odTvsjiYMjQ96M@wmIMTt4||nrRR+*uZmJ(^Rqz;CA-l>NR*}?6reVV`$W5d%&AU z$6EB3OoqAJ4fCg-L!L>__56w)Ge5znHP5@)QNehA2D7$Qjj*ulH0Gq9`NaJ3Cg(z! z1&k>GfHVTp{&7AmWzL%P-(;nD40@k33xAPMc#l>F#E9O8i=OPJGc9~(m6HqCo5y4p z$CtAD+%5_~e5wED)KtQ1YPY{Ufg0cKk+1Ygw)4co`s2)vT^Y*oN2uj1WZ$|81 zVf;}_l~}%>Bj@@NU;Q9CkF&M!V9t~=mtM!rUIp#8G)(~NKyZlNIgEdjZ#W8k)-5ZS zqq5E*v}BMv)Z~Vs*&`6c#krY;JN1GWwS5Iy@!m^$0?&#&?6?u%L}F|86)wh%ROS?Y zkE9i-GTzVxVT+@ijhs+(9-UT^NyPyh0%gr39LfxX?9>{3KZKsTgnk{d{qYWCj;_t% zXM!!-+MQD$@L*<%k`;OW4aEAa{Zp1bsP&SS{ml2Ti*7sBHaC8CvwLZu6OW_s#o*_HjGmRg zHJz0{&E`k-9|84v6C{F2myQPa2rzZL29dDV)HP`t-#cE8XTk9 z7H3<0%(f^FNFxCctw{(RMLezSHMXUV3Zh>E^GFXs%{v2<%4>^m{1{>rO7`^$C zU>2s91nQnPkrvmB5c~3C%emitx=pTf=;oMLc%S%CZW7H-fTr zUtXy0PGEZNPa8S}Ww*Dc7&NxB+KH|~GPvDw5j;0qUOj;SW?5EVAij91Pen7oXrfsf z4Pm_H#MqK=?=ouFAy#V;6US4aPIEgT+;Gv+*f#N?0~VX@5uIl{u1*J^aaqfCKuW(Z z(I)<4c&OXJ{h^gNND)ihWyG~Uk$FY4STku7W9`a?dz!_W+7vQq%}p(1r1_$}j-Fqe z$m+z>P0M+MjHe`Td1+2yNgc?p_VII1Dn3V7;W)FC8R_n$tB; zlX`}549$5k&lA(1)j^|nIb&aW>7Y{k z`qYzD$^fwcU-*FWa~WD5?ErYUI2)R2i>=fJc2@l&z17U+>gvxUrQdGEp6(o|0ntiv zuMU?z!SCRnV4sBNUZ<^{2wmEI-mp0hta=>govpoj+p zIxCc>ilB>vutBdITQjjcUx`Y6y3r!i99l5nB3GDj>44pqB3YaL?!RZ#f6lDQpZ}-) zkZhwrp)UUoe1i(m7|o~y>?Bd@^Jh@@jT_sVxo)uYkRs^Ze+ggur$YVT%cuNLixqu% zJmi|!6J2n^B>Zpi6g(f|06tU^xK3;XG$(6oK&kqkQ8xkENaSx}7FLHz!!)NTMM zv2!`rRKB9LHN#h&mEeG|GPeIgPYwRbqQCu_Mu{AUed}`y@daTa`%fd4Xi$D4)9aL%GdO@y?j>8@wuT(VJGXyD* zDFn_W4o=>gJ3RCzJTz07eTKZyynveQ$&u{{h-&$O??r9DUV3h1-o%v{SfbCXZuE<@ zXU+b@V{F2MjF*Dx$4_8=2Ppd^%xe-z=gbDg5y8E2C9Bhjs~fGMvvg;yT2Fd(dfJQU zL4>x9!|g!k5QpjdJkH<=K|yR(vbWnO0_W&xjl$4Q! zIl#Rc)&vtY>oDJnI|Qyg(;TX>pVtmZ5zq?JSvRrHnPoeO{rTL*a=Oj?XlIKS%Y=5{ zfEwAiRMugLmHrHDmew=EhsK9}ovh&3B2;N^8?e}U(P4rZ9QtH>1N{o4QB(hm>sGuW zn{FWQ=fsFDH4~6I)$!CGJhJryepL&Lh&^J%_5?i+G)#JkLaG?9CGN~*Kpexv zmJl<^9aaa?J3`~4(Yp06Mk##^mD{`Dqm47qY=sXg!QYlcx*!5XS!Y;{Q_P+;n_eT9 zBcn9goi_Sit?aHu*m*woR#;4~4&NB}E|`TlY^N~Us_L@9ib|U9Sv9bi_|omKuFv$f z0i0t0)Q=V&lYcjt9H*95bCWlB2=xBW0nt2HRhIFNdv%v8onMTLTN z!3D1$n*i}#L$hM>M!;rWKxW9jGpy!DF9kMQjJ~wyNRU8Vs#tS0XCgMbOYrnqv#v&K zsK$%iEoq%R=KA*p@6DR~tGz}9U;<$R&?u(3ek{YRu1sxXG%nTOKDBV6KCA$IaXmCi z1@4Hg+fvJi?zB%Qy)Fw98d)%F{G2u_ZCidvUpoFG#hA~js8KJF=YFxf)}99oG~F8S za7=+$`W+1|C`5HeZ#YpvHiTfgxWUA^b~#NbYULY)tF>PbLsI#> z1|A-sjSx^VRv8zAz{kr(zh|PibP47jEzfTx_UKcGE%vsVyN8^bz8Og$TED7(-!gPh z6vC-~9hLXpTo)hhE9^=TzQzs^jL?vAXj|nT>|Y$;m8BEf-$=z`6tn$ z%epw*x6A2c9~4ozD~b!<9*JHqxy++d)v>;>8{Susb%ma*u~B$Ub&BfDN6$zB7533> z+L-{|&Ug<7;zY1KJ})4i=7kS*+u>DoUz+BPL8cPU&0b>T@nkm}bhRtHt`~>J#j~fm z`ST)Xq!v#YJgW18En2rRemA%zGPPjdO2|EEx`0PBw#MoP4wH{_> za;!TosGI&o-~CevB?Ci1T7W~}#kXgUxKLaKYseI$$DZr`$;5{bvN)Qk-l*Ay4N?1d zJS0%9w7rITdC+})II6|FLy!Rj4t-w_W5Ne_9;6wtL?D4+e1reP5nG-m?~9B*Ua^x* z*z!h@JaKD*m}X#G7fzH5GH5-ieo)bbrFkcl=UdiaY*45kG1JTRvOh98KLaGt`35e! zyc&Cw2>}kg{MQ4^i;lJN9-Rx!`(=K}#qB7d7N-lhWNn>!x{LF=Y(`y_karaIGGTUH z-*!{6GVAS}9o`;ySU;?;_F>-T$hJ4`rje72nl{6yAD6%P719_tgit?KDa7w!JJHYGSFEhhbFn`f0>#T7+kas+k9HE-;dJlKee>Kc7XJ);_a-KZ0w#f`zm_0}Bb#@tuuZ-*#qXYD~WsHp)9H ztz3R#$|J?7d#gpYc%Zz*e0caImtc+l1WU4G#%v*CYhtSX5!2H?{-33rD7jM{&Q>q) zLd$^_PUM1zgOz+9lqw#No>mb$dAIQq?}YVe%VR3_Y5J5GaobH(xFTc4)_H?fYtVod z(X>0I^X=SoEFjTUMmvQz2fFxr7Y1Dn?`&L|TW@LjmSvWiffZr0hWdoMuEseNW)ya@}stb3m;Ya;BDQ(c9tt zd=6Bq`hANn4tu`h!RV#!cM)j}-hI6)fHFmQi>@?C3h!BtHyhLCB7vSbWq(;OZ-!S4 zj%>=-Ie74&>oMQXeYO+|klp)6(Rr*23p_5yy&B)rtGM3}O_{zZ_;B<|Fpytx{DoEh z_VWVFPonYh)w%V?$zFhoF;Fy!$d!cCx4-`)wIso~nA}ou>$T@FTc7HMRvWw}e1ix+ zDX6xkzdq@!q4q~3R=Qf5)345m{ciE}wXIb4kR=xpT6NyNv&y)4fQX>kO*WRGh%qpz z7?-u2F>c_El|wd(MtDfFtl%nD)G8BvMB0QVcchvS?)`3nQ$2-&QrCku}sv>0`Gu3O1&LQoG7 zY=wBg>DB^I#feXD52bcz8wVs}!f$-(-|cB$O{rf`wXHgV1C zrV4FB8nk^tSw*EFW6GIpe1oV2ZEEM;0fHh_%b6MUP3S^5@2x}dv{CU_4~5L3f$le8K~1ADaf;t)wyoXg)A-0=e#?W zxqtSGV&f6q!9sWs8%%V#I_;uMIk=Mut~gmv>$)#LhdAn$2##2t&?$CuJB5@RRcvwU zJj(wWzzBa{H2*Qf`t`+m9*_t%%^k+G&jqlny{)Pv&1{&DOM2L>7^(BEm@Y0ZFRPzy zHzrwME}dVN==A2#H8fKE#Sxg4fjz#~fcMPD>!QUvzRGuF*HTV$d)9ZXCiIp-puz}; z5fgr9#*x%+Rq4B|%0cIrm{{>1I3_G-L%y4`UqDfBf}j3#{^%jKx1le0Hqy+~7sMu7 zhG0CtHRhY$^+SbV# z>$pYR%;PJMO_(2F{B=+K@PMhvkN)_^X96@HZA1_Tz1+KB_&j{;B-rLzu2U9%YX(1F zZ{v~^T)E`Ij#nenonQ`wWIxQgc-ha-UDsGCc)4O?xq2^dDWjjKul>+-!$jS_{Aa7$ zNoX~k8UJ}@r^a2r3*uOZ$b0oZ*}+j>(7K#%XC=%_$L(Eo&yj98;yyCk6B^%MD=0Cl zNdKw6xUw;&>x&usk$Ga9nuYh!6~X-Gcyw})_Y(5Vx+deWy0jC@gWko9=k1t#;V%RI zD2l0CxKr@u{zsze!#8)HyhTa?MXYzO{YlSHN&fuz#U07E_-|_qCR;qP{-tOjy6z(qC8UMp&JU4na{-4>m zPVc>0A#&Mz%6TR(KU+PnpSj5Eg?g*P+#{}1-wGpxy|OBV(~ zkQzXGuc9KL^qPoD7ZDKYpaRlCKqNpQ6zLrl6cv;rAXTdL-c))gv?TPJfM9?SzsGmZ zdq!XV=A1eIW`-YJz;%V^x!HT|wbx#It@}n53AeMmMQjw_?t!L!uuc-v+bw0|3*J)- ziE}rZ16nRbJy9${W}Ru_ky3LsE2@+HHFX?QIz^SQ*lripi6l*SD|u(GfS58H3{c;j zo9OU@(YhmIm5Rz%8ch!ptW1NOz_Kp3@||iLya`vO=T@3N?l*b9n=pqacOHU6^5*g` zJCv!}dbE?2zWI{Ews79rH%%vOwSJOo>Gf^uC?Ufe zVstlJxKs0Cn#0l=lx97rKbV?Mo%X(Zpt|dx^x?By|NT|f<^#*9Z;((PawP+-r&(>q zfa%oOP_JQe$yOwNyBTl-rg$hPM>4PwwFUDz5`h-9T2jJ%BXTosxC6LPM6x{YzN=zKpR2Kwbyiho^cWu#OUYBZ#I`Q zd{fi>r}wKV-XyE=#g6lagmK0MtD`MxTCqP`Tx(L`_I4C81CC&CFvEo@$^~D z$BQ-VK~q^LWHcv)JpWB?03dT;cMhPzn@H9b(C~}C^ZP+m)J0IP-jzms{lSd-pQMm3 zCID@cJI25j$;MfypY^T(D9vO4S(+F1kJ7vbk$JnP^?Io7=qqM8$@Z~Xp0Prg*~8f_ zkLk^eg@Ht#3Cp}OOf+e`rghm)?8QMv2q*S)@7(Xhoe{{IYLB?^Tv9)VGg}ml#NU_O z`kC>MGf+0O6u88BC+#=fS1x%#!=}zM>J#NU?Pzs#2Fe6xyDmHe8UiT`m9AvMba72@ zq57@Ug|byURA)3IxW*>!$Bzn@4&J(l_QGOwE)HL}CG{u;azVo6 z)Az=Skr|x0x|Z1sZuB@e%leNabKb8W6>|1|T8JdEkrRG>S!s7H>lx@{g{YnWAeaeS zJlvL1UiA+7h8NN2)>I)aRc&yT#Mb(i*p^bEgq+KXe7>_170ojlHm-$rYjw(C#+|#i z=_ZykFw@H~wV~mpk9bj77l-U_o_Fbm9ix5_#q%)1+}}1vqCiaA=icz1GIO#Qs5Wt* z{OU*rdf>ik2m@g=Q0i?(^53>8aY@=vES`K7Y3G+?uB_crcvG`o&6ayld3^r`&H)Kr zRH=t686q<_UHDvG=c{#?57(^3t_X^KIm$Oa5PS9HIV%x^T!(MltRwe%HyV2$wnmCI zeMep1xVgJS`<7-1&F3^1QdmHa6qLR|DY`**d<4)@FWw21f0x{=!NxVoWbHq?am869 zGg?_Ilj!Yh>en{tA}!w|X5AZ>n&NhW{MoK+m!aB+NN8ySBVdUjs6T`_}e)jREO8dj6vWUk%XSrD|;IJQhJL;W3LC1wn} zjonJcQto!Kdq;|idLhOh*3?GQ-$2yxWg$vq0^O@QDTlGCz}Q7`D-Y7fqudz3xaWSP z-Y;!qq~IeL@J`9{R+?Y10cl-o{$3I#TYWbJa|=$|;iA}?s`i;8__dp^nEI4|HGf9y zEA*F_+mQLRMwYZSwUn#-D{M8qmy#~Vw_Ih~O)0`kb{;ObH9(qc-&eURL2@Oei!vrN ztuAGjmGtFt&P#e(k44W#rpu0i*{1N|`mwL+oR#+mCXUnSE5a^8pl5v+{R!wShlq7XEW2bAG~`;u5;pq|qeO2pWDw==Phg13C!h|EbFB?s6!e z0~OD{=IJoYH0WAsmiJ&cJ8Jrrp#&K^c~}tCS-QR&Kam?B!_5oXBZC}*FX~JZ&!=!x zVejUn9bi1UD@NYz8~U1zDQBAM@5U>(a3gf?jN>7NIIDIRcAf~S)rw=aIk#6Xm)p)Q zQr8?7kl@Bw$io77CRTYWfp*^uun?`$#|TJiZ+zm?r+e`gKZyLU@BudhZDXH!=wXb5 zV8MV9I2}wE&83FwZ>v=>rC^?Z>R`2@r^v9t_2C1t9GhaemU%PGNY&pYAI6Bgf@MLT zt3j27D5T`j?8n9RyFIe8eUa&Q{;tX=W*)DgPH308WGfE|fez=r?>`*C53?K<|X4WDYs-pKoyZ|9NaE-Zi`5!xl5PYZ7YajwE?TmpEl>;sI#T|Y;-1q@TUO>0;s z$h#+j42#tor*V^64$P3!{m3k++M$k-wo`#huKDGIrP#?dB@Ed4G8egWxE9c25ay2) znimlTUB`ub7pki!NqJ;1R|dwE`PsY`viivWeQ* zzs{hB_CfWozG%yxI#^$e8k6S2esONc90}n(?rfU`G`z!-^@!{hN1+P@;j-9vr8V|r zcklRA6<8W3SBvArx^h_2uFI}Fc)IP^QB@{%DQRg7s9CrtUG`z^zQ1kRhSpx6(I!yj zzMFHDO=U^d*QNK_5|mIxtzDJqN^U+C)_lMawW37j29UK!rZJU7+wDlni)U)DQZb$4 zZ+l|wL7u-M;WQ3hiuaNuX(QptZQNb`)oV+}i${+YEC$kfL+ny|!}yFBkGt8F%eKh> z@cbh1_H;_%sz9{jRXn{zhIPDAh1ojuZdP(%XdrO2DZtgBP7|_e%(OQiM__WYV$8uA z*g5e}tTG4CRlPD8ea{*-#2ck4h%pX)Bsq~BNOAUpu>+4F0x@kd)8XJin%plLfsPWo zwADU;F{non8)UJcgAqq9B_fx{r9r106HWNpESin%N2rs!v&#Y%7TnDwp>53&>LzD=cn?fvb?{ff9mJ7o+Z!#p(p270KkCQI*Dzp^W%9c z?z}jX-r}0JX&0sOr9A<`_n^*Ogowyl?6QZ0mX0F@596Sz!trS3_ozKZgosrcLf8A! zPdR~pK|3KM3@NC!{6qUckF6))|IbJJlQH`5Ge&;GEeA>BA#i5Hx0+NA^!KXW_OcF2 zA%P_vC4VMO^EcugA?^8VO@e?4{4Oj8ohmJP3v$AFZPaZ-F~F^$sh^LCu1oJxE|9c+FCv2}9l*Ddm2q ze9Yy+EB&Lp+ZETTpLV8Owp6o5zvsg)`GSe%oXnPXUFiW0`Vd3DI0-TIMV}*}-S2E=4D(-Ps~vofvN$ z(iSYKHDN=re&I~J`n6`N-R9o>9-~Llcj1mY8b~wzV|7@e)Qp<4>73e#bNE!IfHTlL zYhEHuRO%|>J}kYG&Rd859{25-svSZG^LuN$GEVWTs;>I%YX;iI*6KcD-YljC4|VB- zB7JqGL4iU8jVQEJ=mQea^>y|0JlZfLOi4t*#ehKt^|m^+1pTSx9Baujs zR}l+MaaI*3x{$QbXCF?IKVmJXg$hAeoSO4ZCJ|yC@i&vxo)81U=KoGD{`4VC`&)I` z7cj+P0wdJTw4$;WlTw0=emt55t#0g!6qwoiAfbg$F!t&M^Jl)-Tbg#5I3zK}iOx4s z1`O?Ub6}s8dpgbg`^o~>+)hqUZ!?AIS*qP-r3n@OWaAvD^JI=XfDC4Uv&AMM+7-eh zFFoEqv)VT_<0x?Z6i2~5&}VDmm>B>0Q+uQdk~=zD6$n}?(NvgIR;(ZrZGK=ha{|nUkoz!Ih*Q&|< zuP|REe;%4j?%~uq<1yZ-ni~&EG@=Em(Jw(eqy)11fd6Rk*nm`I@APBiCUgAT9hg7i zub(|kwp9MtPB+K@Et$7-@gI_T-!ekx&WMA>*A>!JbJzDxEjnT@fWN$${QAMnLBQ=D zBIA3gPo;0u#vG~%cLV5N**xVSH0hLAGc3GJ6xn#EzcfJ&PI;5o`YO(=aD9#)jdS2k zY{}<1a28A)c^=bl=0_*re5MPNgUgtwXk>%k_=JfaD{;!7HtXO_`r=ynA$0taKFB{u z7bUU*r-doRYaZ9uo1rhDjVo~9UhJL8c0Hx-epKcBg9yP9f*a?+kX#*Tya?0Be(!+O zt;!tMXX1-rIX!uobh#zsb2aHx`t!oM!o`5{INLO0-9vjpr_dMc6H6P4de;X``E_ zGbI~@rn1fFov}*GD84xQi>aSxmbSU=Z6UQ3)lbeWZ+-7I0cuEr6KD8br7>2gq;)XM zhb|csUdbDLK@d7a9a-+-B2O)|;7SJEEbbTNK)>v>e#CwSvkpr|*ByO&(dEQI*gmUp z4?N(5$mk4f#-XAP;ro`D_^0=A{y;7_s!?P}bWbnyQZ%X28A0RrM+aq>_0LSJ+@_Ul z=`!7_ps{Y{spx8PV=2y=kCjy)tBB~SN}r>~p5>6bBsi7Jkr*O=jl79=9;Tz}-@#oy zUlN}2F*ms0r4T24b6lK1Y{IlnP$P7Ui__I^YK8^in!dUnEdPUOib0$Tx4Uluum*Kl zK(1B|d$B!y8WwBho3&*W`GUBfjFUmpJthq}Ge@6}-5jkSMwm?NFjCc;2*i|iDjUaz ztQ)ScS_RHk@B}xq;sr8LfGFI1qR;(khOwP2K* z;lOwOGvI~@QhM_}f3_p5X@p~=A|^cIeqhVF9OO!_{VR^dn{l66@pTOCD!D93XI8LJ=(l z#esUetclBJc9Lu?~O0*7jH8CY&N{}NF*wt#BH0lM+2@a>Eu{1h2rR{fzR#W?lzUGw8nwrNW z&D%Me6)oJVz%0*$-=Vfi;H~Z`2-6CI7Bk$ta6Qj4j(m!hfwn_Pg^kpsO_0-$tQ;(i zXCEW5PpsDV?-#!*f%+K$_YKO{I{ujM31NqCf~V9dNJ&Ckx(co%abP*Z7fWi)_S1UR z98+jW8;z8asq_X4BzNTpk+JeEB3?9)WUvb3526@u4hSX0I)fG_JMJaowE1M$$mOa! z{iOt6qq)-b=344`o4N<7lAktUbw(Bb9EMo3YPYPFG_SsQ@J9&#Du8FcW}jqNxb%Z` z9TLRqL^zF=0OX5gqaE_H^{*wr7~Ln=&kk&kna7$+=&EABZ>*!{!hR4@6yY6E7V5g1 zHtBLaI!{xf(P08&V12b&_rw()=%zotf4(Do7yj(hw!x@dvACP7l0~CabR>1WfRA-j zSF)AjNJnGVeN{%oGyhZ5jVJ&2|EyH|KF?FhFDxzn(Nr9pG})>d0X956@ykC$ntvs5 z`HxzO|EMhTVfvYPcHW<36E&P&U@&cu1yVFNqImH*>4xM3i*sf+CpyrBF{E{?? zYwfaQ?Qy195owBNx9Gx|wHvCuUD$L@*U=pvMq}D_l;tZ-lRDNm22O=n$-{+c$)L1f zO0!PMFl;-&{i^rcg=)ZC>Cj&Q3E~Rqt)j|WCvam^Bb6wGvM9DHMEs)P2hT4sB=eat zt9A=4@FwWOtkGIP1IjxBKkORL2phitqO1|COvuTB%Jkoov2u$#clPF*jhD+iuHY0H zakU(qTtD|KKeW}PE8zM4Gg|WrylYuEDjs3GtBm+zk?gn3HgIcQIA5cV$9kX1hk4Er zL}6EOJ}3wqj`DEnaJSjCzIR{wn#K&`zOLxg2s#v^W)vUptr! zr}JS=VXLUHATQ;y*A+=V)rU`F$wo*M-ZE$|=L;;PonItbaf^VTh0zxiIxRsMvD6|q zyh`pD=kdGnhtFZ9iCTr;Wu$VK8d&$T+UJ0etfkynfC$Z`U9ZbqQ$O|3^C{@t~%lq~PEcbv5cjg>TMNDF{>~=XY zPh6q{RuNU7)|u?Of2jPX*5UB+t#@WU*KVQ6Zq6Q=aTKR3i!#+b3NIgyQZlV>-!wK|IrKfw5e4^NS~|QPVBD?B zE9RqEN=vkI>jLZ!F8%{d50~tN^1mT; zmkG*}s7WDkJp5$Cr>XZ*MOZXwxWV(Ao=cbK8q)trHh%KBks01P-*j|kq^W{1a~$j0 z6mX^5?Rkv#Y@-`CB?B2N-kF*LrWs!xe{9_9pK&{7rfAAMGv)JT()-c0>TaCX1}ePv`ynk&(U%GX&n40;#^f$f_A6V^fS%n{@ORM@(L5JsQcdO@T4$LvPD&-)DTw0Bi$LRt6 zDL9o66psS*3T_(h?!t388}IK$!ux9ic$T2OOdC9yG}tLXK}Q;pZV#yeT3~C_tk?+s zeB_B3_?;*He0vVh0+Q0?VQuSx+G&Od9`Y5NCNhzQ&E3G;oU#f@i^}z={kj1cMIQ`( zK|?0Lfq8L?d9~<*^|Sf-r(tncmk-;UmZzIQyGkBW`^GT4BW2EmA4KGPQr{*Ez8>Hg zm^l8x{VT#frj4JEUEVlwd&>Scm3)!Cq5}?*J-h??1NUzj4@D+(fKl9`^Wh=iQ+M9s zx%*Om^+F!{FSrN4Eb$np;*V011iQFF%P#R4K;U5j7c#$U`4eq;#OzwdKKDL&*dtI7vd za5L-MvtL2R3|e;Z#6s-QybO5G5ktl2V|LaDZajS{KPT=Tmb_&~b)3t}_>Jy@pp?f! z_!vMO2VTU%U!tEGm9+tbxw71kgXHJF@3pk+U*^q2{DFJrSA<=8B@cf-7-IJY#yd*- z337h)y~x2q)6lzr#r-SB_(99we+*nSj@frA9z6$5{BOaBl*p98P78^Jp8aka(OpF@0V$d)w67!mBNwKZ{lPFjFiq6 z-2xH9^-F$EWJdX7Bb{TgInOi4VJ19&ZuQq?BdO{~jz5<{)U*<71)tx76U5%90_&_> zWdX)B%2nR&Z)(ev{r*>Y52Nm6!2%KZ)UZ>CXU z^zkpt_YLUh5N2gS<_Yi9UrGC9Kwby``Z~v`eP(QKGuN_POWjV*{2Rwd@NWvwe*!qp z5XFStVVK8f-F;EAy!3-e>$l|sxDW_Z3U~Sk(GABVz#RZAJ6JENpZ@9^NMN3jx0!x@ zZTS4L(C_vuW%N-UtviY9CT${@X1cZL^>Tt>*0r1SbIw*^Dj07)uP&o8VS@t-nqPg$ zBGX1GFp$3Ty9Cgh!)m$F%iV+Si!y%z{|(`q$mGw*_D}B2osm`%1AUfuh#~~IeanOY zEAGd?4dgeYa&2IZE%5GuL2Gf73*aJ&_#p$muD{^^)j+s18{+=5d{_Q-n2f)@?v7Du zbu5@@TQPuU?s-4yxdqDAG}2h`?_{!A#W}L)0S}^1&Dk^7b`S=RLJPou>Z}0oG-EcbNABw z6ZUWZL(lT-U$?L8{|ft8h&-7Mf7`v{{s#M33)y7a@c459=U)HAS^oMm_RNORdIt=- z4+7(gFNO-6z6P{PbN=coe_b`ScwvVIl*^p?NAZIo$46s;Sm*f$sAz3ADZFaoIXt$1Dho4b7W z+j@~QDuuT?09r#4qu&X%%Rh)vYkzT=zu7OaML&q|%qYhuPz2CAUVQU;UGgKoI(}LE zACvYkfx>S-`+{Xh1tJ1&0!|J{R(7?uCy$$#uzw}H~)-=P0KkSiq*|FU^y{SErB zHlnEN$NA?9b{P1>W1jzYQFrE*+;?M#5zjusb2N#hQ;g-31B#9LMt^gezb+cUiG&c& z>IPbUQ!8o0cmulXECzq^m%jo8HfcbY=QtxKP#fc^cW2AU672teM)`HCJ_+`(UH>%*ISKZA2`9n+pXZccZR8}_|J8$>1p6nM z{gcf8NoM~a*Hb5%{a=%SCz*ZVM&kFp+(~BtB(wj=CFrkf<|MQKdqVmov%m7Y2RX^? z4;lP=8ac`ApOo>Ol<}OD@%*#;>ZFY4f0fFel<}OD@tlg97_% zSb0upwK_y28z4s5or{8;k=6|@b?{hI=ty}hP4@h@nF!4*nPvICS;)m)vPwH?B^UN2 zy{E8k^AP(+3S*md`eBeCU+WbGz%a$g~1sATUkiujqhjjM^2vma?FY_sc4&O$7%8&eMoE-P(P8;n%DgQLIB@9*&;YrJR-~Y1SC+HbrgV$n0Afs+u{X)hV|A;N) zl*orIhOH|{Db8KkoH|PnxFiX3I zK7^!4FpVg|KQVjewF}3`x+Q@p8+NZBys4oC>=G*(cv-?Yd4PyQcq-8)ub}*5)FHrYY!iQ$=5j@V=nywvY`fgYl`cc)*!Mfa zlB#g!Fg_d*g3Dan?{)EaxDaOl3TN#1ovVeDPUSsnY)Q&psz4_H^ZxlkRmRxXs68D| zq)>X|k;1AKL$YbQS@c+}>DSg%=TL27eem$1`r=o2C3EjepLJi^0Bl#_YGxgxDYW)^ zNpl?}a{Ys;wza4DGZ#IxuQ3O)+?uPSaJ@TVPAK_pTq0T*r~Y`oTU3ZnxlKn-=vpzk zt8Z!UL)%T{=S6?!WdT*IajB|7CEa}c5_hgP;~8zohw+Lw=NG-H_vLyeH9lJCwllLk zX;_;TM9hnkX>HxB=|XD^zcgJ`5E%kXz^+u{EKmhB=Z5dT($g-`tzZ+1P`k5j+er+5 zzVvOX>gjMkd!j+y*YlYTRBag)mAVWtuCV|H}4HZ$H>N|tx^KtT^!`shW zy##bDZ|+Ws3^cO9&W(aEfIrl_7C2ZRzy2tB{LXlLu89>vK;qZ4F~S?`#kk#O8SV>Z zSngL&G|MlmDD=J*_pnR8ruH%?NR60He13oNxy(q8Q$Q|IA)kX)oDVC(w6#5{?aV4R zwi4>-uA(<9Ak)`-C9K?NHCA7htmEpSRd}&0jdlf~(oqXiWxNfrPppiZ8XCEL&^X;d zUPL4lb@-ue|31zZ1)^D-%6&?>q*(;FyE>#LY8`bo_T$Uz_ponrccgcU1h@W4T=6@{ zUIPdz+e+h&+AqmlJ><^GHEwt+A{FavPDVXJ zG{n!Vx40;xzJZ1Ojy=|I61wBaRY z6(t_EqhL=qd-Hydp`?4MeDpF^?2IB>>0uc`NPRx9@uCwwUeSlA?V2j{!)wd2(RHT@ z59+?(tCs5^^7!{RTB+dA;aD(pDD}{a_ZcYfNhM8aQhnMb5e`l6uKNS8k2`2^12cgK zJ5g%^0yupT2|&Pw7jp3tnl|<7N-FPuXVN*~adma9#_><>ni9vcO}O3OajJ8%l*2NF zp88SborcbBS?KQd3&#UGb*1VM??$H%`+pf{5hP1XkrQe*E1ybKYglvmarfx9_*T%x zSLGF_S$kSPDg_cP>`01tYzL?Hx0*cu@^a5f*-mq0G`8qC?;>k41$B*F_dONTV98aj zd7n^5y_^3gQzzoxlFrnCZHj-~MCmY2XEx(_*5}HXM;fYf!oo!9v(Jb_RlOkeN>uqU z8CJJ2(0q{b9&$Kw3}_U&7rf@jxnzv_uI3%+)tMP80{ z|Jz&Yiz4~B$axEGWOcjZ+!@F5C)GxGqdBC;a$=mhm^x*Nd}VVyMu-3xeDZZN27j{w z;%Ph>r-z!0NP8`kJyBump6q-WGp))Hvdgm{U%I_I)*z0yYqs#bIZhs-#Fg8V=OF6F z=+Qz;UA4)1U$PqaJUAqAI-Q&e36L%^mm{s{5bM4)->SSzFWW*VV%wAoKq!N0ZW?b0 z8~CClguY&vq3y|PW(%nrK)HCf_ezMsWo2VYiI5dC#iilcxQhwJ>m41%7P^wW1#~K; zk5sZVqe3bUo%X$c5G7GzL4+F3A4J)kmO_~I4s?s91pB*zZ^!qv>8oVE_tda>UYI7& zL&Ud_XTex;p-2z~UI3dOjiRyINS%st6}^9?ROXZ2`dMC;*W>C!)UH+dej`;KHd_6K+EmQ~->f#;tS+atU&Jxhm2t+@>-BJXb^opKF&;*|9%da0Zpd9X;-;+{ zkuJz%=dkAulS?^2TGnUgFr|4>CG#}q{oKR@{-`Ro>(yL04En)}qb-#C2% zpPF4)aO<*QSl2AAtBYMa5}j&cyI0z?lj5Op8d(OfyR*3M!zoqTgM6Ll=-^emJMe8T zG>s`f5Mme44n?&4>bxFbRjL|W_onP7={U+Jd4!f!Bq40V`mGEDM$`E#hn1wWp&U9p zNT<3;X~jG=I`*rIz;O+?+F=o_Ku=jp5ku1_Q6vtqc9PoLLw2NBGxol-5W+;hsqMBN z+B7OzvHH+YJKc8Jba+@U!+fRY<%>ref}iwf!bg^O3pCS3ECM>0o*)>F=({&#=E+FY zzV}DYaa2^|7LiSCP%0xAwW-$r?wXj6OCtOgF_scs>V}9u+A{_t22YbrUo5fuKF?*M z?I&<7`PAX&+S!G>>PncQUo^t+j23O3i(A%h;Hjh5%Q{0w%j6-mw*s!*$T++GErXHJ zRRxv^X)}G8?B(apcEO1<_{H;K;^2_JX@Ybj7G#J!jio{{C!@?tm}e%ku@$C;PsR+g zbLo>g7TP}>)6su?9sFtjtcB2W6x>dGE~F}h#uhu9Clzg?)V*k?*}kxCx7gTUUBH8U zpR%@OXxqE7lwUDgk~R5Q63lFY^J~i}^XiJ)bE7hLk}z{bUejTB75u^wQlAeI+dw0@ z*2iN@LgG6c)LS5!u+_#VIY57}qs8oj_R;7rEdEmQT$emvalC&#T?*%(L+ESd#c&6q zD7I`|93GZxZZ6J=eo8w>Yxc#E-0@0F3p&Rej;Re`hqvj#TLG~p3Sm63N|3CCz9Zd< zEy(zB!Pm*^FEihL`mSuJWe*LsHc%#eq(zS%FlS-m0Z0Hf(lw7+n&%xp^<{jQ(D*Izy--D<_d0(;5%Oo>dT-v1u6Q z@B!L&ry6@Hz$b06Xc5ZT_-&<>XZ~IQc6q0eCuSJWHV&y!G6Xuum>f;RBeqMJHAQX0 zG>~Uhrqysptjz?0+XSw@&$_9MQ_FvFA{R_Iw zmLQA%R$ZQWfRpm9OTCJ6-L#34i;FiWboPNWgOMP0@P|jfXihunD^KiP#TfF{^x`%- z6msKXddT>xXe%r@MQ16CHrLy^^cL5UMqB*@i4Q6l8L6qU6~0D*&M&)L^cKtoTY};V zE3|DWjX7Vo1A3OO^XcJz&d|mO?}&uumbsj+fmj22r>xp30)(fWB&#Yf_<;KoZoz%m zu9wEVC5{m7QS{LKUTh6CeO8c%m%u#HtavvE<;EbCgp3QBRe4@?&-t}1L5b5nmQNqc zcURi%*}XJKFI4{QB9+wG@2{`G#c~@{(gk#UH(p>#ryZ_{wbP3Bs^4#Ry=MI|Vta~K zB8KuCum5EebEx|K_(mIYo8b$RipEKAEQvX}-*84mhb?u>?m;_qAedzk04_2&SK*jfHF^zU@cOfR!cs z^%^R7oLdfDCTBu;SDPQS1(GQc$rUfwb2m~{4t@iX!lZ_z{iOrr_3CQ@Ry#yulJ_Ya z>!fLHGYO)rQ3!8HeN(?BngA zU`<(OC&9J{vXKnm)>e3FSJ)f|p0^uOmGg%^G75pD3;G zCu45K0#+EgU%n#aZep_bq{-gNK5RtudIG{IGoRxYIa{Adr&A3szX&I8ip|U*Uae+M z)2Zj@6KXH3GY4ymN3ung@DjJ6g^S5)Otd|xTk|jK>Cg3huIYxGv3`rGMRS?ZkN}uAQIlNg1wtFOp z*Ts|s7S&(3L(SZoXnQ=M?R45r4H~Xj zM{Pb(t9PsFj$o833M`)AB=+I;&<%J|fc0*k^0WujW80vP{a44)qec9U)fKkquQ%~N zBa)|Pp&2I)L2$wYfoW14C!AKnjH9><;F+2aC#oAOLA&QYJ{vwabE4_cxF4*z+sPBF zq>Ayo1sJlQHb!wxA!fh!DGN*O%tCqf)?iti^*u@MnlohNTu`yXI}V2Xn{~6>S(OcL zPOx|fToYEZwF%V7XW#PysxWTSP*=t6HQnx7RXy8GdfH4dX(1?Po&>?Id~_Qsdjr!S zC-uhQdTDT{vi{810kb>}eD~+z7IhN7ak(`$-(<^BfE=2K&=&y4K6&E_Z~~(q4kswd zI=MVb>`4)9UoUqju~)vb>$N7*9RPvp3<0O0vF;Uar&Zs_G>o2FIn;d%%=dB=Fr<)G=i<5)z)49%H1J@@Fz^H;2q7YynRH-;79lcYS5PIXS7CmBbkpW-J& z2-?Th$3D7%)??H+Ra`vA4k_C+E>mlUFp);4A*sTM2W0}!EHC#XEdiPhYQ5qg zM1xm{AQ(1)_2k3B!>CkG&s^Z-(nH|JYmMM}JoB!@MT26bzg{%7f;kBj9lCWP%{v$k zNH*e0szV#k1a$d&xA)^zH}?GDhF)OXW{zl$4f^W|TKt*IB>9I}fb@U^ECdtAy~2!Z zjaI}mu5!!7-H^R<-KA2C?s}FM5iRl5oy7D838!qFC)Nll3vBChUT?;S=DvGar_)A7{YmbD&4)vFDjir3Z&L4x%$(Iie0e zL}-}Dbwn*Aq`%3w&2bREWY9=)IcWm)B<)=K#?qmNHL@v2V$G**IkXVPa-QST3ssh4 zI896l`g^#NE~f47X#MrfOAM+XqMz9&dM|2R#dal;ad1(vcIQrmidouR@}cjKS{15W z<7v9)gDA}WMv@r%5Nhy8bc}t*r)bp%{II)jfH!d9ra#VB0toW)QX@((GN~R9hOb_J z;hcG?oz3*&8P4KniseOT%GJFlrhw0f8PVd6ypCYeaWAUq3b8}Mhih_E7FmM4s(f*Z z-Dd^Ix`%{WE}Lo4dO8@B z-FW%VljyXXUwiZNFfh=8eJ$B+%jJMpkTGIo!+N7W&cL zv2;Mk=5gcUP8exDW_e!=4Tuq8iYT zM5)B1m6B%issbP25a|A3CEIz$rl+%%7?ypD=id@cjIAUE?_W`%>%3gUMg(YcD(%iT zMgu@Gx8%Cq<3k(yrtq?ux!8&x z0s}Nve{ADHq?q8R5djL8#6SVGR`*HHN~($j4p;EI@ssJ_H@9I zxd}72WN5c2hlEBKPje_PX4>I!DlE)XCvqVN@);z90kY7heGgp01FuK| zpJSWxaN)Ul-KvVRbh-Bl!QCZ|(|gX;Tb7D(6~>@91QFb9KT5pALcL>5L30RMr*XAH zjOV__a}Y0)$DQ;y>(QA}rQqe`=U_n-Xvxjg)+z#MxZ-7ng~ZeaX{rZGUxu2_EfbRq zbJV75mShB6hS?4g`0NXiUv$HL)x#GmM;Zsl$DE5Uy}Ns3!kr!C9WwqQDs|rpSM(Mp ziVMw~hQ2mG_cGt~3_Da{ms+flO;fMO+?CU2A?~78r11Q?cz6!30Qs;X-*M{08g|CQ zp<3^ALLqM|-_3*)>}jj|>9b?+r-Ht91@n)(NR@zA)6e2axRa5SGD3TOmF_M~{m(SM zrW;?{nlTP#r?}Cq;+9*l?LkX6Kk%8!{rkt#6EHQ$rBk9mPPa;F zcis&!Gtw0>821tdXK}Qea6ySw)R#Xs`vOtiVlB45-o1M^Ic9lX^-bVvy-)6nRk`@a zv2~XHAy-uq%HJVfUb>*b@Hzjp^RqvQF3UALtG$uCqw5D{>Fml@26++ za`L#};&p~9NTs60f*A9PRok+?dnFmk*V6yYn>Fy2-qd%J$*9*=#U z20CI25qajcdI};=`!!9?l!UJ}@(0mrc#k$_`}pZ*(>KTQ86FN>9E)(f|0$kmiRsBX zQ?ujZJ}*sbgWMOMjOnHyc^Ui8a6y$4Z&Z^6<3^7|Fh=P8P&5dHQ&g?d321c^c}0;) zMdX!o>1!StQ|X;Y@(X){=|^Z#EP)NrI{vuVcfCbsDm6l!*ItybI!f-To`~&q)o?{p zv(2enibS4h2tDCE>>REEyRE59zh3)3b$*k*Pgg{*IuzftW%B%!uIL0GCAmmOYNadQ z6${^3#NKURKa0OM8ul^QScf~q#lcp|U5D>oB(+ zGzGH2JmXe54t}3AART`uV3_B0y=84`u+$8X>5#y= zDLdjUAhl&F@TM3Z6q54V$;*mefjY4y|*UC0&0oY55i=PR8L2h z&D+?-Hpq8x3E|#h6p`dD+kkK+Ql=npy|${XIMZZsr2T6s)5|F-j@t~^0yTxxvxA!- zC(hx-_uP1l?+%;$E1_QG&61f)_EBd9tPN@l5Tv22LpSpBCwXxdzm>77OTUa9> z&Z_0m@R?5jq@(5omvMVHAPu5PWGm}xdHKo!aR<9_M7Q8XCr>&`0G} zSsOLvAW$>OJz*QC;iKQ}zI)HZN1n+W9n;7TpFG?4WT|z%EsgXrG=^^KX14C>JkgMf zEk%5ecu4YkvIY$tr$ykNBYZj3?I_{EiD<_Ox<8gW61l^#nPLF1R(SHU>sCD+q!^a7Bta}N`c7EPjw+gb_{31>6*?IJlczIa~GIy%!7HJmY3igdg@FxCP z5>KCQBSL9h80(z#0Z9?`IH??RYJYU>oz zqueoNn>wZ1+U{!*8ghl2*kWErvI910rSntYoxPp~4GKGy4Xo$NpIy)FLy1JkT5iec z6U=p3du;Xl5Iqkm$vN$mG&6CMEegW;vxmD~rgLH6j*6b(Zl=@nfES%4cjp1$#$Tu8+X#93`@JM;MUwkK&$_B-Y;nta#3ZathFw|~eZ zZhp!=IZBgQ7g_c4eJ|iV>BlP$DvnG<0j@{`Dp%}=Mv<0Xd!&cQUQ#-v}p5*4v(l6_*@PIr^)Li~MJswDy1 z4_e=q<$ChCw&UwB0CCAfIMW>d8qPlp2R9pb-g4cDefF`hn?L%inhE2nnu~Wz0F@;k zsesQ`JC99;kNsxgE8!*gQ&Hp1B_KQ*Ha7@%1ydBIUtYYN z#b>m1My_8exeHG<2C;KHrTPvxY>F)|a6+xTeeUYQJ>|n2o8fWKIdFNA7qb)>=;OUf z@`FhD3L11s_(3$uTt5a-jiN`Fo81_SbI?4b&^m(=m?0dRq-~GU;UvBiCIAzOxet%3 zKb7xH{uWOQcPM|%yOlP*b%`hDj^hru0)ZBl=SrF6EN8Zc>^5Qw;0H?25Z{oJ^FMz@%g=Q*T zKTp{5%1wRN)W2@6G#_>NgQ%^ExseD*hWc(X5Fmt0+3E9h=LB;+FLvb(jLrRi;i4@o zn$50D7(sc}9a1*e2B&grJckXB+7qXVem*Ql`10N%Eh$`PVOvn6@Ul5gbdsE6yk&YN zs)V=~%QBxEk%j%aa)+gr%c^IpgLQF0k$OohwR#b7dIMaeaYE)`Ds=qk=m4Hu72 z!R8c>nX*KS+cfO*tEFxfemyXv+NCqZn5f9>btxHR!Iei+I0Gc11Qb^3;@N3Bv*B9h zX|CWG7luyfaSMH$VH0b*AYbhED@k#g*yhTAgd=J9bb14&9DG;OZ^;+i^ zV;ShY2$7uNa!j(N?U7zVuk||%CkW*trnt(=`7o!hO{i#U;~+uFZiz2Yq@Ju3ng^zX zhRk2axiG&$DVv#L)T1+nY{nlK6uek??RKfK@YMh;`@&tz_PBa`!XTVO=`3n4yp|^j zCII(FF_zUtEv?_FSJRdK5}RUc;VkLvpfCF%JLkUA#01nTsia;Pp6_5uQ$8GXK-pf;j`kn0#pP4oFO}Z zcd6>5VAU9P&?|w{ys_;}MCce!ui~-qolRvkKZu%-AfX0$l~J`wdn7v1x%kEbgVgKl zN$hAm=36lc$I4Sw#IBdhG)X;?n_~eVk9SZ6fI!+OlH59+_osD}{7(Vbq2HKla`$ zs>!c=7Y(8msnUB;P*8eD2u(yl1VoTtlwPC@1PHzNCLmovKx(A-CS9aA=_H{_OOO&F z#QlC}oQu8B8RP%|zMC`7*!y>pF}Qd~!kTNY_0ICl=Mfs93Rx$Sr-DZHb(1!lshZ6- zrhCzhCzd|2=B*l^`m_|BN_RsYa>nfr6uj{duv})>@g3j|Ga+L!Y?yY&Voeo(?9rdM z_tFiItx4RB{6zLuf{%mjr8@*r6N|ciKxg8eIBS5|%M7U2?i6f5bp=i20MV|(dLTC|ru1e6^RjwDcnhwj;eX&5{KUa9-`MX$35=zqJr{wLLNt&i zQv~Su;~y!1tV;($0W)bx|OX{W@J2|3D?ykJ&)8u1Yk4SZM3+rt)2T~$@3&U{~S*L@o2 zi#0(WGb}10s)=SaCt-{m*F1+A^%Hz8ZT;4COu7w4L-DlZhyA%5z8BvtVuHvdTo;%2 zH+Ba2_NzITCxj?AN&027U{jH=oonC)9m3D#)AuriSn#*T&}|n89c)}pj#!CA=>7tO z=ZhmI`laWC%+X8}!*p=g`d7zp@~oe%xOi@qw#V`c?S!uF2^J+jd)kssOyp5}=wA>cQ$ehT6Fr0DVHPaTdfDW!&``8149 zgInIiJKNmty6_{7&6tbZ3Rj*@4D-@?%&Y#q-7=>u235!53WcRYtFTcHXz&^_;-SBfC(90+;42q zN42E<5-Up_&M!3YdPnnI)6$0sInTxPGx!5HLeGb-w%W{fz@o0J3^{rn&5{)7wfY2k zNY)j@+?FVrX+J`8N6jknJAJ@^;~|mYb^aCC|4YYCwgn zpn;gYg?6G|8ns-@$_t zc#cvGcmSEM}D(m^;JS3ppiHM5Ibj@Ov{&;cA zc~tN^%Cg)&H?eZicYx}pTruJ}xPutIEfkwC-#IA&PkTBih^mj&qhaEV75~8PA9A~Y zq}j)mccx7KxRA(0j_PkiWe!i;}Aez3aIsY?B6@8dW0traFv z!^kID?t&h1@|J`RbBO(>?x9~Jw1VgHI{2&il)w~?e*Lb4=t$- zeSOVc`B!w6LYAuLLV^E5UMBwuHe&G{KiKA-^#!Jc5uQE0G8snA(1)%(ts}VV%_XA$ z{n{UXFo2;2TEmn$3nbY(ljDw7=&?4nB0&9|;e6b|W+`DQeFUxWCpb;aL9X92!%1W9 zP$gLRQWZgXMPHF&&kfqL7<08zzIT6uPwL|-J5}7{KH19{9A=^PYq7eX$o3S9&*xv4 zxk;U@r=O4~ZtLsmdk_%A*9Y8|R0j$`#<-hUO~lCAbX$HH(%($=Rr3}9&;gozre1y{ z$An-Op$<9SH;*d@;wI7sWOu?w$3l(sX@ZSF{(@2Hk{5S%UH@J}zNIkNqh}nCstr**|*< z1i`nUK^syD5Hds()4tS&!Ms5n{a__U|FngvCV^7a!wBZv-NH(PzMBOy*eHxtFU#?P z4ba%VvFA5c(9Z&E8uPL{cQ6VRETa)3bL`Fg6Vyo6gXXd z;((AXQu$2}_JF+Tq1X`KNLh}zUMPaz6VRV|j>cyp6oN(e$Aq$ODmJ_pQ3jhNJQy=D&2g~Q|%WO z-6a_~f#;p?kVVPq4w`dmR6m@yZ!iJWG;w3SVJ||wMU=;tH$swfN*HcPVx=~GgIwxe zuOqC*Kcg@AtIJ4wf>)S-a9spQV%l9_oL5^A<211WsN*HUs~##e>P4s~a}C$b*|P+u zVao?nX8DFoB^t@1s)X?8q4e9%wT{PtG*n`r4FoKSpJ=)h#tb zprOGcjE!v}Xd@E)YQ2G@+!wGUiIWJl^zcD|@%i>VlB8NxS^jCu%cCp#jUDc=_$}eb zLXkn_9YU4(scu@FcKNQP6mWg|B{$Agl_bDEt|r$veUscd0;!?6&j#M(AEDXS?*!h4 z#wvheGE*?ws-<53Z0mU`QrWv|qtDhXzi_&+K0oC;{VhO@QjLHRUpW%5UM?8#B^%PIQf8db@3*!Kix%_i^@Htx5mEXXii7JH#n7 zfLtl2D-U7895`k!IoY5Y7Ntxzhf9=Y*(l?5?d`Q)}@=3Q_o3JQ!2kr${ zvyzGyT)QjtdaJ2K=x2?>)Mn}ux5`jv#wZ{87p|n|J1&8uP!^%kb-MSJ6hSiMaAbR) zfqMAT4+u6J$`1A(tL%U0*3TjHzUT*4VK;(|<3`;i&>p%%1jbbCQAIb(wzo$kKR!_8 zU;dC~xRsNZD6(P|9f!z_fJj`q8IF|NH;FhbHHEpqKYwuFKGiGbbry9zFK2nrar=Dh zswdLt-~to&V#;fR65_M(1Rcx#F6F@N2-~H-uz=P0^0~4Ksmx=^} zR1#57(A70*63HDcj8asdV$!nbHmiEUppEww79rV?sPU#2p;f`xxM1*3WTgNSz5o5pKVhZ=^$P`~XHydgYr zg3ras=RlTTBYxA%Tx^`LU=Gi<+oaIM{TD>jP?n}M%{6~(slok&L*a(xoEwSsIKhzk z0dYg%R5$bcF|t99``7@XzD^GOHcIPCdcM@=cd?jKU&vP4hZT|E-t2s+@0V#PhR!Pq zoLbWy&cPKqW(j7H2r+Sb+LXnWZT;dI{G*Yo$}8oN#OwX7wlBc|iniw;5!e5-L|p%~ z{Vr)turQ&Bo zb$<_H`JEJNaZ9j62qUX83A??J&t1FlZm_V#*ZnvP)ob|~Bt>29t;lw#rvymf+Jy*k zS{T*7q(fRnmH?L%hAFEo>IawYVY@HtID6-vxPYA=hQ*%6JIm9vLj7*UJ7jzoS^Spw z*>Eqe;;bwbVi9;*WQcXrZ4G#2)7-7*ytuUV%p-)2AbH?JykD%t&#Z4^rga7?u6Lkm z#u&TkvIU4z(EY>Ho$YkAFtN%@>6fwu12zT*NUF#nYRJPP)hcLG?`2nx<)+Y*pupm5 z^<5?afhZqE|6RvFfjd1}N5wnnHiVX^Unrgh91&XE+|okjJ&F_N8M`}S)j%yb{K<}4 z#ScD^ql0pdHwQw90EAjG8Xw*TNM&0u@w=;#D@Nv>gM@$7EGND5GborqBvCJ6^(Xol zSR@Yo?*icXKH+>*-%F0I97Fau>(viAZ=Y(F(GjiKrJpA{o95 z8ezJLCo028^-Zv0CFl9zbby5BboJKVSN=KPhNE|q+b>;uAa)QI(6&9?dp3~aK|K)Z zL*{U-2)-NuaOmh`V0mJ~?Q5MOo}qFpQtdU9PAcpHfOvt_AP1iG4)HyU1 zR38;5&d&O6L7ox7gG77z=PAEP+|i9YSjG>zz1C1UNfcIRf?&**Y!HY3uQ1GLd|t7| znq%P-mz67_y0FbS;ww2Otl-5ftqt2LGohF+4(LvA6J`Zk{4KjC{pROK+MX_>tRl>0 z-A70NTBU&mFgC#lpOmM^J;P`vT*HB$CXwUCIghN%z2F0wn|E5mdZayJa#7Xl-o-h~ z=QiiF^nu0$?Jad@aT{*cy@qmT;-$8@I(O&7BiVSEjTE56~EejOCVUL z|1u@=jS{iIOhHD+RevA|0}p>!*p5+%Xw-Z_S}>YuGU}aRR-1dne}neK_(K5{rF{_oRH9F5f-a zJ~8CtZ^8tt`*3~Q_6wN-{=E9j zXMj9(ZC>=a!AqJwLiug6V_RuALrj^&1*6P|X-PuJVZ_%2 z(!NdFv&1j0c!+D4skltY)LkRK-hlpcJpOO}?Ip2JHP1?DR`v*EKtQI99KP5`-!{_fD&Mp zF;99AUjfp}r*M=8vKQ^M@KWi-rFkx{=JK8c+5B08C$YZ(sMY#VK3RS2 z@qj$t>}k7$iKRA#XH+2ma7C2hd>ksF+b2(kv5SXuH=^NDUhL*-wcFRJL|$=^2hVp~ zdk59_6q)q&Yq}9|YOH}i{s%@dF5vU(;o9Afh$36lloo3bQ7W!PK2IgA4u-4$l4<@u z_|`t-JVk2eogVLz#CFob<34eMAsv0ecS2QXkHz=fWut|-lKao62lb!2xi^$=vSDKP z;ek{*of#NpY3m~RY?%KJWFh^~g!ki!twqNt%Fl_sgfT^JRJXCR1Nj2&IruxS6l?po zlf@J44G$E9(-MB}QqKHgIl?Polk_me3F2v0Ffof8E6aPoLMLlj-mmp2tZ09r)+2Wh zoA^YWs$+s@1`6#sJ9ln*dh}XJrMTg5<7uMzNpezBD&v%*s?RIoP^W%*#<}h~oNAH9 zo7~dZm3*#wCVGD;do{nnrx>eh*wsAibDe79ukZDd z%h`j3>03VOE^iAH17kCbOQrLdC25T~2Yu+rV7KqegkcNGd?lER{sIQvi+KSr1xE8e zFLx)Z6k3%VPj9#gOes!q&-=u5upvY{2mLLb~i)p~bg4G8+f|JeBX>CrIrhA`&^iP~eu;j^?1BvYNyF>y~{{ z>p^E~x?ES0HYtLq383U{VUG$?um|AL>r^-~#;DWEE5213kV*$jJcnzt48oB9o#$jK z@jC-K3@vgeF_72Pq&fCXC1dSp8bw}*C9jp$TvK9oqNs=az+0?cZy-M=eKVtr9(`0? zIl=&0uTvbawUb_3Wt5g4VSm*1-y9C!I>JY>d^16I>lC|zg4czo?1cS(FrQ23Z!1~O zo3;e!%ftJrpE;P7a1TSa^$b4k191l=h<*)T<t z?)OC-Zw!peanCWOwde(HG-Y9xZ$5Zt)w;RfkV~^l%1W?;x$DY{2mZApljA0)q#$ks z-MAjnXfIKjbjColEIP`&^Wl~J+mn1%HkMc_B5ci`S7|dEU&uRoBJt#F+BrW1@fiN- zwt~e`!E;bwQKJh)49RLixp#RsnBdQm^`%|a&U*?hi1?8HD5~}59jt+}KRO7Rn1k3} z5b7YVQF;@z-2r!8d^)Hhdc6hm;&xYL)1>#*m~PZ`)sNDcYS^!Sa%mM^U475N+Ji`o zUWq4I(;1qB*hz%3I?*r0LLOG^>7OK*%Z;`3+e8nWT}!>;5X+|kd5Rn8TA>$)mNLVE z0TiCE0Eoo1_>Z>Ka&fa2L;v{s>aJu{U}WhWo&lyj3Aqbw*t2E?yN333;ER=&p{>Ie zMbmQGNOg8qKhWlX7J2{IS;cr5LWo1FK2v`WAc33Ab~`1-%S5K0>#R9QlJCA;Su#TE zq{N5*=mER&efv`KhCAQ)sHUW?HCw$b{YR<>7lWOphhf?X_wVe)|M&0x&%gc8-~a1g z{9_Nm9dwfj>i=9nQv_q+AsK= z9vX?^m(n@C&5HBY{~RNe23QNCyBVSq55?yvk7%Uzc~f`B?Uw`-!H&Q4{oKuXV(<#9 z`$0@NF(Ai94|HY19fbL%G|!VHWpOt?r~fPwt=XT=y)*Is(Yu@7B$g@NE)+7t@kU;i zbp~wlr0Te@PO}}PNOsk4wSm*-oYUNQ){TA%qSX{-*(SUR-=N)dfA5)o1~=@4pBAu! z8KIsVP3do|&D1Pjb~+)apEGUs+l_u>kTYT1+~jENS%O(hwyE~-gR!cBz}+`b_nqS_ zbNRljMGL0ItBJD~JV*Yi(N{SzLMQ>Ei*gOIU=lB2+;6_zWVmEq>+vGZ_KsCdE%?x+ z#{5)z_ckW>Pj>ry6i|{%3V}RC$`))2_(+; z0kXlU0|j61TBi65&5M=tOWFb>mPjJ_L92HrnBFUh*i`xiqEWcIH(*j2kOMRqy7aZj zI~O7MooZm5=vt{W!tR?T)k)yXd9lve^~F^`;aYoR!tC3p{y&XnorhoRI(!r|&$ zxhY!(2<9~hapDH7h0)hJya)`6N!w4cUtlqPxtDR-Zo*pd^;sOZ>!VLwUG{`;yoUTx z3xgblwOAok5IHmnwYete{Hk|ZJM86*V0f}=MeUP1HH*+*>5Us=LlVetiY}pjpj_`z zu`lq}soH3t7vtFGyx8yK*q=5|N%f!D%7PB7a87^?>|&ZdYH056Y>V_CRTcSOQ9s^G zKg5?RmJ)V?Ds_yCYaBBeviSNe9ZAJt+Ie1CiVa^fu~>o4XmSh=+d`U6X=neu$xX@r zh8{X3E^z=8y|;+W=fpacVdKT+ZRTj~C4^JfKAzv9a6Wg5>j{VHC& zyeqS}2E|h|t4T{di~S^@gT2G;C-iSy z6SaAGvd6ICigj$zhQa_mTE@B*n8T*%&@orLncB~7yUxkO!`+0`)@9<6u5#u>9YuMf zQ7Y)9e(i`h*SO-Tw^worGi!}iDT5#ab&{c?FVdXs#ayvlcy^d+8`d4!>9VhlzRtUd zIxDevea~99%9gy<^x%Z_k8<5+C08o6kN*^Pmi1e(H>9C~c-EpXDN3J%ylxIH!HjB^(lvcR zsq4wxvzds!RU5w$r>iIjw02Y>+&nVJ!`TD1cK*jBzr zLm&a4)*Yf=wP8XBZGmWpzvtJq*ki@0K-66nU%Vce3V$Db1FAdd$2%1PXl!z~nK*R0 zE-PZK=1hChYQUVgpx^w#lr7MB70k0j__tQ`=N~1^udjVpHqM|h(a7Jp=@B8(OC}go2N1Qg_PKdWAwj>y0t}ciuplP&-u%M>x zzkL0fG3S%NNu1FLnfMDOzLd!=y|4+c!pikK9iAH&j6au!BDxqBvCl9ML?_&xVKe;S z4Onmb)9cygKU{t(C%fSq2YHPIM|Cp@06YV|j zulWChM&_VS*Q4Fn_cPkSl!22Lln}nsU;4&8J#qeqXBx^@LCqE)u8Z!G*vJ-26Z4co z7DPVd%+Y0$fztMY^602OrUnx;$u+~0>Ebza9gm~b2Y*2l#edwm*_;)8*29U5V2=R= zKcUHWV^QraL?cKr)91^ov1Ep=f~{J*^-l(cw%dogE#$etJ_|)T-)%ti917VuP^-OZ zKS3oB-6)#y01-|Sm~$b(VDN36b0aq5`h(yP#=5nDsELyc*VU8bCHI7D@AEw~i_kzB zZG=#ax$r^_OvJfjca1OGL4uvdx8>1^Yy?$9SO{17cSHz;av*r^x zrr~{aNS=5%=+SWpZ?=Bi6*bln-oGf%AqoFts_9j+w5S1T7OeYTBrqjf2djlY-V~Iv zHn=5pNdL(Y%GjSzfsXo?r=T<~kwaQdl?F4`;f~fF^A^Ev5Pow{^sVvf0kc%YWYOEM zQC$*fvw}FB=uFN>fzsUG`&HqaAKa*zxiMiGE^h8B!TWd#Y%MApc2ZJd@qm&eH_jY;X_nQDnle0 zrhRKplAm385J7EG?1r29BHQAV>_OkwnMO8*;x4IT!|M7R-WP2OVHDT7i}6_7p)S6? zYuO%e4ub1Sm@h{DoL(M0b=tgeuo`%fYFY`aT&`H*9lDah;1h~}nR8-pXShUZwVf_5vhX$A9R&qeEvEw;PY9s5zG>G+LZ)ObpKV(Z?h%jplR=~ApL@|YG1WL-i7 zLgd(GV%J2nR^}%KA!jh{FHi66Fp zc;lf8yYX|--kw4z8dUI87hwW&6M}~*oG-be%b*F?NqExrjfK0JJ~3O?a-xze@k#yQ z@3lAz%#iw2APu~)fDNb6fbouVc3aTbxIfYiWlHV0<_n?~8SZ8M=t22ND8_=F5lQu} zTDE5%PgXn0f4YzHayozbo6ViyC5}4j&CW%5<^<2zF$Tif4q1%B0G{=prkAj;H7ZAgAP zPP}FQy}N<9&lPx^VmY)!sO7^m72aL(;J8JDZ3m@}PMYm*VsZ^4_6__3fCByTaYHq~ zgSXfUB;)*^E^kwOEg#44QD-J*Id@G?-i5lraf>?;5%ks2QdR!L*4D30bK=`|np#T= zA_qUe%6=t~Mtvbp?zl5ExIY<42h(lAT2(uWsuvpVx9OL=o|{}t?jF+e$gvU=XRw8m zSPi`(r?SK3C!jp9%Q3;j57-`KMo0?ut2#i+MeTjSjqN;%3Y224AF^hg%o(sGG35bO2=3sZw zC`4yL_`9=Eg$6cs89*~_x-Ud~Ieiu8|6Bu1(!3s_c;F%r9elW~v zy-A&a;_+OXI6f8HJ1QkDU1CdYfq@UKkuC&+u&z&U!)^DVy%Nj{yk6}hV9ZVkg#^X|%Cl>hX;zDam_Ah}$d?L$ETK5mfbf1D zrDUiYoD`dh@t|Ub+G(IOqhNR60woxSI%dSzrnE7i51~@+$zpv{OuvS>F^PlVCDw1o zgL$8|F@y-B9HfA!dc@tZR~mh;+qbUTC+`yH=CZ}71&gT!k7H`ekwJukKQqj^u*J?c z0Rc8XPCjmz)^Dv^BNWN*5hmr3t+Un0?XL)&QRohVslBKea17Wp`optX{=RR1zgl7# z*(#p(zajS`9rU#%ofwnZ87!dPx8OL$Ka%UrHIAr?c0QEMh`9ICVD#~3D48|dqd(p~ zNjd5K13EGXZU*h^>%Mh5rZC9Ji)fVWwo5RJ`hgS~Ufusg~+I z6L#snd4uYjVa*EAn$hihFPDvCdiVFWzp$)vVIH&tiOD%1*2i_D`uUE!vkUSU z>Sgy=PxA3!JGZS(?<}yfA%$hEbzu%wj`C91(XfZe0(z~5?75_9&2X7;tmp)(I_a&p z=2g>tyt$T^rh7gScF~~_2B1|U{82$S4Y5OgDdR2z0z0|OBaWM?-qNr9>N$qC-{!Kt z2FC<3m0`BiilLtB=+(?fm`HKndA4TppRgbWS^257P=89Jm=WoJN%9NyJb=_o$uopQV;@{72~_-6x7}uPckN1^rztz6E{xcjw+m<`VEZTzHsd zfySlYaY>I1258zC*a2o8kS9a`SU5&eMY&-+?erM-9~7Mj*>ZU!B`aN4)AwgwJ7037 z{TJIkxo<9wkqYa6lN9w8Yo*^hy*=x4RGj^5UYV_s!8gaTWy?ctgb8BRTH`YW215u? zqqNu6=;wrAl*`yX;4Hs2O~E9DTW6hCKeM-OIs=pe|k1sOI5gYSeAJ|rgUO8B=kpg*adeb2F1g)2DeDHs=q7U7bE z+&wi6oUnR-QSHR-9t?W*L}a&ul7!fP7#T^dekF%3HUNTcaD3pSx>nn{H%(3XvRPW^ zzfC4M-cGD>HXV7U&6i*`{*_BEZ`ci7a}8V`p10oW3cvWu{=_z~D49EIOCXi#HKojr z4$BU}aCDsL1t640_$yE()kCYE)!y+|{dtFZ*p%*p7MR`O=xWaO|1Ko(q2!qUABBWw zz8ajf^IuR&FIN4%Qx{4ToIBBl-oakhBblD+@Bu`a{c#mpxCsY#KI^&cy9 z&tcQ|!!-&hi?|Nj8XN(7Ey5Xd7vhRccz{bfFUF27wIB0m#B`q)kyfm>1VeM{EtjG`Cm}G55VD-x{$bF zg>D`SLRZW4IpmAuNAWXPBp(9OCQe`zqC82*hwrQc{Ww0X_4rGL;e~O}yRIAVeQn1O z6$?bnH$TV|Og^D?Ws_YLzPDQfB6ef`exjx2amw1hP9C^+!9pC>C_AR0(SlJ@KRD#E zFG`0E$}-ahe{cT?QoT_YcAkU2E^T*5UTKHP(8-H_RKRI5>>iT$-NJQdt*G9Nyt(;% zq=p!=Ga$zYz?~YwtWbEb19Hp-xocsvDtBd+<8UD>8~o+_avUW|&+?G5K4BB~5YvsM z2BwkijTvKv-Usl!X!YlzKiLC_nc#z!rc_Gs6a5(c@&B(fTExpPQQ9 zz1+W8{Cpf~=j9n8DoC=QNa@bRF3L9%$P0Up*6t@c5_(?{F$MK8YwNr+o3ChV$b9xL za-~!>w)lR?F#cG}@i?SQ(%9aDA_!rQUGHU(7eQ}&=EQ0E?ns^(w{qtt(&bkT)&BWt zM@(l(rK8R2Xs}*y&=(XF_^8b(&*BLN=Dq(#`$scFpRbqgFOSMl|AUc{5x8+9`aBB} z!~mU9oGsE*xFfM2$7_lv*DMnsxc&=*p76|7ZfeK;1u^kp@G+mEcIxP@f8D{Kx2nZ+ zp8W=S7UUJ!kMzn#@%L|LuVJ(gX)Ccg{lEm2?UekOP&o5_uPgJvpypvn=Ru&-SK;`0 z*v}PT;Ig(s0eI?VnCKjy*j{GfL#isGQ=Z-8WrHFa>3uiTH)x|5F3;R2NnK$|z3hrYmFYYJ^SXcu1htF>&slH>weebEvdrPc~`$7m0ZS(#rKZeZbWOO@Yx zzMH(x{|2zJL`UZ^GdI<2EPA*RN%`BhxBLY;Xp=a!oh`&eWYHEcW^ivk5?OVf&Y^QZ zVdGpRk0CoZY4g>~-T>Vp+Z^78YA$3~Yq{e~tdIVTGtJLm&t@iMTz*S^L`rNTip`0^ zLVi;gOi;?9jqU`T2vQ*_4SLq7LF_C~q5PtaM#-aM;P%MfK(d>tV3G;8g;<;5#h>Q>IxOHOK-UrS!=q~2BPJkp$O^PfDTS>9 z&&y7!XTJ>M!&+${NhYfOdPdqqoGkH$J?NkSxoV=FGsqY4Wo^wtMk_>M)A-#2`Q%-L zHSa=M0|iMn_A%&sT%aIK1=HcvgujP*eLa`H8LG}tc-YM3{GCCh2NaT2=6BG=h;u?` z_9YRm?7f2VCF#$)R+rSzN^n&{h>jR7y_s-Lw{Il3>ZZjn6ab^M=(6a>T_Fh9Ml_Dc zHUs&XfBO3PW~z&&^~%PbUY+$f-PNMCAGR)jFIw`I!yGI!ccE+S@Yy zE_7|%KXBS#UvlbOvg>zd?Pt7XQ^35!QW{QQ-W{E=5q~I&IVky=q?zg$i|V=yW!Xn6 zBy`=z%1>_^=d6<&|H&k857+r@vs$}ys2j49{79E@>lfdiKUGvvy=yGYOQ8=;xt}lC zgt^i1)x?SM0Z(H~9>E_s(D1Orx18EO53%2a?ZvBD0JfSD5=dv}aPewMv$+(zQa;qA zBHlAm6nhaASwM!n2~2+p;rVb%QT;L{xl)ni0#Z+PS``PalXKnEet`&EIf;I9+)?pU z9T1>G*yPnDRO19O^s94Cg{-XAKqH1|yLV8SDI}gPB|hIER0%aDp&bc)C7w~`Gt?iM z2lW12J2by6m5j|e$TCn!KkgZJ(Gm{o(3G4A z8oAkI9QH-v+`%xopPcAzV-yoH2$M_s8_0!%Y_GwCEJ=OU`d2{VdhYO^ym@E&;gxtD zh=kK>Tlb)Xl9B{{&rb(CyQp7vh1;Vb;T5=<_z1`}#;SS(S6jOC<(p=JDRc`V_<{Mv@aD-FufkD_~HLP=mqk$Bjea_i>RzPsWEp>!A zjqicUO>1#OZgOg1)SWEk_aXi1c?5d&+~Pp?{?xovihrFhkFDx@I=D)jrtI{?3-`qd+Q3tF7` zMKvsQtZd(Hl=pqipQZ00R@D_0&$Z(CsXMva`(X>WcOH_wpdmE1Q# zrk(d0Say2PpYiH7hwO|z`i8d1JRkc^k(f^o2>bqFKT#Tan+rCB3TQWCClmnk`{BP~ zs>d5Euv-2~{toi#TX9)j$#*z>-fA%$(#W7V$v6Ck2Kfp?NP)pQyMfD~gwKtxRNvmG zls2%=FIzg(y1bD>xp;4S6>Y$LRE%aRV&;w#GwQ2jvhd@ABHJVv?CrIK2UgO@FYiH8 z`Q0mJYrj>*rv}^-W>xV9qszM<{sm1*V0`eTM+(^3*nLD)e1-Gd&sj^D`_BjKmze@F)hFf<#5B(4_}%EAa?`?N0!q z={<^k8bp0&GA4lI5_ccey9TU&sftA#&^-G6b$WSLtgHss>l5q+*0tPGii34-+ex)?_WaLz zCRxkD{bwTKZxaKLl-@v3SR8_N%nQ(-J?3C+7&!j@p?b|=`P)LxFMF1xH!3y2Om0dm zq9Z*+%r$UbfbNU&U}9r}#jq2xa2AKX+m?{al))O6VrgS)4L&pbGXkva9`BF(&r0bU zU(Lqdi2T!j8hnD8Vl@NMY5gqTnE^G1j@1G7g6W5%k{(JoITqPC@NRaUmwX-5`L&=Jz*!JU4nR(@ws?ZM?Q4vv#n*nBMh6ZlV%g zVZI^mm>`EqR zI0fU6AK)vvX1os-Ai2>dN8AJSFNDI+0N9oTL&|8`uE^)+6Y+{jiGXFd&s$xn_op=; zUFp}^@2^?)up$_jp?>4Ey(Q(P#hlTW1y2>4xJb+5_BYhhkd)p%WpBdm3cg)k^uoqa zzjkCG_gok4Iy7U{1btX+u3=O4!L{+*r_>%n-@9rz?}P>GS+fkHwfhR9jJ10WL{ew${dviJWZ9(FgDf3Q@E}}cEp*zZ$xPKz@GNafX z(P?hm;BThwTHxT;p7>4Ais>2C&e0|Vanjw=kGJS&aI$Edg?^!!ONFp%L59^c(pd2= zA7A$h;6QoYF$`J34EQGl5THg1kW$f(U2Q|vp}O2#w`vtpWM zJ!BSQaF4JKh$Ied+yKj3ZH0w{`EB&6kiX}n2&rfHEWW?k_+m+&);q#Pm>VJt$&bBg z2he{7Brsnzyg#28tKo^1rO@bei>vIEHRk>1??!58meu>McKjI8tCQ@|#f)`E!vPE& z;d?m1{LU!kwHzZcVy!9reCj*j!7IJi)%biVJ2#MMqI%JWujWEXhpG*FaA@d)A*CiF zzSio8 zNCa?8^c-RfGQVhT&>0w^XL=Tb04~ZsbIOKRhSIa;A1yX3_Y&yZn`HAU++0Z} zmC;@qPXsLqJ~lCOrK|Sdd=rum+)Tg6==A2R-!)H4YDpy(iGu%uaT*aasIFy@RHi&$A{ocEqtnp*-A{MSo8-&6+ zC}ssSY#W}=#o&L1*-(EHnCW0<_QGmD@09uZ$ z>GLo)t4IRZ2S0!0Y^ko?-iowh+EeMl{NkGpq=zX?!t6F&qqDodE?A=aF8S6M|Ipmh z2s^G0}B{KjvU zo2VhE73n*`fzh_!*2lF1rFC^$H((mR| zVHq*nLw+}$@>$VU^?TDaTy6Q#Pe#IS-hblB$TzLYtvR585W+En1ozevFB7Go`Gf#J znXRtmrqx&Pa>97*JRv7$VSv+~!{1(nv0&Y;kR%<@Z1PJ_&64Fkk0&)R`C%)e8;pM< zMN(4N8gd9X1ArU^9tAV;LUcObY?yWCxq@ICDn?m%a_dq>jwrkUmzSrtfN^7p@=Dg7 zGFU1tjLAy;UnJxvD-k!T5_dN$D0g7*b%`yMU?lTU8VQu@bbDkD+&2&gJU#`j!8}JO z2f2M!6u^xlv_ZwXn-NGO6LlU~T+~-?iPzzdHCHDR1rctkpz=M(7zw}g!VBd|V4}bf zmsOuZHr*&vR)~J_=ZL%9z6Mi0xoMS+!7(+#6Qw~n-zutq)3Q@;5Xaa{%L{~0uR;_D zHM**R<{rko&=DTnMSiE-ACUrNrh+Xj-pY zNn!g`N3GjdGQDoMV``Nex0UoTArNVWb<9Wz$nZIMQOF!k30l!A&U~ASNj|mahK(Lc zSEQfw{5x?WJVk=g(#yZNq-x*NHmE)>-ZxZk$mPJjooQTlGOwpvh5jrk3Qq!~$zSjB z6KoDZiesqa#d(k4Q2)q(A^PWrf#=Dlbt)ZOQYOc#)EoJiMP1<-0D1zC@Gc-cJH7*@ zdNpr12N9|$P5(0LXJ9jPtY@pj&gglgOpY#;im1x*-w&FBQx3#n_=i~THt?aqXPiXC ze0-ZrJvYswBju;&#S%+GYGLNcdA2ufgoAFf6Vx!d>zvadCPxLzMw4SktgAso^dG=X~>lw{Uz@cy8>me&d4c(O`P7>s9`1jbs+^O-gK>W|kFxVBxDV#s}mbu^I_VyJ%TbVhaNf zv>)HRJa`v;%NY;WK*D3XxMz=CjdzBDxt~})?XN+jssf2ra}?p(5UhAuj&)6*Fk z7?~8scyW;}6zj>}*@=hj+T40Jt;nu%CviZV=U!Y0O59*N|322~3Ic=73qS}_azO*M z*bKvBsqB&@fEk<7J=sWYSWDT8+&%G`6DyLcCqYX4x(p(RuJ66bBxNYGp*t~MZO(qV zt;+?FKyW_|xda@P25`^`MEAiC5**D4zTF^TH!ulJmC9bDu-)jNuQ%m<{DL4=v>L~k z`$mdOL1y3h^?U?UQ(3v|wqTW@b;Cy?O-!x+5R!s4SKg_A7ymast*24WEW!5x$l3 zKC3R0Bd1A#AXkVS2f425V$v3vW#|IODLRoHksYZOz1gF6!5=-bNn+w&=xfkB2|4o# z>$Y3<>G=!dD8}qWOLTH9_hxI(W`FRjZMRq-loADXD($sH+}up!aeEj-vt|H66 zyiN#r-Piozz{tlbL>?c~PDH+M z7P67L->8%m zU*5|x_IEQLz=Z@}u^M3Rm!z5i*dF#3&O2XkR;FaG2%F?O!;3l;N^!5_^tz@4#U>D7 z8k}4tv1g41x7x{r^^~TtkbJS00HzBZzAUTMUY{ZThoc8|Z4d6@PbxbsUy-@vI+Fwn zy^o{|q?8;km0{*J~_5gGA!5C5&p0s2TDbS(B@bi=} zN3*~&`vvBE+B!2?NVB)%0L)}^Q+F%dsNnr{M?8_}f%*Ug;d-~7MYz1oEW{ruQ86sN zqd@$G8$WB65{V=r{9o~(@PV&AhA zeaJ)h2B6M#CNJe{v2e7H5q23vxq#H}OE6HM6&J9ar;_)rd1^b7@`U}DZ_jN};vXb$ z6px!7knB`?*IhWW!d;el;|O?EgOPY%e*yIL1n_cd23zo{Z%17;>6>2JD zXFdWzl9B`n|07psD4{ZQ3ku{ftFK9Zd=2fgW2oAtLZL_LyW+m96 zjjnnR%X$ob(vkpM!rJQ}hO)s&?u~yzhv~3C=AGzDWs8kp9AI2Q@1-@)rc6 zKh2D7?2gCF1h5WR5W=*JCJ^mcPk$rw1V$G%N8Gk%^TTfxb5le23PO)+T!dUpJKD3h zTe6mntUWWlty0y`xMyA&S?L>YzNZxK)smu8{vYhUcU06{(FXtR**4(vb&ARhV z|IvTITDvJ~*RHBvRr`6qKkM)=*vE&IEcogu^7z0s4ez&AR4H0Jyxv=@i>6rIGr__q zd|A&k#YRO{u7L>aGH_UP_*@>^)ZR7FDyaHS{@d!9L&@TfX*~69X7#D)PcwLURLo-K z@3(QH-$323^;{lPB%Fa>*zc#wISEXH`Inh-ct4An+Ca04ZSS+ z`c)@_B|Y9d^%-deeffomZNx|PXeQlJ_=V)fmx5;nIT0^D#atYk`$?}DJdqm*TRYtH zy=TFfXZ27v?v&j0%&_xmvgwj*2ZKSuXxokK&@#MFuzweB2}3itj`+&t?l>wHY`0NC7f)rIq6j4JX~lx%c|w@u zCfnq)-(nq;?0tua!F0o702su3b4r0N;^b@cQ};ISPe1Nky654yEcdJrc?N$6qo)C2 z5`DdjcPe^5?mk@Kw|h9>`?XVtZj7CHC4oL&3pyfGi@iq@1YFU9!E3Ef@GZNO)_aTi z!owtrrp6QpY)7oFjvo?CYka%j_4rP#Erm&OBW+9PtfhD>p`*K-BsEVfhvI|Mpj({E zV(R*NWGq-l&-@1;ve2_41rfGgXEYggseGlcm-UL1W@zmfJs-oy+((d8gRU>WF=zpm zj>!Tz$;xnygaHCib&SWdePmfM{@kYo z1N~eL4LHpT$ix{(Nngn5?Y7-|0{Q3((TKJ#+j5OS4;i59+2vUh9?OGPGcKO`-beHX z0~4@PQj@OJYu`?IOhzZy^?NtY4$SUi+cR*|=R|6S|7%}WLg<+h<>3&sg+H-DZ`58s znCodGpC9lkFes7P3S9TlRApp@lo)z4a1owL7{Lb0BPfiBT_x|X#&q-Wy%@K5kolTP zTTvBgIH94Bulo{a(V=ggD9UE%yBdw?V~LufQ+~qnnJn@@PYgHSQqx9OObM?qnC)|h zQKumt(u#*EaZOz#m@^=LuUAIw+-cZgW?t@Io6}`UAGl_-Aov%E*L~?HyH@xigl}MR zPB5c!O{yXPTSCCk>RtvSxAv&^>uoduvOWp#@t~{{^OLtqZPh+`(eh?bqf`tZ7Ms!1 z8b@wcwOjDK+IlqJ0)hXOv>ASaQ2t0Dm#^YhyL$2Rx(3J46X&%6;zzHrdVIg()8Uh; z+6VZBtOBn9t>`FMNFvJ7>?oOU$6O*c@smVS;#@i#;{(MUQ3P1kj3?BLq>lXhNVxeD z%wfi;W73ddTpU{`hA9J=9SdFLh)9!yHTQZX$;lvMcT~CyAzK&&@PV&sA zn%Q2K(@(mG3+n{0m*hr$AmkMvzUM1H`NAUt&LXhKTwa!1u!2ewdb)Vhzkb_O|g+$aLX4uP2!h-k3kt)P4&9 zDsvi*Aph7?_mNxc{`xK7y2Rx&>BAtd^vkSp1_CKTvp}E`)SdN{*9NZ3UV#hnT9Z__ z;p!tjU=UoCNEtGFooBd9d}hniDc-In(Ut8R#|^nlpS3nym=r1MMeW1YiwbAQrH9Vr4<0=V(H1lc-Uoik&>%<{LXu# zIhV61x5q?571;5%Fith>-9tS8;ikhtw4~hH@GVxg50S!=-lkOhE{$VgtV zrj56*(I(D;8Iee6!Iun!WfAUKbP4OHtD8a!qsFG({lqU~#WYtNy@5NZ;R#|n7%sS6 zcHy{W!T+hZj3VTc)dqPArNQ1leP_8hg2)?>j3Ms?Jm$5;*5V%BrCtb~RMcvDU>naL4%Zf8G1W9>beNsXxF~p-CR_$9yC)RJD6=OZ5#( zELJF8(`5B;Nf~j05JB?msllgjCWQUiR+c(5^tziSGFywacb%1dJS;0@xGS5IG^Ro4 z&)#o~8F~%+hL`PRL=VIT2LsIv?OdyTg_j)cp99PZMNja8B#X33iqYIC(pF>ZwS&&x3i%=*2lm=oIS0tT#V(;g-DCmL`qlTtAUikT84KvGe$mU!b4$g**xE z(gLKj7rvRa9Q#ARt6ag(nklbw;NHtZmcRf7MmO;&UnkFq)x#(knLHV} zjSy<{tn16Y#J5c9_lN1Yk_GxrZl%!n5dV*BwUZ^dd4o*uX%aa>+}S_t+0&(UJL>;lUz+!@IMt{wNGK$Y+oLd9=^rVryu4 z=juA)KL>JAoB%cR((!)^S(JxVf|rp2&rlhJs_46E=tv~ zhoQ4QgtYIrzvNCw)}b|V&XK@sA^yRYxq^@oR}Dd6-j;k*BkJ0~IRKlH(eieboZP4K_t%Vi4@_4OS+T~4Rt z1_qAXeD}}^B!8Ft>N>{k)O9U&Ah7m`KjOo6qIxgq6QJ5a@Zu<) z+@^WYRT1~e_nd*zBlVkmkQi@k(cv$-)iGb6S(_kL;GcZ=kmvb?ZcBLr5V26J4U>~5 ze+cp>uw}j5<;D&n?f4VWtQcK?X&8-o-1&JeC+Z$ja}w={JkQ(zEc#G~=oiTMeCCq< z>cYbRW+G|mw-aG#{9J%|uU4oXzm2>zFl%iyQCjp|sA}uS9U3uhKl`jK^tE50KEx-k z=^UgMJX_})AFNgM&gK3eTE~J7CHZryT-ZV=K>gv!UZPc*N(NS$~zrG>>Rd8Vp0v~?*!+?E}ac$ zWQ~6Omt|iO`|7fFGOelsc-o3SJ2hI$+U!ouJ4If|AN=`p|Fr$9BGP5IM*qfwxWV{n za+QoM2BFW<&BysFTlWXA?$`qP9ud5LNB0SBhxg&@jzw2zJ9UZOtwvFTq= ziw_xu08OUID1$sJxCUv>eHim~0ICDb7;%K0f?=&f>6YuGIk2P&@0&b1qx{YA>j`_)c{UmX(?(2u-~~LN7t&m=<}oM zpD)3G6Z-0^An2*ipQj}R8w?xd4s!ZoZ9cqyPpA(~j$%)I^cHcb3_Jkvk#}QANg}%{ zVU1ShZ|o;8Yz5p|bX2{znan@s|NaYVlltm@-OX+d1m@1zG&%hxtfO0F%!8w+Oj;px{fBh6@n&*bUOUx(*!Cq?|y-z$47y~qD62W5|gTf zv$j4ukk$A6FDI<9{1pI?-Wg$bqn-YES>>!IO!Yj)Ns$j2in-qgL!RZoi$tX=ilVyn zud2ftdMfXK2gR8sE+u6hOy{xlJZs1#HR>NiU-fM^P|PasQD z?vQ6;e-rxZs#sOS0Y2cQIDW7M&U>t~loEF%>P>ITZ@lDH0o|deV!tt-ihp>?zu1$j zR)t9C(wp5L6<8^laV?6j4~3fj?|8}gSGW14R{5WEL`bDyAemjDkc2Y|LCmK9#!de9 zpzNulxR9#cfs|{D>Gjqu-}+a;%^+~)m^iP zo?b`l!85drkS7J}v`#sV3|VPvzju^Z*V#aU0t!+Cfb?zOZqdaE)fNBgDF1d? zpudS(-0cKyWStibYm2GMff)Bg9?ro@?btX zviZHIyt>ms#?lT1zxEZ8OUhyr)E$LiAefEyZ(QYHk4xomLRQ{yva_rD5R>s?`De(I z{fE?7{Tpn%-2C?;>&f4xzPhZBz1;jaA?x{XT;){>#btbGe`7z||8$jCH>`K`#-NGS5gQ}dXGu(|5*sZr1w`UA(-_3FV~VQ zdAcViy~kAVG1Yra^`2f>22;KNcVi7xz5jPV6H~p%RPTS==KO0(5>vhZ&n7gcdVjU1 zi>cnf>HX_b!Bp=t!#RH)D!N+r#|-CShI25(Ihf%b%y7(Nug>)O}o{Df49c7`FoyZTSdibCiVEEus)B)7?Ov&&BTw@Zm!o=o_PtlrGH zqhIACexZpkL@doIkK>Gwb4$8Ubh8ko6I95O38LG^8Pj^Ks;;kVFw>yetnG&{X47RFjqysn~MepT{yX%JybfpQbTBqZ`gJ&4G*wpNmfSnzAuu) zxAxpt4CH$0>Cp>gb&s>mI7^S>k*`H)jnQsv;5+`p1Hd;D&3N*4Nzo`#%0Ol2Y;O}E z-R|W4R7ijYcC}=qJuOXBu<<107|&3)x>w5P;m0%E+X~yOT@ALj1ZatqWG6^>oo;!G zyw+H+38|31J~q})XUo=`RXr8n0tiaHt!q(0T<=%fQbZ$%|3+pbg!`)kn4Kv7g62f0 z6y=cZ-}TTiCEMD2qONYei>I}(6s_$ye6}Lq2zD-?%a?zPOGe^Fg^d;?@p?7AJ@(627wDn|bw@k2 zlk&A4dN)AjqO-X?nBiv2t5aQvXcXOA>0QOPrfBV+k}sQID#SFk9^YWx8(z1qMkblq z!97k*$0axl`iou4cHd=_eP3@0X+M4@8@5n9^b2IkchfTw9QBYgJQt46PkkceDEncu zj8QCP-2dpV{~4Y4Xq6IEfuWn#cwwH^@rX_QrSi>HnfCAv2e&!9^;JBR(p_?96L zB9cL$$RANr%>pBbCk9-n`iQ*u58W%JDs$g%Z$!Hk*xOCx@IOL+_P=pFj4(~@N7RSa zw(^};(BGSIrIRJXZ&7%?LpL(RL5Cbc-VU`7Y+NG)(X?j5hSPRrZcmWP3=?$UMOwr7DTl1d#Xr}*y(Pf4+e9f zj85-1Nfp>WfJjx0iA?nU`wh8bl-}(vvVS{plOOwPi_6vE2UPcRa5erFDik#{kMP?r9kJa!{n^}$S9(>-Mf(H#zd z4cJt&&@dT_zY$;^T(`8c7)#|!(Rtn-J9$x0S7k3AdIMHx%XboTY#I`@cuXo+j_Zp-)QjLK0ysd=2OLrGN+>uLVv`rZB|WFL*+PQ zYwf#%OneIMCD6XP7#?15U*QP7!Zq2vdEeLkpU+>s#G4gG+B&5kgIGax@dy7i#CVqgqDi-bOVLxC~R3oXDA5Xt40H1dgUD z)%AtYI3k&n`i|4uW3nj9h1|z15Wb!F)S_54;V=#y)5A~K8D2=2;VF-o*F@P&X^oZX z-kj4(T%``c$tjvAk)W6JE|MXt6IFY2M-{5|5JKhq1Q8QsRs*51W-i=RT$x!-4e9K?` zuv$6`vs=x2n{^9i3xMIh0%!`s_LWBzMqGQbGDp0Q&fz33i=_oH5@;OKO-KgeH#Kt` z$2d7hzz&;AfP4}1@MxEP^VQE*F1-Z3Z@Ur-2+H0}o~aVIQXhjvzsDU|wk~8&b1kBF z9Ys-E=|`Ehqbe7VQ2Gs{#F=QGxEEzz-0t6Ub4?k1?@6E0UQDHo@7sJgt~Y;Y`(WNO zRV?`-S*k*hbzPYHiVDre`S{;30B;_}Wcy8uv>LkESJD$mftVUq>{-m)& zvrnOy%--Qo@>PANpuL9G&y*SIIV4ub3*|j!s3;g51^}O7mdgN9$)Y5j_3bp$!7zSt zaJsQBktOv$tO)D#T-IxgLS#D(&4<`n7oq2z%xk}YjVZl*aRmI?XQPGp!T&uraDb?de5;|o=l25VkWu8vmF56*@lPgk(f}l|L57(d^ zo7A{XLt1CA-GeiaLH+Cna(4&VqxloPe`M4YA^#)7|2~)bnsuo253(C92}eo@5ixJ`JIECByqKx;um+>62hZb zh;QsO0&e`RG5~j#3qFKAd;8U@oUk~m|D2loP(IB@#S(b^CX#hPvi0)24Q@?ieM186 zW4cFiB=DngO}B+^=Y1#+KA|rkZI;XPJ6syg;@V}5nF?m?%%F8|5446_xeoB2m-pgw z0&NjksZ^Uj={#Wb<1pMTg1-;NNyS|KgRovu$|aE2b9gE>u?sEf0REn!U8?}DO4!SZ zDwy}}oM!QM`yiv(Z1qt-KV)Y0J+1vN|784+36lnyH`TdNYW!Un&02xY&Z$8+j{$qG zNK1IZ^tsCnj3w7%zcv&{;Qi_V^hXRlOxLi(hGU&?Z2<;J9wAzf;DTvKg4UBJ9kPLaw^E$sa z(~~9X%r+w?atp;_$INHzX8g5?pD{p1jf5#TXj0MkX1i#i3&T7f3yJQd8RZ*$s9>J2 z!|BU%^nxdw86I|I9E9JRg#?157GxhzG{1az!C}}hI_n4f$`d44plhG6KdpOSR(5XJ z;}nS|!#$yIH%9mR`W5sad0jMD$85aB;aBmFolTmZ$G#`{QzK1#a43$a#@u&=(J^<8 znVh`BmQI(iCMsFtDBbK;GHGe)o22WLV);j2SbcXDN>0_HHJXBh^<>=s5En@ycuf2> zmzQ6Aw9+eMz@9Z?h(Gmu=yNnrc+`|r)@Z+Q*keS{u&8gB$tADq}!Xy`& z?y;HItex~U?2B`s84KxsAGp;I!;5G26zf8<8#;o)U%t!C%hHij&AhLOJ@`CC{7{X> zR8L0_N3rOhKm|^CN9Wd*u;Ibd-qbzGxg=`Mlk2q>K663ubf^{|sAf`f`W@+<*-HEj z2piN{$F_d~l6rs5Gz~4Y{tHyLb^h`};()lg`~_2#2R|Kzpk{ZJ(G}yAQ9s6&Y!o1TT3RZ6s>-Q#w056_nlA`9S>LeA63^YpCcDtA#ka?=QB$YtzWtTb*BnbKKi2h+tUVvOnHJPmmLS7uiEwQ~#nYyE zQ!bEvBq6V#i^c)>0Z)J+BPjja4Y5+4%+uxENm-Go_m(03Spd?&*WzYKwSMxMy}r5L zI89KgQB9ObgoT36OWqAC?AcG>gg~T@4^vY&XZ3WRx`6Phsl*DchYp$T<7Q%>R}Ny| z1u)02Pt5BE*T{|!RQK!e`x2tv(!b5O{*-nc+~mKRB-U$lxskEZ)d}a->Q_Ar*sPvi zv~p16Sn4+oZb)BSjAx}VTvFD_oF5Q!=DRyjlsn-gu91;zZDgiewrMg2FV!C1>r;Or zZ&nXNpHz<3afZYs?zq{|awPaap0~uy!*VJoicB14Eve!vU}a_Aq@Q?J)|SCSG0Zb| zBmClRtRhX`b1N?C(${uDtn=@vwe6WCOl+lU?e|&RQ+Vy%n;u4@I_#v5u{o3+XgxZ~ zGYBoI-br8`YMRzmG`yetER?TLD~MGaB_PU^J;@xhp~H-~2_zXi=c_gQJ-arH&zYiW zV?TZHop*{pelwF`X-x(n`q8J}4_fyZL%%$-vlLFRnr&%brDl5W3?|@#tTRB4jW(^h z!E2L8=tgy{3O&8jq}j5CPC>huG1NkHg*>Aysk3T*^W?AX)ip`)wT`SpuMt-A_gmrw zFBZ?w`X#a)vCzA?MY`1ZSrO-!+L^z;&6}It-$BZZeKSjc!sqI4PNW>#6DXOPdd|pt z>KC02S}v3v?OtOLwu~ied<6Qbh658pz5VhFWH9{WlW@sj&D6X}$XUq#K7jb$%Ks6l z_+v`#m{!Ao=~fH3o)V$nq$f^cSNY@iCu)-8__iz*u}$Y$Ui0f~qeUZ+N`U*xzfJ*R z`m29kLjJsn{Plx<@4x*5o8{!s3q%g^^FJuLzw`?B0QvECh3|jzHOMOcjkw|+hQ;B3 zABzJ<*BD)6Yye{e|3}$?H@X@wDhHQkh@dA&@K4!2w-xRwpGGBxJd}5)t5R(+i4I6d z7)mSU*9+w7lB+xV0F^bv&liG_FP++usZtpFtq`k+ajE*u*!%q|08Hu3AqGs@@}%_p z!^5uPQt)%72Lq~ew1}LDm_%g(#e~CQ@)aRr3r=!YH3Buw_KZ#_*G^0@1cYK+1*RBJ z7nu-RbBPB(t^EhrRW<@iGjbxGoy+`_v-zDzZr%$U`?d#c7@OOMQ~K=0741l;%V`8z=_ zuxF&N-JEU}&|Cb}hyUdI)?&JB@ECvuD-TBrF2|7Q&%B^akKJPi&C@1cfnX4KCpi|4e8Sn!lK|Ofq!h?5? zO069ks4lYk1hI~lQ2!9W?;>kST@Vr^o+^B!Jv66F{NCB=9(nd%*4>$m@Xsw7}D~v;Sk|JK1nt<>ph{M?Y?V| z^0tI-mX+Fbm*-bCM|^Aul7(u|8|QF*#+$!otz9@IFf$K@wr0=DKvtEcdi@q(p7D2I zC=*XQ5`(dgUU=rLuOii`gR32dn zFim=0+}8uzo1OHxm6-IJ!@JE>BE#EEnX!*<56y~s{IO>0sq-MOTIzLn`S#Cym8*0* zLW3mFo5uNQNh|bZ4Jsa{69;%t4u`kVBDXrdy_b-0yJ$k9if^^~4ai`;fV;C(Qy+AeDEil|GQii?IpyedFcWWqb=dLUAG=VvS}muy0h?X z&XVeW2+Zza`#Q^i3asZW=6KbeKrOmFmFa6ddK@k+NwL)R3q)8ObEBnG=Kf-+Mf2+q z1_9NU)G&rcvUwUU!BBxaMSE*!I}Tre^mA1;BNY*xFj+gz@1J$M-9P2cMB-GjQ?thU z_5()o0)7_YYrfhlrFcl}>3*SB2UX$Ns8{MQ4{*P9ltx+Wq+Qs!w+qx44XGNGrNCoW zl`DDXy&=IT_(Zw+)b+TLT+zjejHHs+t?QQX{aF^0rG}RmRJ-A6;mL9V+aNJKQS={y z<6BVfo_(NqBXBV!0NpM};jPi}bw;e($#o^2HmSEK^5(@@4LJ%t3{atFCLbE*6;MMO zbVB17E$W(~E7uaEx&jvP@g$~Z+6nx*06;mimfLF_!gE9q#&=FXn^MSsZ}xTGa^G|~ zAWlBipjvv8MIN4Tsu=CfaJREhk!tP+}4-RucjL04aXTrJ*UuxZrOdG%w%?RKZ zMScsGcxQz}Ew*gA>olYZ))TewMi)@s<;IsOko6UA@b^hzphhMY@$(o!V0?HQwbC9{ zr(4!q_}RoP@hC?{+(erF5%pOf-AEgch^)1{1z*oE&^aGH_b*Vz`}U!RPp5~Gvy@$2 z`4cGXmErK)HmR-q%SjgxBy&Mqo1bZywZcc^$M09G<(7^;wpG+QEMKmwjr=0|NOR8ok zPl*|{8t4c|9|Ulk=Zh9^8c=t@6XyN44SvkI<;5t%kAH0Is`P^I?7ZMkt)a=AlYJ1R zlJGi)in(Ea&*`MZA$U<7VHDkl=h?s2qa}N)_%c(}{;LB0vN5;%4bZu#RJ+J%%e&5B zpc<*7mGW>y<|(Z%g#J$I#_(+3nBm%W%AJIFmJ*K6Er`+jg3H1#tJ$(RTlmkR(cT|; zp;V>iIQ|Oe#zWI@iIt_%^qJ=$l|1m5Kh2aW*4x?F)IZsRF2O}m2_yi->$E0-b|%MT ztZ_-Aj_yIorj>X}L8i;H8-LW>Emd~e4G{}QT3)Y`YZmsbiK#5x ztns}~4U6y>)J8oWJzm;-+syh#25(kk`MFu9p3VAwmfO)OrR~(dkO^No#NDn%fsvZ0 zBjrLGuG;I37tfR#4!L|ILYNt2{IhGfO1!*$#Lva`5Ks0;GqW*)O{J1>#6ALl6BjH_L6&R1A5|X3T zlfaI7U(m+E5mMtnQQxls60S zv@*G)c)?aa1*QknJX zs@lf?s0epa^y3wLUt!z#mB1yF`9f;s3tNG=b%Fa#g3X`8_aLkR(nlAqw$t>sc1EYK5KZ71ylB$9itWdz zb+^v#E5dH@f1Y*hxVRvI$Kay8fG-m1kz#JBgS(||>yB?i_B=OkmsWnJ(!{SRBfc>! z7&z9}mUE$?r;jAjhev0?zpISaTt1%E({rtAyv@@PM^H_E8??nHVTZ0+V~LAqCNj)3 zG^a1FM~O}Q5BLiqq*@_GRy1v;tdnW^+K&_6_rh@)AAG|C-RS^`n>tZ?h$pZ%)&@N~ zk8Z(*&*na-$;?(cM!YY%$=ft&15}K39l97IbPKvjC>2VrCmk1I689EYXDvACoT+Yg zeZ(Pl^g#^1Mkyil08*iFny0s{mxybINsM@=W-Z(6;^-C7nz-8GvFY(7EXPHgEgla| z!yLPx=|>dUxqdr61V)o@wU`&9zbx`04D-qqr7BH@JLe2)tO!j^B9cJ7#5eiZJ<6Du z9iS*_1m$VKn7xE;@q?m!38qfMNg1@Zm2gK*v`!f5TN8Lg@_71?*^c(@qQX21~N!uF|j?FU<=5@$k)a~37XTc#ns`WW)-_b_n zj2|BJ&FN{v-Qx-suLnCpJY0C*JiQSa3P4o5x_$=v*pVmk?aNt`B|WT5g2NPR5JX=M z^;6?AwCnKhhDVA=#nuYp{(oRhLxXen_xlvzE8@Q7FwrHbKjMacI(sa7WBWy ze)lc9p-0L*KmX=U^+c7KSwwBkQsbPjCh}seg-GgbCz;cKGj^iHv~sXIO_FR{7xgY);J(7n_d#D6LSz*d=Fhmp zod_YS*(Z4!zhiGP@hZbS^#ysLCKD^07#<5S*9}Z=c1dR;6(uN3fr}gycr~Reb?nOp z1m))yTjEo_fl8iBH)&dv+*Y4*%p_1NAg6J6_n7msMrP&#WYX#gw!IC6w(XtLjxk>u zsVtiZxIb2)o)7r2)6IT(mB-pn*rNs0%EP3D;N>W06YvV_#O8$m*y-2Hw6C5^19R0| zu%xIN!&cF9&Z4x&g`gZx)%f_j_H2TmTBiWQd>qLt+ocb1?aJONPvLHmLlKLao zHN3zLxj!ISM%qXkhhX4V*221~r^L2uo>_3O$RVm)pa_@r5vXHJe7m5v@2mMm+0!)p z1&NU#GGwYRyfIwUe`{I%A5}fW$d0jJj16FH0Am9f8^G8A#s)ApfU$x9J8b|Dc!$&V z9Hk9Ig}esC3Bd3I*o6{GO9A^qPJuigyf)q#tu4G(qv0a8B{IGZVY-MhO*&0SmNFkG zUOxCE(oT_;`DBnATyxf=UEOx{JWWz$h8?yp=p7mFTSB7Ze>F(~l*c*!h>A&&g6|CkZQO;TY= zNolc;s^&i=$%^}Dq4KLT&cd>o(Tr%ZfGo5hc9veLvQ7b z+0mBsQUy=WDdz#ckD6bg9)(*t&7&)fCyMtKP+#)pey3N}uNPq$wPMtYu~v)|!1z{- zZ^eWxOeTOyurLW0CU5im3@;N-h5?QDI6gK#>en!NL>)6mAu31G%AFyj}PsTRzz5M~DJfAb8M2A%2Y z8)Qlu()&VY+>MK^rZsSXQ=?jjm6n{5*6H(iLp>SV;f6`lAdeSDj;b=`Y>!lB{sboe z*9U7GjE}zi8Nv1vft%M`dM{I`l-^ENhl$iHiu%Q^^+@dIQm+#~+>3iU!-dH2y}Ev% zLNm9zDDU^;cW{qB#gl9lE=Djs9cj1B3VD!uv-X>v8-xN0UC3)i;BI6O5H*n`5}NM~%1_r$<(O0gm&zqvVuF_d-p;4Aq{ zKZR=nl6+lDM923oQ-NooPkKZszx5?46l^={HD%8$p=8cD=5xfBV@@0lwG7WLF^S;tk&~D|&GrSTIlF)L+&LPt176bTJUOn}V--)}wEMNo@U@ni`sd zX8oRxm_7Xkl7C+l6G_R)S-5^X^TxKtvTwDF-yMVq`gT@0xcXiU!bb_7pY*|YvZ?;m zB8MXDRy2O^sD~XLWFv)o{kpM2hw#!iS_1BOxL37A?rRBO>#V1V3N87jqhoz~(}8RZ zcQ);)nGw%ItnXYJn^C=i;qFw9&4czETBn|4_OAPKst)0@>u;Maw0^wtNtBGSfbLJX~ko^Ok0K#V>ZFUW7al^v%z6z83zSb8M z+i0N%czu{ql$sIgWkQ-t=RGNxGwPuz`Lj1t^`#}UL+l;DKw1pRUyg`Z zYbBKlwmD5*Q`<0c}RzDEjuQgCiCnZy_UE=lh`*!bl$YF9d~*tCp$bt z+5?2YXT8yakTO5Wnx3p*Q;MY~N!v`&TyctOaN80d(3(#5=+!&_1v1Sr>V@{7n-C{CV1-G`xe4?q6y%jS}g(jQ0N&d*KKx@9xElQ@uGQ*w{LVAT_~t-S0`Pmgr?D6%)U$_J(A zXlM(4+N1=260|S@pcAa}H7ajV592_Jy*DI?mWg~;DT<1;t*(DlESOd(QaVi`AmJbg z?Zp}}hmr3Z)%aZ&gzo!tz>Q>6bcZ`nIaqg;aq8pCHeX3PDnjPe4YKyy5%jxzHjCs^ z6!32T9eUcvCdKX7&;gC=mYbFm{09!Iq1>w(Are&3j4aO|hPQVf+ATZRPZDs)`JThq zQ=F#za`FXogHt`QSNgg3#l;zjJe${IKC4hDttin?pq}I!eSuh#SDlkexOWG=2qLDA z#{beQwyY(xatQUmG1(@b6{3b>g~xk7+eIt!QtI)amR>-)OSXb^0=BUUx15+09Hm}l zH#vl7(gt^eDI{c8(qt{_#!m1*1T+qKnGAi++_D!u)E|8DUlyBPySiR4qR*X+rpVG{ znxI^(eQi$WIDQ$x$I1>Ai0D-ojGoCZnZXsodoU<&x*?e#ei{^}VVnVq6o%lpW4IR^W?OhggO5K`= zB7a;a&P6y?TMmqsN!sK!m7)u1YOHB8i>W#~$Z-2zHQ#GJIHP(9zUUw#l53>(lF4aB)Hx z)TjQAANt8gN>Myt81FOOKO4kyA%%|CLaA2Uj@C%Mo?>Oa^7$4+z7f)4Yn9`fP_0UxU8ZA<{mE-N19poMb`OJn$>_tSt^!{ zWLYfEyl52@)ye!MCv+8%f z0khqUu1{RZHv<}@)aOczWjGq*CW26ba_X9!Kg`E0xa{MS%?R@3SbTntIB@FE=@-w= z70E{s76k(~Y6n24!kC2OIr%gh30R`CQ*xY+I6fCYxO1*0pZQ#+aopbRi=ofU`ZJ>) z^{!J}NQ>-cmdKP4!OxUq%^)vL@7Ls(}pxbu| z09|%{+7?IDtWVyjK_{4*AJC`_ooooqdY-7Ww-zMd$N9pPS(wU-ag=BC0pbf61-9c_ zIYbxuSI9rQRt}rs_CJji=a;>4pGay~&qoa1ml*f35Gw`tb>92*1FuHv1Y?tYZW=*9 zRoi09X@QD0nY*nM(Qs{4WqEC`ZO{%x=<@yOc83 zRR5FryU~&_4lI-E!aebi5M>)?R72u4*EWHd?2kI3lYvJ4kH8*eXD*M*%tv&c^z|gSYacjyJ)gri-8>$$st>&(15f2=43D%dS6>WhOp&pc zg)iwTN7<1%%Z5zkQ0+{Qf!6j9qr*165FY- zKmNdLsj9gTRq#GMRp%GuqKU?vnl1f@C)*IWwe^YmH08r$8jz_2E|uo=Qg87Zn&isT zrvbzXIFgJImm-(04qK1hn6m4hT8PUVjt<>@!%6riYA|!P>VV*G0e|;Mng5y_ z*)(0)t;-t(VXHrF+?Ys(ld$5<16M3>_Q2;Nim4a(Bo5PIts)#CiD zCtzOm`_g2f{$O?uZ=%>9W21aLn+5yl>sSQ~iVl|G8PZWU4UnMdd0LF&I6yO?xn!Q8 z?!Q;~dX3J8puKo)zo@<-vEdWhwdu^srF|a8rFt{-pO&KgFElPW6!n!q2|VWpp^EHZ zDM?K~GS$kIPIRXxki=`n@_YW1OKox?Nm(zvRMX2KS|lAMUf`7STnV!kxRb8p$+PQAA7s;bM_V_xutZDuV|$5|oP4C|5LL+D7;tuJ{` zgkG?`K9B}-I|=nN*3e!jo5YGQHAMT2UreXqfH}O}t7|vb)M41a+hz`Wl*ISQg zAI~X_WsZ#YQ9q!*H!=!gqFNf9OP->A70{R^V^pE-4|8J~!Mi~giI&{iMi^@AU$29T zM0jw?HvDN|f0sqUV_oVUA>wgdwb()++7mFH5gFYvRh9`RxflH|v9fYc9`)B~6hD=n z$dP^VvhBVcxy1tGwabkVeOYPM==4myyla0N_g~#>iWy04@7>!HjQ}RzhZmIWFN6La z7Rz?;b2~|k#8xzKc@w9Q3oLBOdif97bvMjZZ|qFb*WiAI#%r^LnDT;%o0Brf0l=kS zpgjDxVZ7(BXMUhHK6-g<^t|>Tcs-YmN0(9*HxxK1S4hsoH z>87RnO^J&`kSf+(OpDUx})4vt+2jmk=wsO1N;GUqg91CJIye)-$;WP?o2vEPSDi#LA1dj2(wn4!4OeFN@tSgWn#S8J4Qo)patF1uUdG%Q3Oq!se zvqpcA&9Wd|j51KQo66yH$MsxtuzUNgm@B|-O= zO#+q4HV|V0pU7RhO7p&=pL_-zM{D~l5zivx^?-|UrIf!8vp&hk54>uj_-q!p1D+L` zzMFpOR+KjnDT(O|+lYwXZ>g^oe&&-U`RGF8_VN~gncyS+ASegIPVj@9h5nD?@rxJy z?={!&3;jsW8zW`EA!>Yo068H}{zlKBWrRBr#0*wHf58Rh0`DD&PHMI%N90(n40QRU zGor9Q)Q{}{M}P)Z{J#O(e_ci@H7TyMQq(W{PJri-ja%YEO?mC0E%C-XELHc=wf3!_ zFDM19iV*_458v?D@OQUt4N&!cSAlLWuI}jxr*qxO`1H~w>?4qWK7f9!4WzLxzNf(# zTp7N_lwu!2pW@`i#C7MQW?nFO{u?ESs@7iM52~(LY)N3R-j@XbPkVPA6j#$O2z<~a zXmFP|Xo3ZI2?Pu79vp%U1RY!h3B%wTLV(~N2(E$P?hs&bf(3`*kUjbCy;a}7->toM zcmLViJ%5~{ikf0(x_|xj)7^*jn7qJYMPM9 z`|3ez!s3v^60H}R=dEf9`1gAPmQrt3ApLIb&cxo)d)AK2g_@FvpLLlVPe$c9%GNeZ z?Lu|;|0ROs^gr2~>v0H(@1Xo5@&Hw+ccaWi#o7L^B=>z1F;Y&%2`&i?TowMo<7iFclE`JuHkEn`4xBh@TQV`p)UE1xk$}zvyjdBWXgj&FUR<=(cGaaR#^zRdo3cp^N_wX$|}+FV(kRH)}~Ud~^9G zs(u?DQX{th_Ia&m7$bC$Sd!jthJ>US?$6If$Q04B`#K%18%WF4vum>Sj&mN`*>49o ztW$8D7SGrx8&<~j|LsGBYKbqjbXAqsj`h(0pk(SxDf!|C0s|&@A z6aLln(FfJ=y+;b^m4C8V^{iK{C7$==#l}R~NF!?FMF_TaDdz;nvvf2ztqnd<$9Aq= z0YfiQx2ngH^MDiQiDf8OWpI$1sy*YY&t+vk6Ds^S|@ZC>JVExKLx0Wy&>!(*d9{=^{{t5`9I1_Mmq=3!)utgW*4BC*W^C_paNm`n4q0fQt zO*)A}rplual326L^c67Xo{x4t>TRR>neNX@p$ngA05)P*_35j_f>_*mPBNX9HRtBP zY!A4Q6pye~b|1xN`2x1wb)#-u=Y`4*kE0KyT($9a!j67Y-WBkviWZkf&W*N<73h5?#Gx#kTxGgIS}(w(QoW@w|6G3Z1;BOE9(q9nAcErqCo?o0gFy%4)N zsR(F5Y4H#(#6p-F2=1R`jlVqib@CnY}?~mS(0Y z$7R?>WqZ$g%5pi_<3dBeKDl1I0ai>v61nWjt75YM1g)~dd4{Z_JAu^3h+79n*R{s%W zDhYzbJu@&N8UutXUOL43z~hwjQC^N+3)syu(h>Z^r}awSxL-YjrQcV0=_(SQ49%4* zE=Xp;>!9l_`T3Gd76(_2@aOsB9`RdJPblN~ZHH!d;MLDhQ|TjD{V3$m&&+=}ix zO!3`6ze^k1kHDFML9L68jNW$=mUUj@g)){r7Qd%1OmYl$_eqKNlP~cT9lIg$^`_ct zd>*f43klPS`}jUJ8I2{`si1{9=ocMaLf`_He}g|RLEy(T>C7Lgz!jZSXn#(?_sIKc z$17dPFY|fGBSfuYd4-7|YQmZ4+ZDGP+m9q3YI}06cWq59p5Izu4%PRF!}JDDHOxf( zB^3@Gmxw>eO^TT^)rDgWRz`U{T6uD_I&-Sg`*pZr_h>X_Bpsx{B&&YR?A}@)R^Qk( z=$CnD6=VN~>|%cze9^c&TNQlrYsCK26;6p(dpPp0G=TcXtMcgHTYg1;6<(#uDw56k z(VD5+7nR?UtZ&w1t&!wTL(?(G*e#Ad8*K5p>v$?d=5vEGt zB){Fir;Lx19f@)p6DH3ef|G}Hz5JG;XThhgI4U-o$S~YccAwv2y7~0&wA<34t_bq$r^(3=_C;m#_ z{|$NNPu7`%bA*1!K31w=SB{%A*AzjJlSD#C9cJ-Nj0k?*&sssJWKVE6m_p0ldepVq zDIRdwy}jNDKzzw&u$D07R~a(|F_)p0FcU&^AsO~VsXgq>q~KqAcU9a`uq8nm;;)M> zY`b_pe89}l4inZvK3m_{`SlqGXpf>*lYr|k37}lBd{OJq7U>`R)|){F5p8EQ_bN!X z=pX^~TXcALEXXCV{Krf3lhw2C0|miKeD=FhO=$5F%G7S5-46X*1!m%DN_3$TSQj6c zmk7NCS7kTqpwRL;4>;~RRE)K6m(9mCqV)mPaxL*^X#!ou%51LS zY##84W6{jp%!C8{ueGhd*-1fH^DFWQKhagLh)mQ|6*_f6vMc8IMb8Rl)*HP!rw6sI z6ETM;`s1G@)r{;etvE;NEfHpRUG=qAwWh6z@lA6zaMlU9(3|ARSQR26m#zyj!!I8m zIW;Uhlh1kObfi3XE;4i`P&g_La+Z_3)PESD%b(=y?NYb{6A7Dto3W~!CI`W(B2;YK z?#pho_v-1?@@iVetXYj%JvP;BNj~UbXd1xld^6&Qis@fM2!9;(??E$*NkYQ_G&!CG!m=#_bCnN z=(sgeHuG#Xq)JWUN(QHswHcP!-JK;+DFAwR@IK zc^%c}sUr0h?fJ6oo<49T;tW?VO)@8cpD9CDY)W9{*gkVR%d3ZB!Pt%N3tvq=pzh=C zUC>XKj1qvOw(Cvr{FTjzes@7w%zeWc5}2f(9h`FDl$|z=j`(qRnjT0BDXgK$$+*pp zsCx{tCEwF|m8GaZns&@Txm^G5;65Cm{A&Em_M(Hb)4G+ggt{jF1pi0ivmuE(lVPt^ zC+Mlj5|HDDD%85?PxeBN_FjslmB^x)0ecV>Wd;2?D&9=Sw;v<_lE`(x*$J!Z3%PWn z;s{YZA2DQX$}sW>PQ5>qUDzE^gMq3r7IQ6voms=tQLoit@%`Dz^m_+40^h_2ixNqu zpkX|>Tl*+tj40N{{<-N@#`NA}W;7_hKbruY6&u4|Es#jfff0JH;O!;;8s!$ldQ3`x z%%PXeFxqNBh8(Nev-^p@b>&-)Yo(WBxe16*mu^1|_|!=`+Qk%YVN?Q?QUVB%^?&&m z7E^DI<`;-qMQL6Lh}yh&A*nVa=k!DV!oXV1$_}c~KGS3rJW^yZ*IrN8CRXR!B@3at zRJ>e{d*|^B{a3!X0MzYK}bcEIIlaIt$?YfRk(YSKL*3d%U1jHG?Askb`Hi=@i1nN{bj*B4R-8Vohj?lD`;M1h`_*~t`rKP(+aOV$l+$nsoktBlx|;%XVMloFQx_peqV7TM%08nQ zCyM%4!-9X;R^-N?G{Jb_x`T>nBfgV5EnplQS+z=LMizYPmJI)5ci4ZZ{H6Q#z~~wu zR@dp>2>ft?V(AC;8%_G=Pt~e8rtmw1;JFKq=p4prbH+-RqK%9MMQTmCx7hS3^*`aL zU0w0R<8#i;ZhT)j+mDm5a7j7rh{J6%f5tX3$Fcli#xaRA0_ z*Mh_ii(h_a7=Hsg7Y zppng^3*Lx*)uA_LbZ)>fW`8Be9-wH^96uX$nSy?@EBh?)b&B8!yIGhJn)pr)F-A!F z_Bp}xsxI~@y0m&il#ewp;FwcGbbk+5&-lh_lbo??O|VJHw-bOrtjke-^c!N;g;jSz zD&1+BRkZ1g-GDJLeAIyEXYQ(a#{U73x|k!TNA}_{y--TT{j4}qLu$+$0a@gFCT8c~&;%a<}sLu@P=ST88XeJaS{I;Kp z7T8uOm&&5BIq5f{L`oYuorEAs&vW0GI$MzuBKbI_7C$@~7RS}j*lg0zv~ zqF5{pj+rcR4O)b0(_8Qci5ItDqf8{v?A_7@96WAe;{iIj*E*a{sn>7tpiL(9#4NM_ zgB_oX5wfHfyQju$$G!{*a}S}L6Xwy|xj{X#@s5m7^O}#tqns-CXPcMnbkB=Nm(@UNs2oLTNpL!49?;>6@r)^snwKTFdrg5a z>PKv04p;-PM->Toufu}r!fb(vTxToB%{Mw|)Sn1N=EQB;SsAgGEkQew3SP#jp8{%B zftD%CkE$;5()qHbU(utSrkf$ToBB!jcC}X@;ZC9nN9|5LFo)4McrOalJ0mz1CA#B% zzlWFM4odQ52g$1ymhJ#EB6}k&ZGx(S0#7ZGIP`Q#-p&Q0xVMRnQ|e{-nCo7wtxn39 z<4fgW^e%q+&m`jbZ<7dmNcn7FPt?J!8{Ke`_9&9vJnd=LWn^{c3zXPDE3dkOC)hb+ zxsGA5waGIQLwP%EJL(^)>k~l94aAV8FMWOT$|qOM)99#~nEERww0(;Nak}(P!c9d$Kz`{z+Cn8-CBM zr1r~v4I()OZ!FwwXW16BNJEM=J6Tj*mI^&3)^)o`te6b%zi=6FMW z>mUNhFdr9=w~cG8WDleS&gyv<8fTly<84CBTyH9^Yy-aX!2{kJVb<$7=Onn_<`jJ>AJ;y=$xOU?J3*og^wj%*R?k}bu&m~|i7XQ0 zgocjDa4|@Fq{8T;NJ-5egt=A@Oar7!qDpqn?+3?wo9^{%v+`%k5@STrTPqcQj3zNA z45X}eGG7XS9dRL-PlnX9gIL5r11f&b^I-J0OlulgNVH!4RPh?tbVZr zH_WBYhtCR>oa$6ut-4V(QSUtdgsA^&de`D;Idv22FWNjVWX-av=K0=Hc$@c`R#UNC z{ifkp;Vw>~RSVCiId;0oj)Oq1Vs7+f2AQx}2-2eqwbI3^s=D?=U-}SxWQAXzbf_k@ z&L3}d|Tv1^X=mR={LN9nm>7&RlU_$ zGL!Rt$xMDrjrtI&*tzu1+{!iT1noZ)LKlB^qoI-F>rozVVJrpb{`Y?y*FZSHru1Ag z4-tOW+8580x$^-rC7|@GT>XLak%t9w(UqGz5Dlh6jMx+rV~f3g!+*_rpNW@nL~n8+ ztTu^(=^Cr9V2GMb`M7rKyPQjgeI7B6==9&w|3UXpQSwnGMH}rD|H_w-1o0;u(e%N7 zRVM^DB_crf3Ooay=YQ2p!TRIBAYgHrj-Eq*ULoG8I~HWtaN;&e%m%MxPln|&$8TrFvf?!<4vWHvfLC~m zrgHp}O~Y^_JcQAzwW#2qL0fi)>)6-Cn7;|!s@MQc=Ql{ZA+Hsy9~($%O{~uQ%&ICy zDSXZjE)oyJU~v}TPT@7mgB#2X$6_uH%kkJJ5o2}d4NmJRC$tO{V(~(>F44w|cX;I` zvW`3F6N5t$p2gMb5A;WEtD0)Utm|JfMtJ&vYm51oQ!alZbqQd_1Sk)xu+!1AVec;@C*a&OO0g47{NFM9$r78TY#VFAMH@U^47dXdkNc+N2^@WDAbEz{#%mvTe{;QJ({9*JjnL50 zaIiwvHeP4;W1ckplPrp*bXVDg*R*BC)yhdIkER`PV^{%V;_n1Ng$%} zF@8N>99wo>)HXNpMicMSYrYn)Uviw4TQBFXzS8jlLWJ{Q;n<>PMG+>jhQ6C8NfHLR z??YeAzoU|;DN01eYN4*3A$#oJ7YRk`+4z?3#Duv9nTn*s`g3I14uGuQOp%k-rZxU{FR#x$29pu z8rMgCys&HSxO?1pYnKw~XtELhbI{h+(~$vk4J_nPD;+e_gb(HvKDfqWxPw9D`A?2ATD6(-nT}%@AA>BacRh z1m>q$v1BKImK%R=RUCp!=ukTJJ=xsdHF)rgpbWXF8%mihBfWVMq!)19s(VBC<8drD=8wrx-i z4E85~TfhUk2agRLX>xyhllwfu960ZQh4;J5DUGBFgt!@eh+TSAJ|goysa??+@$pXMpZXpJNaMgg@eBX+vNY$0CuBl zOo_u>vxsg){(`;W1hqWWfgo;a>mGl@s&ja&_#yNSY?0+KqbT37SGuh8Fq6w=EAK7j zn$}?^&{nChS@iJ3>P!^h8@0V5L8UMbmN|+n{EcMuOn14{OAJ>^)9%a&SRih*+KP%c z@}f?85_%*ySMb68j7BXrCNm}d=|U_Ps^|}6Jh~2v`$vI@ea5%nTB#;$Y$9nL45fzS zHuE>O8rr)RwskxXaJ}AsyQ(`geRryK`{b~E1!EnTh$kVaji9$zEL!NZ-w|B|{}NCE zs?xNhDG%1Je`IdbAu}zr0BhJn`tmnu?{y(brv>6*c0EV$bI3 zQa@?Ozb0AQlf7OjC~!=*?yR35AG^8&|9YSXJ#<_BxRK{#?z~LnUCt52`?$vXL0mnm z8U=kQVl%C?`p`C#tJ#Dr3@RpEG*H%6uUNp*LYL`?8Odw)pN8dcucfwWA06K1z;brNXJ<4gZSt9X$HzSq>=>cG5SV8BOzfqlGhX)NFHPSMp85j> zu}xP_ZDO`!lzFffNh1A=7ZY7%X(Xp29BY@JSD~HHdFsS4w=@7vB9ahZFI_crLYj50qXLXeFj!rMK^QTi< zs6FBPaV}1x3dN?^#+7SA>sJ#^Xq!=i9X`P0%4-65zY=VdrJ3xvv&`B;p+lBGMfU4fIh3yDJ1M*F zO1vxN&mw=m%}~k7LUyL(WU!6h$Q)U&22@^)Z@+vnRh=98t@3_Z)?^ssos%wI16`VG z_k6YgD1I-G&pKK^aQbTI`!)EE&QIWQsjXLn&Clqq_N3Wl`A~UM&UeKh)$K~CyE2b= zVvrEB1~azLp=aKQbdfh2%WA}4B0qKO4&~n=zU|BbDRi!pm`3lNVdcmox5#<-_%kzE z_lW!(fe&ZO7j|o0?^3jCBR+NT^yIcRh$Kx^qKa)!KYl=sHmm^IFn#D}eZ>Ct%U$FV zm&&+fbxF;UP^fGLoMVimv4>Hb2U9R4TSutpC3o<>^%ZUwN9iwWjlOy4Ow@tNY=P5VMmbv$h2uQqsk+~;-9 z^5q%N*$0+QDf}L+9IaR$$#>9-O!{e%OxG|c6b=w*^x1q`3k#YSj8u+^1ry zaMof-Hk=i_z%~F4{Hp=9uNN9edRi9-t84>J{sQy56a3^71BKf#c>-k5ul9Bd^Z5H6 zPw6+B=m>6n$0Sz_cUo~SoDb)E+NbCGcPE`R*O7`muxH2RnAkY+UY0?;X@^&j^?`zy zg53iu*ejoJ*p{d+9`$rfP)EDD*g1=BEGp?SCRBb)m`Xj9=#q@#`$*N1 zrWU^2%)1greNa6Pr5mKWyqrBlq!WF29aL5P%nh8OFWi`1LPQO?c$w;Ii!+8jCn5a*EyF8HqX%Pj$mi+q*^5mJ5M1 z^o|!7*PoC#LSudmM?@=5A6B?X$*{V2&U+5}EXwX ztQ9mY(fmtzUXfk$8i#dnEDu|PBebq1L~9$U!dgvyrvWo_846kO^E_NestjBD32KSX;S0k=*7OJQYvlMC;o{GN_Lyz&6ri?#OJ zMb5*)gxh>(?P!>&{ATgp5at4kOM&0ttYk4)d)dT#+R{;;kPZ#hzUcYFRLmX`M z5buWR!bIgZw8GKQ(oYi74(A>lpv-!~R`uSUN+PB+3HQsXbfzCQ3i9$#&@Jt2B64FI zu_`s9?~zkmG@3>PlAUH!c+t*$qa{7${~A{PW-?Q+K7w=ZM?r(N^+J3}wfTpb{HK^~ zz|7l5tRedpi#0n4yuda94S)tf1E2xW0B8U-02%-dfCfMVpaIYTXaF<-8UPJ|20#O# z0nh+w05kv^01bc!Km(uw&;V!vGyoa^4S)tf1E2xW0B8U-02%-dfCfMVpaIYTXaF<- z8UPJ|20#O#0nh+w05kv^01bc!Km(uw&;V!vGyoa^4S)tf1E2xW0B8U-02%-dfCfMV zpaIYTXaF<-8UPJ|20#O#0nh+w05kv^01bc!Km(uw&;V!vGyoa^4S)tf1E2xW0B8U- z02%-dfCfMVpaIYTXaF<-8UPJ|20#O#0nh+w05kv^01bc!Km(uw&;V!vGyoa^4S)tf z1E2xW0B8U-02%-dfCfMVpaIYTXaF<-8UPJ|20#O#0nh+w05kv^01bc!Km(uw(7^vi z2A&8p8Aa-EN=f$yw~0$J@H0V(HDtjHYy;51|F!`gei~^SfhpUMG*g*o_c7f<{QV1C zf{Iq=D?PI15VP@g3$-p2bt?$`w&|MJB69h2*5|3(&8h;uL1({c*KQnIFbrhaFm)+# z@Sf3TXQ!9HUlQqk$Q1Gnq)Fq6dtrvw(B2{@NGczQ44zRGZ&Q=TpA@xrk*PEiE&B zHFRP}9G6&61Zp3Jmp##G2p!e&4jB1s&9NCTb8$PSobAQq<$CEu73yLb!1{Rg($|JQAH-=?{`&Oc#6hR9OXaspd>Z` | — | 额外 Skill 搜索目录,叠加到默认目录之上 | | `extra_agent_dirs` | `array` | — | 额外自定义 Agent 搜索目录,叠加到默认目录之上 | -| `builtin_product_skills` | `boolean` | `true` | 是否向模型提供介绍 Kimi Code 自身的内置 Skills:`update-config`、`custom-theme`、`mcp-config`、`check-kimi-code-docs`、`import-from-cc-codex`。关闭后它们的名称和描述不再进入系统提示词,代价是失去这些任务的引导流程。默认的 `agent-core-v2` 引擎会读取本字段;设置 `KIMI_CODE_LEGACY_FLAG=1` 选择旧版引擎时会忽略 | +| `builtin_product_skills` | `boolean` | `true` | 是否向模型提供介绍 Kimi Code 自身的内置 Skills | | `telemetry` | `boolean` | `true` | 是否启用匿名遥测;显式设为 `false` 时关闭 | -| `providers` | `table` | `{}` | API 供应商表 → [`providers`](#providers) | -| `models` | `table` | — | 模型别名表 → [`models`](#models) | -| `thinking` | `table` | — | Thinking 模式默认参数 → [`thinking`](#thinking) | -| `loop_control` | `table` | — | Agent 循环控制参数 → [`loop_control`](#loop-control) | -| `background` | `table` | — | 后台任务运行参数 → [`background`](#background) | -| `tools` | `table` | — | 全局工具开关 → [`tools`](#tools) | -| `image` | `table` | — | 图片压缩参数 → [`image`](#image) | -| `services` | `table` | — | 内置外部服务配置 → [`services`](#services) | -| `permission` | `table` | — | 初始权限规则 → [`permission`](#permission) | -| `hooks` | `array
` | — | 生命周期 hook,详见 [Hooks](../customization/hooks.md) | -| `identity` | `table` | — | 自定义 Agent 身份 → [`identity`](#identity) | - -以下各节对 `providers`、`models`、`thinking`、`loop_control`、`background`、`image`、`services`、`permission` 等嵌套表逐一展开。 +| [`providers`](#providers) | `table` | `{}` | API 供应商表 | +| [`models`](#models) | `table` | — | 模型别名表 | +| [`thinking`](#thinking) | `table` | — | Thinking 模式默认参数 | +| [`loop_control`](#loop_control) | `table` | — | Agent 循环控制参数 | +| [`background`](#background) | `table` | — | 后台任务运行参数 | +| [`tools`](#tools) | `table` | — | 全局工具开关 | +| [`image`](#image) | `table` | — | 图片压缩参数 | +| [`services`](#services) | `table` | — | 内置外部服务配置 | +| [`permission`](#permission) | `table` | — | 初始权限规则 | +| [`hooks`](../customization/hooks.md) | `array
` | — | 生命周期 hook | +| [`identity`](#identity) | `table` | — | 自定义 Agent 身份 | ## `providers` -`providers` 表的每一项定义一个 API 供应商,以唯一名称为 key。CLI 只从这里读取凭证,**不会**从 shell 环境变量自动取后备值——在终端里 `export KIMI_API_KEY` 不会让供应商自动获得密钥,必须显式写在配置文件里(详见[配置覆盖](./overrides.md#供应商凭证))。 +`providers` 表的每一项定义一个 API 供应商,以唯一名称为 key。CLI 只从这里读取凭证,**不会**从 shell 环境变量自动取后备值。在终端里 `export KIMI_API_KEY` 不会让供应商自动获得密钥,必须显式写在配置文件里(详见[配置覆盖](./overrides.md#供应商凭证))。 | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | @@ -129,7 +125,7 @@ timeout = 5 | `api_key` | `string` | 否 | API 密钥,明文写在配置文件里 | | `base_url` | `string` | 否 | API 基础 URL | | `oauth` | `table` | 否 | OAuth 凭据引用(`storage`、`key` 两个字段),由登录流程自动注入,通常无需手写 | -| `env` | `table` | 否 | 供应商凭证的备用来源,详见下文 | +| `env` | `table` | 否 | 供应商凭证的备用来源,见 `env` 子表 | | `custom_headers` | `table` | 否 | 每次请求附加的自定义 HTTP 头 | **`env` 子表**:可以把供应商惯用的键名(如 `KIMI_API_KEY`)写在 `[providers..env]` 里,作为 `api_key` / `base_url` 的备用来源。这个子表**只在配置文件里读取**,不会修改 shell 环境: @@ -151,16 +147,16 @@ KIMI_BASE_URL = "https://api.moonshot.ai/v1" | `provider` | `string` | 是 | 使用的供应商名称,必须在 `providers` 中定义 | | `model` | `string` | 是 | 调用 API 时实际传给服务端的模型 ID | | `max_context_size` | `integer` | 是 | 最大上下文长度(token 数),必须 ≥ 1 | -| `max_input_size` | `integer` | 否 | 模型声明的单次请求输入上限(当低于总窗口时,如 gpt-5 的 400k 窗口 / 272k 输入)。压缩、上下文溢出检查和用量比率优先使用它;补全预算仍使用总窗口。解析时会被钳制到不超过 `max_context_size` | -| `max_output_size` | `integer` | 否 | 单次请求的输出 token 上限(对应 `max_tokens`)。目前仅 `anthropic` 供应商读取。为 Claude 模型设置后,这个显式值会覆盖内置的服务端最大值 | -| `capabilities` | `array` | 否 | 显式追加的能力标签:`thinking`、`always_thinking`、`image_in`、`video_in`、`audio_in`、`tool_use`。与供应商自动识别的能力取并集,只能追加不能移除 | -| `support_efforts` | `array` | 否 | 模型接受的 Thinking 档位。对 `kimi` 而言,在运行时选择列表外的值会报错;模型解析时若配置值或之前的值不受目标模型支持,会回落到目标模型的 `default_effort`,并将该有效值同步给 UI。支持 Thinking 但没有此字段的 Kimi 模型使用布尔 `on` / `off`。其他 provider 在协议提供原生 effort 字段时会原样传递具体值;协议仅提供等级或 token budget 时,只做必要的格式转换。managed 和 open-platform 刷新可能会改写该字段;如需手动固定,请改用 `[models."".overrides] support_efforts` | -| `default_effort` | `string` | 否 | 模型的默认 Thinking 档位。managed 和 open-platform 刷新可能会改写该字段;如需手动固定,请改用 `[models."".overrides] default_effort` | -| `off_effort` | `string` | 否 | 关闭 Thinking 时在线上传输的 effort 编码(如 xai grok 的 `none`)。仅对声明了该编码的模型(catalog 会导入)有意义:设置后选择 Off 会发送这个值而不是省略 effort 字段——对默认就会推理的模型,这是真正关闭推理的唯一方式 | -| `base_url` | `string` | 否 | 模型级端点覆盖(catalog 导入网关模型时写入,这些模型与供应商默认端点不同)。解析时优先于供应商的 `base_url`;仅在与 `protocol` 配合时生效 | +| `max_input_size` | `integer` | 否 | 模型声明的单次请求输入上限;压缩、溢出检查与用量比率优先使用它,补全预算仍用总窗口 | +| `max_output_size` | `integer` | 否 | 单次请求的输出 token 上限(对应 `max_tokens`),目前仅 `anthropic` 供应商读取 | +| `capabilities` | `array` | 否 | 显式追加的能力标签:`thinking`、`always_thinking`、`image_in`、`video_in`、`audio_in`、`tool_use`,只能追加不能移除 | +| `support_efforts` | `array` | 否 | 模型接受的 Thinking 档位;解析时配置值不受支持会回落到模型的 `default_effort` 并同步给 UI;选列表外的值会报错,managed 刷新会改写(固定请用 overrides) | +| `default_effort` | `string` | 否 | 模型的默认 Thinking 档位;managed/open-platform 刷新可能改写,固定请用 [模型覆盖项](#模型覆盖项) | +| `off_effort` | `string` | 否 | 关闭 Thinking 时在线上传输的 effort 编码(如 xai grok 的 `none`);对默认就会推理的模型,这是真正关闭推理的唯一方式 | +| `base_url` | `string` | 否 | 模型级端点覆盖(catalog 导入网关模型时写入);解析时优先于供应商的 `base_url`,仅与 `protocol` 配合时生效 | | `display_name` | `string` | 否 | UI 中显示的名称,未设时回退到 `model` | -| `reasoning_key` | `string` | 否 | 仅 `openai` 供应商。当网关用非标准字段名返回推理内容时才需要设置;默认自动识别 `reasoning_content` / `reasoning_details` / `reasoning` | -| `adaptive_thinking` | `boolean` | 否 | 仅 `anthropic` 供应商。强制开启或关闭 adaptive thinking,覆盖按模型名推断的逻辑。省略时自动推断(Claude ≥ 4.6 使用 adaptive) | +| `reasoning_key` | `string` | 否 | 仅 `openai` 供应商;网关用非标准字段名返回推理内容时才需要设置,默认自动识别 `reasoning_content` 等 | +| `adaptive_thinking` | `boolean` | 否 | 仅 `anthropic` 供应商;强制开关 adaptive thinking,省略时按模型名自动推断(Claude ≥ 4.6 用 adaptive) | 别名中含 `.` 时需要加引号: @@ -188,19 +184,17 @@ display_name = "Kimi for Coding (custom)" `[models."".overrides]` 接受普通模型字段,例如 `max_context_size`、`max_input_size`、`max_output_size`、`capabilities`、`display_name`、`reasoning_key`、`adaptive_thinking`、`support_efforts`、`default_effort` 和 `off_effort`。不接受身份 / 路由字段:`provider`、`model`、`protocol`、`beta_api` 和 `base_url`。 -无需修改配置文件也可以临时切换模型——通过 `KIMI_MODEL_*` 环境变量在内存里合成一个临时供应商,详见[用环境变量定义模型](./env-vars.md#用环境变量定义模型-kimi-model)。 +无需修改配置文件也可以临时切换模型:通过 `KIMI_MODEL_*` 环境变量在内存里合成一个临时供应商,详见[用环境变量定义模型](./env-vars.md#用环境变量定义模型kimi_model_)。 ## `secondary_model` -subagent 默认继承 main agent 正在运行的模型。`[secondary_model]` 节把这件事变成可配置的:为 subagent 准备一批候选模型(模型池)并指定默认绑定——典型用法是给不需要主模型能力的子任务换一个更便宜的模型。 +subagent 默认继承 main agent 正在运行的模型。`[secondary_model]` 节把这件事变成可配置的:为 subagent 准备一批候选模型(模型池)并指定默认绑定。典型用法是给不需要主模型能力的子任务换一个更便宜的模型。 ### subagent 模型池 -配置后在包括交互式 TUI 在内的所有启动方式下生效。 - -模型池默认启用,在包括交互式 TUI 在内的所有启动方式下生效。如需禁用,设置 `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=0`(或在 `config.toml` 的 `[experimental]` 下配置 `secondary-model = false`);禁用期间模型池配置不生效:subagent 继承调用方模型,会话启动也会跳过池校验。 +该功能默认开启,无需配置即可使用。设置 `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=0` 可关闭:关闭后模型池配置不生效,subagent 继承调用方模型,会话启动也会跳过池校验。 -最小配置只有一行——单独写下的 `default_model` 就是只含一个条目的模型池: +最小配置只有一行:单独写下的 `default_model` 就是只含一个条目的模型池: ```toml [secondary_model] @@ -210,15 +204,15 @@ default_model = "kimi-code/kimi-for-coding-highspeed" | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `default_model` | `string` | — | subagent 的默认模型 | -| `models` | `table` | — | subagent 模型池。key 是 [`[models]`](#models) 条目的别名,value 是给 main agent 的挑选提示 | +| `models` | `table` | — | subagent 模型池;key 为 [`[models]`](#models) 条目别名,value 为挑选提示 | | `force` | `boolean` | `false` | 把所有 subagent 固定到 `default_model`,收回 main agent 的选择权 | -| `default_effort` | `string` | — | 每次派生的 subagent 绑定的 Thinking 档位,优先于所绑定模型条目自己的 `default_effort` | +| `default_effort` | `string` | — | 每次派生的 subagent 绑定的 Thinking 档位,优先于所绑定模型自带的 `default_effort` | 字段之间的约束: - `default_model`:配置 `models` 表时必填,且必须是其中的 key。 - `models`:value 中英文均可;空字符串表示只列出别名、不给提示。 -- `force`:必须搭配 `default_model`,且不能与 `models` 表同用——表的意义在于提供选择,而 force 取消了选择。 +- `force`:必须搭配 `default_model`,且不能与 `models` 表同用:表的意义在于提供选择,而 force 取消了选择。 - `default_effort` 是节级设置:无论派生绑定到池中哪个条目(或 force 固定的模型)都生效。想按条目区分档位时不要设置它,改用下文的模型「变体」。 - `primary` 是保留字(含义见下文),不能作为池中 key。 @@ -226,7 +220,7 @@ default_model = "kimi-code/kimi-for-coding-highspeed" 在交互式 TUI 中,也可以用 [`/secondary-model`](../reference/slash-commands.md) 命令(别名 `/subagent-model`)打开模型选择器:选择后写入 `default_model`(已有 models 表而所选别名不在其中时,会一并补一条空描述条目),之后派生的 subagent 立即按新默认值绑定,无需重启会话。 -配置了模型池(显式的 `models` 表或隐式的单条目池)即启用模型选择:`Agent` / `AgentSwarm` 工具会获得 `model` 参数,工具描述中列出模型池(默认模型标注 `[default]`),main agent 可按次派生选择模型。池 key 只能引用已配置的 [`[models]`](#models) 条目——下面的 `kimi-code/*` 别名由 `/login` 自动提供: +配置了模型池(显式的 `models` 表或隐式的单条目池)即启用模型选择:`Agent` / `AgentSwarm` 工具会获得 `model` 参数,工具描述中列出模型池(默认模型标注 `[default]`),main agent 可按次派生选择模型。池 key 只能引用已配置的 [`[models]`](#models) 条目。下面的 `kimi-code/*` 别名由 `/login` 自动提供: ```toml [secondary_model] @@ -244,7 +238,7 @@ default_model = "kimi-code/kimi-for-coding-highspeed" `model` 参数的取值规则: -- 接受池中任意别名,或 `"primary"`——调用方自己正在运行的模型,始终合法,即使不在池中。 +- 接受池中任意别名,或 `"primary"`,即调用方自己正在运行的模型,始终合法,即使不在池中。 - `default_model` 与 `models` 都未配置时该参数不存在,subagent 继承调用方模型。 - 绑定池中别名时不继承调用方的 Thinking 档位。本节设置了 `default_effort` 时以它为准;否则,`[thinking].enabled = false` 会保持关闭 Thinking;开启 Thinking 时,再依次使用所绑定模型条目的 `default_effort`、全局 `[thinking].effort`、所绑定模型 `support_efforts` 的中间项。 - `"primary"` 则连模型带档位一起继承调用方。 @@ -289,7 +283,7 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" 两个前提: - 底层模型必须声明了 `support_efforts`(`managed:kimi-code` 下目前只有 k3 系列声明了档位)。 -- 变体是独立条目,不会继承被指向条目的字段——`capabilities`、`support_efforts` 等元数据要完整照抄,否则 `default_effort` 不生效(它必须是 `support_efforts` 列表中的值)。 +- 变体是独立条目,不会继承被指向条目的字段:`capabilities`、`support_efforts` 等元数据要完整照抄,否则 `default_effort` 不生效(它必须是 `support_efforts` 列表中的值)。 另外注意 main agent 与 subagent 的不对称:对 main agent,全局 `[thinking].effort` 一旦设置就压过变体的 `default_effort`;对绑定池内别名的 subagent,变体的 `default_effort` 优先于全局值,只有 `[secondary_model].default_effort` 的优先级更高。取值与回落规则同 [`[models]` 条目的 `default_effort`](#models)。 @@ -307,17 +301,19 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | 新会话是否默认开启 Thinking,设为 `false` 可强制关闭 | -| `effort` | `string` | — | Thinking 强度(例如 `low`、`medium`、`high`、`xhigh`、`max`)。非 Kimi provider 在上游协议接受具体 effort 值时不会改写该值;如果上游拒绝,请改成该模型支持的档位。协议仅提供等级或 token budget 时,仍需做格式转换。对于带 `support_efforts` 的 Kimi 模型,若该配置值不在列表中,会回落到模型默认档位;没有该列表的 Kimi 模型会把任意开启值视为布尔 `on` | -| `keep` | `string` | `"all"` | 保留思考透传。在 `kimi` 上以 `thinking.keep` 发送;在 `anthropic`(Claude 以及 Kimi 的 Anthropic 兼容模式)上以 `context_management` 的 `clear_thinking_20251015` 编辑发送(开启 keep 会让 Anthropic 请求走 beta Messages API;关值可禁用 keep 并回到标准端点)。`"all"` 会保留历史轮次的思考内容(`reasoning_content` / Anthropic thinking blocks);传入关值(`false`/`0`/`no`/`off`/`none`/`null`)可禁用。可被 `KIMI_MODEL_THINKING_KEEP` 覆盖;仅在 Thinking 开启时注入 | +| `effort` | `string` | — | Thinking 强度:`low`/`medium`/`high`/`xhigh`/`max`;不在模型支持列表时回落默认档 | +| `keep` | `string` | `"all"` | 保留思考透传;`kimi` 以 `thinking.keep` 发送,`anthropic` 以 `clear_thinking_20251015` 编辑发送(走 beta API);关值可禁用;Thinking 开启时注入,可被同名环境变量覆盖 | -### 已废弃字段 +
已废弃字段 | 字段 | 废弃版本 | 描述 | | --- | --- | --- | -| `default_thinking` | 0.21.0 | 顶层布尔值,由 `[thinking] enabled` 取代。将 `default_thinking = true` 迁移为 `enabled = true`,`default_thinking = false` 迁移为 `enabled = false`。 | -| `thinking.mode` | 0.21.0 | 可选值 `auto` / `on` / `off`,由 `[thinking] enabled` 取代。`mode = "off"` 改为 `enabled = false`;`mode = "on"` 和 `mode = "auto"` 等价于 `enabled = true`(默认值),可删除该行。 | -| `loop_control.max_retries_per_step` | 0.32.0 | 由 `loop_control.max_attempts_per_step` 取代(该值本来就是含首次尝试的总尝试次数上限)。旧 key 不再生效,启动时会给出警告,请在 `config.toml` 中手动改名。 | -| `loop_control.max_steps_per_run` | 0.32.0 | 由 `loop_control.max_steps_per_turn` 取代。旧 key 不再生效,启动时会给出警告,请在 `config.toml` 中手动改名。 | +| `default_thinking` | 0.21.0 | 顶层布尔值,由 `[thinking] enabled` 取代,值不变 | +| `thinking.mode` | 0.21.0 | 可选值 `auto`/`on`/`off`,由 `[thinking] enabled` 取代;`off` 改 `enabled = false`,其余可删 | +| `loop_control.max_retries_per_step` | 0.32.0 | 由 `loop_control.max_attempts_per_step` 取代(本就是含首次尝试的总次数);旧 key 不生效并警告 | +| `loop_control.max_steps_per_run` | 0.32.0 | 由 `loop_control.max_steps_per_turn` 取代;旧 key 不生效,启动警告,请手动改名 | + +
## `loop_control` @@ -331,15 +327,15 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" `max_steps_per_turn` 可被环境变量 `KIMI_LOOP_MAX_STEPS_PER_TURN` 覆盖,`max_attempts_per_step` 可被 `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP` 覆盖,优先级均高于配置文件。旧的 `KIMI_LOOP_MAX_RETRIES_PER_STEP` 已废弃,但在新变量未设置时仍生效(启动时会给出警告)。 -重试仅针对瞬时故障——连接错误、超时、HTTP 429 限流和 5xx 服务端错误。账户额度耗尽或余额不足导致的 429 不会重试,会立即失败:在充值之前重试不可能成功。 +重试仅针对瞬时故障:连接错误、超时、HTTP 429 限流和 5xx 服务端错误。账户额度耗尽或余额不足导致的 429 不会重试,会立即失败:在充值之前重试不可能成功。 ## `token_counting` -`token_counting` 决定对外上报的上下文 token 计数——即上下文大小显示所基于的值。内部逻辑(自动压缩触发、预算、超限退避)始终同时使用供应商实测与估算,不受本配置影响。 +`token_counting` 决定对外上报的上下文 token 计数,即上下文大小显示所基于的值。内部逻辑(自动压缩触发、预算、超限退避)始终同时使用供应商实测与估算,不受本配置影响。 | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `strategy` | `"measured+estimated" \| "measured" \| "estimated"` | `"measured+estimated"` | `measured+estimated` 上报实时大小——每次请求的供应商实测用量加上未实测尾部的估算——并以最近一次实测总量兜底;`measured` 只上报供应商实测,显示仅在每次请求完成后变化;`estimated` 忽略供应商实测、上报纯估算——适用于不上报用量或用量不可信的供应商 | +| `strategy` | `"measured+estimated" \| "measured" \| "estimated"` | `"measured+estimated"` | 上下文 token 计数策略:`measured+estimated` 为实测加估算兜底,`measured` 仅实测(请求完成后更新),`estimated` 纯估算(供应商不上报用量时用) | `strategy` 可被环境变量 `KIMI_TOKEN_COUNTING_STRATEGY` 覆盖,优先级高于 `config.toml`。 @@ -350,13 +346,13 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `max_running_tasks` | `integer` | — | 同时运行的最大后台任务数 | -| `keep_alive_on_exit` | `boolean` | `false` | 会话关闭时是否保留仍在运行的后台任务。默认情况下,Kimi Code 会在进程退出前请求停止所有后台任务;只有希望任务在会话结束后继续运行时才设为 `true`。在 print 模式(`kimi -p`)下,本字段仅作为 `print_background_mode` 未设置时的兼容回退:`true` 等价于 `print_background_mode = "drain"` | -| `kill_grace_period_ms` | `integer` | `5000` | 会话关闭、手动停止或任务超时请求正常终止后,等待任务自行结束的宽限时间(毫秒)。超过该时间仍在运行时,Kimi Code 会尝试强制停止该任务 | -| `bash_auto_background_on_timeout` | `boolean` | `true` | 前台 `Bash` 命令触及超时时间时,将其转为后台任务而不是直接终止:命令完成时 agent 会收到通知,转入后台的命令受 `bash_task_timeout_s` 默认后台超时约束。设为 `false` 则恢复超时即终止的行为 | -| `bash_task_timeout_s` | `integer` | `600` | 后台 `Bash` 任务在调用未传 `timeout` 时的默认超时(秒);前台命令超时转后台后也按此值重新计时。`0` 表示无超时——任务一直运行到自行结束或被模型手动停止。显式传入的 `timeout` 不受影响。在 print 模式(`kimi -p`)下未显式设置时默认为 `0` | -| `print_background_mode` | `"exit" \| "drain" \| "steer"` | `"steer"` | 仅 print 模式(`kimi -p`)生效,决定 main agent 的 turn 结束后如何处理未返回的后台任务:`"exit"` 立即退出;`"drain"` 退出前等待所有后台任务进入终态(结果不回馈给 main agent);`"steer"` 不退出,让后台任务完成时像后台 subagent 一样以合成 user 消息 steer main agent 进入新 turn,直到某 turn 结束时无未决后台任务或触及上限。设置后优先级高于 `keep_alive_on_exit` 的 print 回退 | -| `print_wait_ceiling_s` | `integer` | `2147483` | print 模式(`kimi -p`)下,`print_background_mode` 为 `"drain"` 或 `"steer"` 时,等待/steer 循环的墙钟上限(秒;默认约 24.8 天,近似不设限)。在非 print 模式或 `"exit"` 时无效 | -| `print_max_turns` | `integer` | `100000` | print 模式(`kimi -p`)且 `print_background_mode = "steer"` 时,允许由后台任务完成触发的新 turn 的最大数量,防止 steer 循环失控(默认值近似不设限) | +| `keep_alive_on_exit` | `boolean` | `false` | 会话关闭时是否保留仍在运行的后台任务;print 模式下仅作 `print_background_mode` 的回退:`true` 等价于 `drain` | +| `kill_grace_period_ms` | `integer` | `5000` | 任务被请求正常终止后,等待自行结束的宽限时间(毫秒),超时后强制停止 | +| `bash_auto_background_on_timeout` | `boolean` | `true` | 前台 `Bash` 命令超时后转为后台任务而非终止;设为 `false` 恢复超时即终止 | +| `bash_task_timeout_s` | `integer` | `600` | 后台 `Bash` 任务默认超时(秒);`0` 表示无超时,任务运行到自行结束或被手动停止;显式传入的 timeout 不受影响,print 模式默认 0 | +| `print_background_mode` | `"exit" \| "drain" \| "steer"` | `"steer"` | 仅 print 模式生效;`"exit"` 立即退出、`"drain"` 等待终态(结果不回馈)、`"steer"` 由后台任务合成消息继续 turn(合成消息续跑至无未决任务) | +| `print_wait_ceiling_s` | `integer` | `2147483` | 等待/steer 循环的墙钟上限(秒),非 print 模式或 `"exit"` 时无效 | +| `print_max_turns` | `integer` | `100000` | steer 模式下后台任务触发新 turn 的数量上限,防止 steer 循环失控 | `keep_alive_on_exit` 可被环境变量 `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` 覆盖,`max_running_tasks` 可被 `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS` 覆盖,优先级均高于配置文件。 @@ -368,7 +364,7 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `timeout_ms` | `integer` | `7200000`(2 小时) | 单个 `Agent` subagent 允许运行的最长时间(毫秒)。超时后 subagent 以 `timed_out` 收尾。`0` 表示无超时——subagent 一直运行到自行结束或被模型手动停止。该值是后台任务管理器对每个 subagent 任务的 per-task timeout,因此对前台与后台 subagent 同时生效。在 print 模式(`kimi -p`)下未显式设置时默认为 `0`。注意:超过 `2147483647`(约 24.8 天)的值会被运行时钳到约 24.8 天 | +| `timeout_ms` | `integer` | `7200000`(2 小时) | 单个 `Agent` subagent 允许运行的最长时间(毫秒);超时以 `timed_out` 收尾,`0` 表示无超时 | `timeout_ms` 可被环境变量 `KIMI_SUBAGENT_TIMEOUT_MS` 覆盖,优先级高于配置文件。 @@ -378,7 +374,7 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `timeout_ms` | `integer` | `7200000`(2 小时) | `AgentSwarm` 启动的单个 subagent 允许运行的最长时间(毫秒)。超时后该 subagent 被中止,聚合报告中标记为失败(`Subagent timed out.`),其余 subagent 不受影响。`0` 表示无超时——subagent 一直运行到自行结束或被模型手动停止。在 print 模式(`kimi -p`)下未显式设置时默认为 `0`。注意:超过 `2147483647`(约 24.8 天)的值会被运行时钳到约 24.8 天 | +| `timeout_ms` | `integer` | `7200000`(2 小时) | `AgentSwarm` 单个 subagent 允许运行的最长时间(毫秒);超时后中止,聚合报告标记 `Subagent timed out.`;0 为无超时 | `timeout_ms` 可被环境变量 `KIMI_CODE_SWARM_TIMEOUT_MS` 覆盖,优先级高于配置文件。 @@ -386,8 +382,8 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `startup_timeout_ms` | `integer` | `30000`(30 秒) | 所有 MCP server 的全局默认连接(启动 + 工具发现)超时(毫秒),取值范围为 `1`–`2147483647`。`mcp.json` 中单个 server 的 `startupTimeoutMs` 始终优先于本节与环境变量;都未设置时使用默认值 | -| `tool_timeout_ms` | `integer` | `60000`(60 秒) | 所有 MCP server 的全局默认单次工具调用超时(毫秒),取值范围为 `1`–`2147483647`。`mcp.json` 中单个 server 的 `toolTimeoutMs` 始终优先于本节与环境变量;都未设置时使用客户端内置默认值 | +| `startup_timeout_ms` | `integer` | `30000`(30 秒) | 所有 MCP server 的全局默认连接(启动 + 工具发现)超时(毫秒);`mcp.json` 的 `startupTimeoutMs` 优先于本节 | +| `tool_timeout_ms` | `integer` | `60000`(60 秒) | 所有 MCP server 的全局默认单次工具调用超时(毫秒);`mcp.json` 的 `toolTimeoutMs` 优先于本节 | `startup_timeout_ms` 和 `tool_timeout_ms` 可分别被环境变量 `KIMI_MCP_STARTUP_TIMEOUT_MS` 和 `KIMI_MCP_TOOL_TIMEOUT_MS` 覆盖,优先级高于配置文件。MCP server 的完整配置方式见 [MCP](../customization/mcp.md)。 @@ -398,7 +394,7 @@ k3-max = "同一模型的 max Thinking 档位。适合最难的子任务。" | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `name` | `string` | — | Agent 在系统提示词中的自称(填充 `${product_name}` 变量,你自己的 `SYSTEM.md` 和 agent 文件同样适用) | -| `slug` | `string` | 由 `name` 派生 | 协议字段中使用的机器标识:发给第三方 provider 的 `User-Agent` 产品名,以及连接 MCP 服务器时声明的客户端名。省略时由 `name` 派生:转小写,连续的非字母数字字符折叠为 `-` | +| `slug` | `string` | 由 `name` 派生 | 协议字段中的机器标识:`User-Agent` 产品名与 MCP 客户端名;省略时由 `name` 派生(转小写,非字母数字折叠为 `-`) | ```toml [identity] @@ -406,11 +402,11 @@ name = "Acme Dev Agent" slug = "acme-dev" # 可选 ``` -两个字段都可以通过 `KIMI_CODE_IDENTITY_NAME` 和 `KIMI_CODE_IDENTITY_SLUG` 环境变量设置,优先级高于 `config.toml`,且不会被写回配置文件——适合不便写配置文件的容器和 CI 场景。 +两个字段都可以通过 `KIMI_CODE_IDENTITY_NAME` 和 `KIMI_CODE_IDENTITY_SLUG` 环境变量设置,优先级高于 `config.toml`,且不会被写回配置文件,适合不便写配置文件的容器和 CI 场景。 如果名称中不含任何 ASCII 字母或数字(例如纯中文名称),就无法派生出 slug,此时回退为 `agent`;需要特定协议标识请显式填写 `slug`。 -身份在启动时解析一次,进程生命周期内保持不变——建立连接时它已宣告给 MCP 服务器和 provider,中途无法更换。修改本节配置在下次启动时对新会话生效;resume 的会话保留录制时的系统提示词,因为其历史轮次本就以原身份自称。同理,已完成的 MCP OAuth 授权保留其授予时的客户端注册;重置该服务器的认证即可在新身份下重新注册。 +身份在启动时解析一次,进程生命周期内保持不变:建立连接时它已宣告给 MCP 服务器和 provider,中途无法更换。修改本节配置在下次启动时对新会话生效;resume 的会话保留录制时的系统提示词,因为其历史轮次本就以原身份自称。同理,已完成的 MCP OAuth 授权保留其授予时的客户端注册;重置该服务器的认证即可在新身份下重新注册。 本节由默认的 `agent-core-v2` 引擎读取。设置 `KIMI_CODE_LEGACY_FLAG=1` 后,旧版 `kimi` / `kimi -p` 路径会忽略此配置;`kimi web` 始终使用 `agent-core-v2`。 @@ -423,7 +419,7 @@ slug = "acme-dev" # 可选 | `enabled` | `array` | — | 全局允许列表:非空时仅列出的工具可用;省略或设为空数组均表示不约束 | | `disabled` | `array` | — | 全局禁止列表,在 `enabled` 之后应用 | -工具名匹配规则与 Agent 文件中的同名字段一致:内置工具按名称精确匹配(如 `Read`),MCP 工具用 glob 匹配(如 `mcp__github__*`)。有三种写法永远匹配不到任何工具,出现时会给出警告:`mcp__` 模式之外使用通配符(`enabled = ["*"]` 会禁用所有工具,而 `disabled = ["*"]` 什么也禁不掉);缺少工具段的 `mcp__` 字面量(`mcp__github` —— 匹配整个服务器要用 `mcp__github__*`);以及任何已注册或内置工具都没有的名字(匹配区分大小写)。 +工具名匹配规则与 Agent 文件中的同名字段一致:内置工具按名称精确匹配(如 `Read`),MCP 工具用 glob 匹配(如 `mcp__github__*`)。有三种写法永远匹配不到任何工具,出现时会给出警告:`mcp__` 模式之外使用通配符(`enabled = ["*"]` 会禁用所有工具,而 `disabled = ["*"]` 什么也禁不掉);缺少工具段的 `mcp__` 字面量(`mcp__github`,匹配整个服务器要用 `mcp__github__*`);以及任何已注册或内置工具都没有的名字(匹配区分大小写)。 ```toml [tools] @@ -441,7 +437,7 @@ disabled = ["EnterPlanMode", "ExitPlanMode", "mcp__github__*"] | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `max_edge_px` | `integer` | `2000` | 图片最长边上限(像素)。超过时按比例缩小到该值以内;调大可保留更多细节,代价是更大的请求体积 | -| `read_byte_budget` | `integer` | `262144`(256 KB) | 模型自行读取的图片(`ReadMediaFile` 默认读取)的单图字节预算。会话中模型反复截图、读图时,累计请求体大小由它控制;细节可通过 `region` 参数按原图坐标全保真回读(`region` 与 `full_resolution` 不受此预算限制) | +| `read_byte_budget` | `integer` | `262144`(256 KB) | 模型自行读取图片的单图字节预算(`ReadMediaFile` 默认读取);`region` 与 `full_resolution` 回读不受此限制 | `max_edge_px` 可被环境变量 `KIMI_IMAGE_MAX_EDGE_PX` 覆盖,`read_byte_budget` 可被 `KIMI_IMAGE_READ_BYTE_BUDGET` 覆盖,优先级均高于配置文件。 @@ -487,7 +483,7 @@ api_key = "sk-xxx" | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | `decision` | `string` | 是 | 匹配后的处置:`allow`(直接放行)、`deny`(直接拒绝)、`ask`(每次询问) | -| `scope` | `string` | 否 | 规则有效范围:`turn-override`、`session-runtime`、`project`、`user`;默认 `user` | +| `scope` | `string` | 否 | 规则有效范围:`turn-override`、`session-runtime`、`project`、`user`,默认 `user` | | `pattern` | `string` | 是 | 匹配模式,格式为 `工具名` 或 `工具名(参数模式)`,如 `Read`、`Bash(rm -rf*)` | | `reason` | `string` | 否 | 规则说明,仅用于调试和审计 | @@ -521,16 +517,23 @@ MCP server 的声明配置写在 `~/.kimi-code/mcp.json` 或项目内 `.kimi-cod | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `theme` | `string` | `auto` | 配色主题:`auto`(跟随终端)、`dark`、`light`,或[自定义主题](../customization/themes.md)的名字 | -| `render_latex` | `boolean` | `true` | 将 Markdown 消息中的 LaTeX 公式(`$…$`、`$$…$$`)渲染为 Unicode 文本;`false` 则保留原始源码 | +| `theme` | `string` | `auto` | 配色主题:`auto`、`dark`、`light` 或[自定义主题](../customization/themes.md)名 | +| `render_latex` | `boolean` | `true` | 将 Markdown 中的 LaTeX 公式渲染为 Unicode 文本;`false` 保留原始源码 | | `disable_paste_burst` | `boolean` | `false` | 禁用非 bracketed paste 的粘贴突发兜底;默认开启,避免快速多行粘贴被逐行提交 | -| `cache_expiry_hint` | `boolean` | `true` | resume 长时间未活动的会话、或长时间空闲后发送消息时,若上下文缓存可能已过期则弹出提醒,可选择先压缩或新建会话(仅 v2 引擎) | +| `cache_expiry_hint` | `boolean` | `true` | resume 或长时间空闲后发消息时,若上下文缓存可能过期则提醒,可先压缩或新建会话(仅 v2 引擎) | | `[editor].command` | `string` | `""` | 编写长输入用的外部编辑器命令;留空则回退到 `$VISUAL` / `$EDITOR` | | `[notifications].enabled` | `boolean` | `true` | 是否发送桌面通知 | | `[notifications].notification_condition` | `string` | `unfocused` | 何时通知:`unfocused`(仅终端失去焦点时)或 `always`(总是) | | `[upgrade].auto_install` | `boolean` | `true` | 是否自动安装新版本 | -| `[status_line].items` | `string[]` | `[]` | 底部状态栏第一行展示哪些内置槽位及其顺序:`mode`、`goal`、`model`、`tasks`、`cwd`、`git`、`tips`。缺省保持默认布局;未知 id 跳过并告警 | -| `[status_line].command` | `string` | `""` | 自定义状态栏命令。其 stdout 第一行替换状态栏第一行,stdin 会收到 JSON 快照(model、cwd、git 分支、permission 模式、plan 模式、上下文用量、session id、版本)。运行上限 300ms、每秒最多一次;失败时回退内置布局 | +| `[status_line].items` | `string[]` | `[]` | 底部状态栏第一行的内置槽位及顺序:`mode`、`goal`、`model`、`tasks`、`cwd`、`git`、`tips`,未知 id 跳过并告警 | +| `[status_line].command` | `string` | `""` | 自定义状态栏命令:stdout 首行替换状态栏,stdin 收 JSON 快照;上限 300ms、每秒一次,失败回退内置布局 | + +
+command 的 stdin 输入 + +model、cwd、git 分支、permission 模式、plan 模式、上下文用量、session id、版本。 + +
```toml # ~/.kimi-code/tui.toml @@ -568,7 +571,7 @@ auto_install = true | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | -| `additional_dir` | `array` | 否 | 额外工作目录列表,以绝对路径存储。在 `/add-dir` 中确认"记住此目录"时自动写入;启动时读回,使这些目录在该项目的每个会话中都可用 | +| `additional_dir` | `array` | 否 | 额外工作目录列表(绝对路径);在 `/add-dir` 确认"记住此目录"时自动写入,该项目每个会话可用 | ```toml [workspace] diff --git a/docs/zh/configuration/data-locations.md b/docs/zh/configuration/data-locations.md index 302198278f8..e1a87c0b869 100644 --- a/docs/zh/configuration/data-locations.md +++ b/docs/zh/configuration/data-locations.md @@ -1,6 +1,6 @@ # 数据路径 -Kimi Code CLI 把所有运行时数据——配置文件、会话历史、登录凭据、诊断日志——集中存放在 `~/.kimi-code/` 下。本页帮你搞清楚每类数据在哪里、用来做什么,以及需要时怎么清理或搬迁。 +Kimi Code CLI 把配置文件、会话历史、登录凭据、诊断日志等运行时数据集中存放在 `~/.kimi-code/` 下。本页帮你搞清楚每类数据在哪里、用来做什么,以及需要时怎么清理或搬迁。 ## 数据根目录 @@ -61,7 +61,7 @@ $KIMI_CODE_HOME (默认 ~/.kimi-code) 数据根下的顶层文件各有用途,大部分由 CLI 自动管理: - **`config.toml`**:主运行时配置,存放供应商、模型、循环控制等用户级设置。详见[配置文件](./config-files.md)。 -- **`tui.toml`**:终端界面客户端偏好,包括 `[upgrade].auto_install`(自动更新,默认开启)。可在 `/settings` 关闭,或手动设为 `auto_install = false`。 +- **`tui.toml`**:终端界面客户端偏好,包括自动更新开关 `[upgrade].auto_install`(默认开启)。可在 `/settings` 关闭,或手动设为 `auto_install = false`。 - **`AGENTS.md`**:全局 Kimi 专属 Agent 指令。该文件会随 `KIMI_CODE_HOME` 移动;跨工具通用指令仍可放在 `~/.agents/AGENTS.md`。 - **`mcp.json`**:用户级 MCP server 声明,启动时与项目内的 `.kimi-code/mcp.json` 合并加载。详见 [MCP](../customization/mcp.md)。 - **`skills/`**:Kimi 专属用户级 Skills。该目录会随 `KIMI_CODE_HOME` 移动;跨工具通用 Skills 仍可放在 `~/.agents/skills/`。详见 [Agent Skills](../customization/skills.md)。 @@ -80,7 +80,7 @@ $KIMI_CODE_HOME (默认 ~/.kimi-code) - **`agents/main/plans/`**:Plan 模式下写入的计划文件,按计划 id 命名(`.md`)。 - **`agents/agent-0/` 等**:subagent 实例目录,各自含 `wire.jsonl`。 - **`logs/kimi-code.log`**:该会话的诊断日志,只有发生诊断事件时才存在。 -- **`tasks/`**:后台任务持久化——`tasks/.json` 保存状态/pid/退出码,`tasks//output.log` 保存输出。 +- **`tasks/`**:后台任务持久化。`tasks/.json` 保存状态/pid/退出码,`tasks//output.log` 保存输出。 - **`cron/`**:定时任务持久化,用 `kimi --session` 恢复会话时重新加载到调度器。详见[定时任务](../reference/tools.md#定时任务)。 ## 内置工具缓存 diff --git a/docs/zh/configuration/env-vars.md b/docs/zh/configuration/env-vars.md index b7c3411cb7e..3bae4e7754d 100644 --- a/docs/zh/configuration/env-vars.md +++ b/docs/zh/configuration/env-vars.md @@ -1,11 +1,11 @@ # 环境变量 -Kimi Code CLI 通过环境变量控制少数运行时行为——迁移数据目录、关闭遥测、不改配置文件临时切换模型。 +Kimi Code CLI 通过环境变量控制少数运行时行为:迁移数据目录、关闭遥测、不改配置文件临时切换模型。 ::: warning 重要:API 密钥不在这里配置 -`KIMI_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY` 等密钥变量**不会**从 shell 环境变量自动读取。在终端里 `export KIMI_API_KEY=xxx` 不会让任何供应商获得密钥——必须写在 `config.toml` 的 `[providers.]` 段或 `[providers..env]` 子表里。 +`KIMI_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY` 等密钥变量**不会**从 shell 环境变量自动读取。在终端里 `export KIMI_API_KEY=xxx` 不会让任何供应商获得密钥。密钥必须写在 `config.toml` 的 `[providers.]` 段或 `[providers..env]` 子表里。 -唯一的例外是 `KIMI_MODEL_*` 系列,它是一个显式通道,*确实*会从 shell 读取凭证——详见[用环境变量定义模型](#用环境变量定义模型-kimi-model)。 +唯一的例外是 `KIMI_MODEL_*` 系列,它是一个显式通道,*确实*会从 shell 读取凭证。详见[用环境变量定义模型](#用环境变量定义模型kimi_model_)。 背景说明见[配置覆盖:供应商凭证](./overrides.md#供应商凭证)。 ::: @@ -34,11 +34,15 @@ export KIMI_DISABLE_TELEMETRY=1 ### `KIMI_MODEL_*` 系列 -不修改 `config.toml` 临时切换模型——设置 `KIMI_MODEL_NAME` 后,CLI 在内存里合成一个临时供应商,重启后失效。详见[用环境变量定义模型](#用环境变量定义模型-kimi-model)。 +不修改 `config.toml` 临时切换模型:设置 `KIMI_MODEL_NAME` 后,CLI 在内存里合成一个临时供应商,重启后失效。详见[用环境变量定义模型](#用环境变量定义模型kimi_model_)。 ### `KIMI_CODE_CUSTOM_HEADERS` -为所有出站的模型请求附加自定义 HTTP 请求头——LLM 聊天请求(所有供应商协议)和 `/models` 模型列表请求都会携带。适合网关按请求头路由的场景,例如指定集群: +::: info 新增 +新增于 0.20.2。 +::: + +为所有出站的模型请求附加自定义 HTTP 请求头:LLM 聊天请求(所有供应商协议)和 `/models` 模型列表请求都会携带。适合网关按请求头路由的场景,例如指定集群: ```sh export KIMI_CODE_CUSTOM_HEADERS=$'X-Gateway-Cluster: my-cluster\nX-Custom-Tag: debug' @@ -46,15 +50,11 @@ export KIMI_CODE_CUSTOM_HEADERS=$'X-Gateway-Cluster: my-cluster\nX-Custom-Tag: d 格式与 `ANTHROPIC_CUSTOM_HEADERS` 一致:由换行分隔的 `Name: Value` 行,键名和值两端的空白会被去除,不含冒号的行会被忽略。 -::: info 新增 -新增于 0.20.2。 -::: - -> 优先级:Kimi 身份头(`User-Agent`、`X-Msh-*`)和 `config.toml` 里供应商的 `custom_headers`(见 [配置文件](./config-files.md#providers))会覆盖这里的同名条目。认证头的行为因协议而异:在 `kimi`、`openai`、`openai_responses` 协议上,`Authorization` 条目会替换生成的 bearer token;`/models` 列表请求始终使用自己的认证头。`authorization` 这类大小写变体不会被当作同名头——它会与真正的头合并,可能导致请求失败。不要用它设置认证等保留头。需要按供应商区分请求头时,请改用 `custom_headers`。 +> 优先级:Kimi 身份头(`User-Agent`、`X-Msh-*`)和 `config.toml` 里供应商的 `custom_headers`(见 [配置文件](./config-files.md#providers))会覆盖这里的同名条目。认证头的行为因协议而异:在 `kimi`、`openai`、`openai_responses` 协议上,`Authorization` 条目会替换生成的 bearer token;`/models` 列表请求始终使用自己的认证头。`authorization` 这类大小写变体不会被当作同名头。它会与真正的头合并,可能导致请求失败。不要用它设置认证等保留头。需要按供应商区分请求头时,请改用 `custom_headers`。 ## 供应商凭证键(写在 config.toml 里) -下面这些键名不是直接从 shell 读取的——它们是写在 `config.toml` 的 `[providers..env]` 子表里、作为 `api_key` / `base_url` 备用来源的键名。CLI 只从配置文件读取,不从 `process.env` 读取。 +下面这些键名不是直接从 shell 读取的。它们是写在 `config.toml` 的 `[providers..env]` 子表里、作为 `api_key` / `base_url` 备用来源的键名。CLI 只从配置文件读取,不从 `process.env` 读取。 这样设计是为了让你保留熟悉的键名写法,同时把密钥放在配置文件里统一管理: @@ -80,7 +80,7 @@ KIMI_BASE_URL = "https://api.moonshot.ai/v1" | `GOOGLE_CLOUD_LOCATION` | Vertex AI | 无 | ::: warning -`GOOGLE_APPLICATION_CREDENTIALS`(服务账号 JSON 路径)是唯一走系统环境变量的例外——它由 Google SDK 自身通过 ADC 流程读取,CLI 不参与。其他所有键名都必须写在 `[providers..env]` 子表里。 +`GOOGLE_APPLICATION_CREDENTIALS`(服务账号 JSON 路径)是唯一走系统环境变量的例外。它由 Google SDK 自身通过 ADC 流程读取,CLI 不参与。其他所有键名都必须写在 `[providers..env]` 子表里。 ::: 供应商类型与字段的完整说明见[平台与模型](./providers.md)。 @@ -137,40 +137,40 @@ kimi | 环境变量 | 用途 | 合法值 | | --- | --- | --- | | `KIMI_DISABLE_TELEMETRY` | 关闭匿名遥测上报 | `1`、`true`、`yes`、`y`(不区分大小写) | -| `KIMI_CODE_PASSWORD` | 为 `kimi web` 本地服务设置并列鉴权密码,与 bearer token 同时有效;把服务绑定到非本机地址时建议设置,见 [在网页中使用:安全注意](../guides/web.md#安全注意) | 任意非空字符串;未设置时仅 token 有效 | +| `KIMI_CODE_PASSWORD` | 为 `kimi web` 本地服务设置并列鉴权密码;绑到非本机地址时建议设置,见 [安全注意](../guides/web.md#安全注意) | 任意非空字符串;未设置时仅 token 有效 | | `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` | 会话关闭时是否保留后台任务,优先级高于 `config.toml`。默认会在退出时停止后台任务 | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | -| `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS` | 同时运行的后台任务数上限,优先级高于 `config.toml` 的 `[background] max_running_tasks`(不设置表示无上限) | 正整数;非法值被忽略 | +| `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS` | 同时运行的后台任务数上限,优先级高于 `config.toml` 的 `[background] max_running_tasks`;不设置表示无上限 | 正整数;非法值被忽略 | | `KIMI_IMAGE_MAX_EDGE_PX` | 图片压缩的最长边上限(像素),优先级高于 `config.toml` 的 `[image] max_edge_px`(默认 `2000`) | 正整数;非法值被忽略 | -| `KIMI_IMAGE_READ_BYTE_BUDGET` | 模型自行读图(`ReadMediaFile` 默认读取)的单图字节预算,优先级高于 `config.toml` 的 `[image] read_byte_budget`(默认 `262144`,即 256 KB) | 正整数;非法值被忽略 | -| `KIMI_CODE_PLUGIN_MARKETPLACE_URL` | 覆盖 `/plugins` 加载的 plugin marketplace JSON,适合 dev loopback server、测试 CDN 文件或替换 marketplace 目录 | `https://code.kimi.com/kimi-code/plugins/marketplace.json`;也接受 `http://`、`file://` URL 和本地路径 | +| `KIMI_IMAGE_READ_BYTE_BUDGET` | 模型自行读图的单图字节预算,优先级高于 `config.toml` 的 `[image] read_byte_budget`(默认 `262144`) | 正整数;非法值被忽略 | +| `KIMI_CODE_PLUGIN_MARKETPLACE_URL` | 覆盖 `/plugins` 加载的 marketplace JSON;默认 `https://code.kimi.com/kimi-code/plugins/marketplace.json` | 也接受 `http://`、`file://` URL 和本地路径 | | `KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY` | 限制 AgentSwarm 初始提升并发阶段可同时运行的 subagent 数量;不设置表示不限制 | 正整数;非法值会立即失败 | -| `KIMI_SUBAGENT_TIMEOUT_MS` | 单个 `Agent` subagent 可运行的最长时间(毫秒);优先级高于 `config.toml` 的 `[subagent] timeout_ms`(默认 `7200000`,即 2 小时) | 正整数;非法值回退到配置或默认值 | -| `KIMI_CODE_SWARM_TIMEOUT_MS` | 单个 `AgentSwarm` subagent 可运行的最长时间(毫秒);优先级高于 `config.toml` 的 `[swarm] timeout_ms`(默认 `7200000`,即 2 小时) | 正整数;非法值回退到配置或默认值 | -| `KIMI_CODE_IDENTITY_NAME` | Agent 在系统提示词中的自称,优先级高于 `config.toml` 的 `[identity] name`,且不会被写回配置文件 | 任意非空字符串;空值视为未设置 | -| `KIMI_CODE_IDENTITY_SLUG` | 协议标识,用于发给第三方 provider 的 `User-Agent` 产品名和 MCP 客户端名,优先级高于 `[identity] slug`。未设置时由名称派生 | 任意非空字符串;会转小写并将连续非字母数字字符折叠为 `-` | -| `KIMI_CODE_BUILTIN_PRODUCT_SKILLS` | 是否向模型提供介绍 Kimi Code 自身的内置 Skills,优先级高于 `config.toml` 的 `builtin_product_skills`(默认开启) | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | -| `KIMI_CODE_TUI_FULL_SCREEN` | 启用实验性的 fullscreen alternate-screen 界面:可滚动的 transcript 视口、鼠标选择文本、可点击链接、Ctrl-Shift-F 搜索 | `1` 开启;其他值保持常规内联界面 | -| `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL` | [subagent 模型池](./config-files.md#subagent-模型池) 默认启用,在包括交互式 TUI 在内的所有启动方式下生效;设为假值可禁用;master `KIMI_CODE_EXPERIMENTAL_FLAG=1` 也会启用本功能 | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | -| `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK` | 在 `Agent` 和 `AgentSwarm` 工具上启用实验性的 `fork` 参数,让模型可以以调用方 Agent 对话历史的快照而不是空上下文启动 subagent;master `KIMI_CODE_EXPERIMENTAL_FLAG=1` 也会启用本功能 | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | -| `KIMI_MCP_STARTUP_TIMEOUT_MS` | 所有 MCP server 的全局默认连接超时(毫秒);优先级高于 `config.toml` 的 `[mcp] startup_timeout_ms`,但低于 `mcp.json` 中单个 server 的 `startupTimeoutMs`(默认 `30000`) | `1` 到 `2147483647` 的整数;非法值被忽略 | -| `KIMI_MCP_TOOL_TIMEOUT_MS` | 所有 MCP server 的全局默认单次工具调用超时(毫秒);优先级高于 `config.toml` 的 `[mcp] tool_timeout_ms`,但低于 `mcp.json` 中单个 server 的 `toolTimeoutMs`(默认 `60000`) | `1` 到 `2147483647` 的整数;非法值被忽略 | -| `KIMI_LOOP_MAX_STEPS_PER_TURN` | Agent 单轮最大步数;优先级高于 `config.toml` 的 `[loop_control] max_steps_per_turn`(不设或 `0` 表示无上限) | 非负整数;非法值被忽略 | -| `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP` | 单步失败后的最大总尝试次数(含首次尝试);优先级高于 `config.toml` 的 `[loop_control] max_attempts_per_step`(默认 `10`)。旧的 `KIMI_LOOP_MAX_RETRIES_PER_STEP` 已废弃,但在本变量未设置时仍生效并给出警告 | 非负整数;非法值被忽略 | -| `KIMI_CODE_INFINITE_RETRY` | 让所有失败的 LLM 请求无限重试(包括轮次内步骤和 compaction 等后台操作)而不是终止任务;重试等待按指数退避(32 秒封顶)并尊重服务端 `Retry-After` 头,等待期间中断仍立即生效。适用于端点可能短暂故障的长时间无人值守评测 | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | -| `KIMI_TOKEN_COUNTING_STRATEGY` | 对外上报的上下文 token 计数(上下文大小显示);优先级高于 `config.toml` 的 `[token_counting] strategy`(默认 `measured+estimated`) | `measured+estimated`、`measured`、`estimated`(不区分大小写);非法值被忽略 | -| `KIMI_WEB_SEARCH_BASE_URL` | 网页搜索(`WebSearch`)服务的 API URL;优先级高于 `config.toml` 的 `[services.moonshot_search] base_url`,未写配置段时也可启用服务。文件中持久化的凭据和自定义 header 不会发送到环境变量指定的端点 | 非空字符串;空白值被忽略 | +| `KIMI_SUBAGENT_TIMEOUT_MS` | 单个 `Agent` subagent 可运行的最长时间(毫秒),优先级高于 `config.toml` 的 `[subagent] timeout_ms` | 正整数;非法值回退到配置或默认值 | +| `KIMI_CODE_SWARM_TIMEOUT_MS` | `AgentSwarm` subagent 可运行的最长时间(毫秒),优先级高于 `config.toml` 的 `[swarm] timeout_ms` | 正整数;非法值回退到配置或默认值 | +| `KIMI_CODE_IDENTITY_NAME` | Agent 在系统提示词中的自称,优先级高于 `config.toml` 的 `[identity] name`,不写回配置文件 | 任意非空字符串;空值视为未设置 | +| `KIMI_CODE_IDENTITY_SLUG` | 协议标识(`User-Agent` 产品名、MCP 客户端名),优先级高于 `[identity] slug`;未设置时由名称派生 | 任意非空字符串;会转小写并将连续非字母数字字符折叠为 `-` | +| `KIMI_CODE_BUILTIN_PRODUCT_SKILLS` | 是否向模型提供介绍 Kimi Code 自身的内置 Skills,优先级高于 `config.toml` 的 `builtin_product_skills` | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | +| `KIMI_CODE_TUI_FULL_SCREEN` | 启用实验性的 fullscreen 界面:可滚动 transcript、鼠标选择、可点击链接、Ctrl-Shift-F 搜索 | `1` 开启;其他值保持常规内联界面 | +| `KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL` | 启用实验性的 [subagent 模型池](./config-files.md#subagent-模型池),所有启动方式生效 | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | +| `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK` | 在 `Agent`/`AgentSwarm` 上启用实验性 `fork` 参数:以调用方对话历史快照而非空上下文启动 subagent | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | +| `KIMI_MCP_STARTUP_TIMEOUT_MS` | MCP server 全局默认连接超时(毫秒);优先级高于配置文件,低于 `mcp.json` 的 `startupTimeoutMs` | `1` 到 `2147483647` 的整数;非法值被忽略 | +| `KIMI_MCP_TOOL_TIMEOUT_MS` | MCP server 全局默认单次工具调用超时(毫秒);优先级高于配置文件,低于 `mcp.json` 的 `toolTimeoutMs` | `1` 到 `2147483647` 的整数;非法值被忽略 | +| `KIMI_LOOP_MAX_STEPS_PER_TURN` | Agent 单轮最大步数,优先级高于 `config.toml` 的 `[loop_control] max_steps_per_turn`;`0` 表示无上限 | 非负整数;非法值被忽略 | +| `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP` | 单步失败后的最大总尝试次数(含首次尝试),优先级高于 `config.toml` 的 `[loop_control] max_attempts_per_step` | 非负整数;非法值被忽略 | +| `KIMI_CODE_INFINITE_RETRY` | 让所有失败的 LLM 请求无限重试而不是终止任务;指数退避(32 秒封顶)并尊重 `Retry-After`,等待期间中断仍生效 | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` | +| `KIMI_TOKEN_COUNTING_STRATEGY` | 对外上报的上下文 token 计数,优先级高于 `config.toml` 的 `[token_counting] strategy` | `measured+estimated`、`measured`、`estimated`(不区分大小写);非法值被忽略 | +| `KIMI_WEB_SEARCH_BASE_URL` | 网页搜索(`WebSearch`)服务的 API URL,优先级高于配置文件;凭据与自定义 header 不发往该端点 | 非空字符串;空白值被忽略 | | `KIMI_WEB_SEARCH_API_KEY` | 网页搜索(`WebSearch`)服务的 API 密钥;设置后同时替换配置中的 API 密钥和 OAuth 凭据 | 非空字符串;空白值被忽略 | -| `KIMI_WEB_FETCH_BASE_URL` | 网页抓取(`FetchURL`)服务的 API URL;优先级高于 `[services.moonshot_fetch] base_url`。文件中持久化的凭据和自定义 header 不会发送到环境变量指定的端点。环境变量和配置都没有指定端点时,已登录用户会先尝试 Kimi OAuth 托管抓取服务,再回退到本地直接请求 | 非空字符串;空白值被忽略 | +| `KIMI_WEB_FETCH_BASE_URL` | 网页抓取(`FetchURL`)服务的 API URL,优先级高于配置文件;未指定端点时已登录用户走 Kimi OAuth 托管抓取,再回退本地直连;凭据不发往该端点 | 非空字符串;空白值被忽略 | | `KIMI_WEB_FETCH_API_KEY` | 网页抓取(`FetchURL`)服务的 API 密钥;设置后同时替换配置中的 API 密钥和 OAuth 凭据 | 非空字符串;空白值被忽略 | -| `KIMI_CODE_EXPERIMENTAL_FLAG` | 在当前进程启用所有已注册的实验功能;单个功能的 `KIMI_CODE_EXPERIMENTAL_` 变量或 `config.toml` 的 `[experimental]` 节中的显式配置优先于它;不用于选择 Agent 引擎 | `1`、`true`、`yes`、`on` | -| `KIMI_CODE_LEGACY_FLAG` | 让 `kimi`、`kimi -p`、`kimi doctor`、`kimi export` 和 `kimi provider` 使用旧版 `agent-core` 引擎;这些命令默认使用 `agent-core-v2` | `1`、`true`、`yes`、`on` | +| `KIMI_CODE_EXPERIMENTAL_FLAG` | 在当前进程启用所有已注册的实验功能;不用于选择 Agent 引擎 | `1`、`true`、`yes`、`on` | +| `KIMI_CODE_LEGACY_FLAG` | 让 `kimi` 系列命令使用旧版 `agent-core` 引擎(默认 `agent-core-v2`) | `1`、`true`、`yes`、`on` | | `KIMI_SHELL_PATH` | Windows 上覆盖 Git Bash 路径(自动探测失败时使用) | 绝对路径 | | `KIMI_MODEL_MAX_COMPLETION_TOKENS` | 单步 LLM 请求的 `max_completion_tokens` 硬上限,仅对 `kimi` 供应商生效 | 正整数;`0` 或负数禁用 clamp | | `KIMI_MODEL_TEMPERATURE` | 每次请求的采样温度,仅对 `kimi` 供应商生效(全局生效,不依赖 `KIMI_MODEL_NAME`) | 数字,如 `0.3` | | `KIMI_MODEL_TOP_P` | 每次请求的核采样 `top_p`,仅对 `kimi` 供应商生效(全局生效) | 数字,如 `0.95` | -| `KIMI_MODEL_THINKING_EFFORT` | 在线上强制使用指定的思考强度(`thinking.effort`),绕过模型声明的 `support_efforts`;仅对 `kimi` 供应商生效,且仅在 Thinking 开启时注入 | 思考强度值,如 `max` | -| `KIMI_MODEL_THINKING_KEEP` | 保留思考透传;在 `kimi` 上以 `thinking.keep` 发送,在 `anthropic`(Claude 以及 Kimi 的 Anthropic 兼容模式)上以 `context_management` 的 `clear_thinking_20251015` 编辑发送(开启 keep 会让 Anthropic 请求走 beta Messages API);覆盖 `[thinking] keep`(其默认值为 `"all"`);仅在 Thinking 开启时注入 | API 接受的值,如 `all`;传入关值(`false`/`0`/`no`/`off`/`none`/`null`)可禁用 | -| `KIMI_CODE_NO_AUTO_UPDATE` | 完全禁用更新预检——不检查、不后台安装、不提示。同时兼容旧名 `KIMI_CLI_NO_AUTO_UPDATE` | 真值:`1`/`true`/`yes`/`on` | +| `KIMI_MODEL_THINKING_EFFORT` | 在线上强制使用指定的思考强度,绕过模型声明的 `support_efforts`;仅 `kimi` 供应商生效 | 思考强度值,如 `max` | +| `KIMI_MODEL_THINKING_KEEP` | 保留思考透传;`kimi` 以 `thinking.keep` 发送,`anthropic` 以 `clear_thinking_20251015` 编辑发送;覆盖 `[thinking] keep` | API 接受的值,如 `all`;传入关值(`false`/`0`/`no`/`off`/`none`/`null`)可禁用 | +| `KIMI_CODE_NO_AUTO_UPDATE` | 完全禁用更新预检:不检查、不后台安装、不提示。同时兼容旧名 `KIMI_CLI_NO_AUTO_UPDATE` | 真值:`1`/`true`/`yes`/`on` | | `KIMI_DISABLE_CRON` | 禁用定时任务工具(`CronCreate` 拒绝新计划,已有任务不触发) | `1` 表示禁用 | `KIMI_CODE_INFINITE_RETRY`、`KIMI_CODE_IDENTITY_*` 和 `KIMI_CODE_BUILTIN_PRODUCT_SKILLS` 这几个变量由默认的 `agent-core-v2` 引擎读取。设置 `KIMI_CODE_LEGACY_FLAG=1` 后,旧版 `kimi` / `kimi -p` 路径会忽略它们。 @@ -203,16 +203,22 @@ CLI 还会读取一些标准系统变量来检测运行环境,不会修改它 ## HTTP 代理 -Kimi Code 会遵循标准代理环境变量,让所有出网流量——模型 API 调用、MCP 服务、网络工具、遥测、登录、更新检查——都走代理: +Kimi Code 会遵循标准代理环境变量,让所有出网流量(模型 API 调用、MCP 服务、网络工具、遥测、登录、更新检查)都走代理: - `HTTP_PROXY` / `http_proxy`:用于 `http://` 请求的代理 - `HTTPS_PROXY` / `https_proxy`:用于 `https://` 请求的代理 -- `ALL_PROXY` / `all_proxy`:当对应 scheme 的变量未设置时使用的兜底代理;SOCKS 代理通常设在这里 +- `ALL_PROXY` / `all_proxy`:当对应 scheme 的变量未设置时使用的兜底代理 - `NO_PROXY` / `no_proxy`:以逗号分隔的、绕过代理的主机列表 -同时支持 HTTP(S) 代理和 SOCKS 代理。SOCKS 代理通过 scheme 识别——`socks5://`、`socks5h://`、`socks4://` 或 `socks://`(`socks5://` 的别名)——通常设在 `ALL_PROXY`(Clash、V2RayN 等工具使用的形式)。对 HTTP/HTTPS 流量,HTTP(S) 代理优先于 `ALL_PROXY`。 +### 代理类型与优先级 + +同时支持 HTTP(S) 代理和 SOCKS 代理。SOCKS 代理通过 scheme 识别:`socks5://`、`socks5h://`、`socks4://` 或 `socks://`(`socks5://` 的别名),通常设在 `ALL_PROXY`。对 HTTP/HTTPS 流量,HTTP(S) 代理优先于 `ALL_PROXY`。 + +### 启用条件与回环地址 + +仅当设置了其中任一变量时才启用代理,否则直连。回环地址(`localhost`、`127.0.0.1`、`::1`)始终绕过代理,因此配置了代理后,本地服务(例如 localhost 上的 MCP 服务)仍能正常工作。你也可以把自己的内网主机加入 `NO_PROXY` 一并放行。 -仅当设置了其中任一变量时才启用代理,否则直连。回环地址(`localhost`、`127.0.0.1`、`::1`)始终绕过代理,因此配置了代理后,本地服务(例如 localhost 上的 MCP 服务)仍能正常工作——你也可以把自己的内网主机加入 `NO_PROXY` 一并放行。 +### MCP 子进程 以 Node 子进程运行的 stdio MCP 服务,在其 Node 版本支持 `NODE_USE_ENV_PROXY` 时(Node ≥ 22.21 或 ≥ 24.5)会自动遵循 `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`;SOCKS 代理仅作用于 Kimi Code 自身的流量。 diff --git a/docs/zh/configuration/overrides.md b/docs/zh/configuration/overrides.md index 402c097a597..cdc792c62af 100644 --- a/docs/zh/configuration/overrides.md +++ b/docs/zh/configuration/overrides.md @@ -1,24 +1,24 @@ # 配置覆盖 -Kimi Code CLI 有三个地方可以影响运行参数:配置文件、命令行选项、环境变量。它们不是简单的"谁优先级高谁赢"——三者面向不同场景,作用范围互不相同: +Kimi Code CLI 有三个地方可以影响运行参数:配置文件、命令行选项、环境变量。三者并非简单的优先级叠加,而是面向不同场景、作用范围互不相同: - **配置文件** 保存长期偏好(模型、密钥、循环控制等),每次启动都生效 - **命令行选项** 做本次启动的临时切换,退出后失效 -- **环境变量** 主要负责数据目录定位、OAuth 端点切换,以及少数运行时开关——**不是配置字段的通用后备来源** +- **环境变量** 主要负责数据目录定位、OAuth 端点切换,以及少数运行时开关。它**不是配置字段的通用后备来源** -这个区别很关键:很多人会在 shell 里 `export KIMI_API_KEY=xxx`,以为 CLI 会自动取到,但实际上不会。原因见下文[供应商凭证](#供应商凭证)。 +凭证解析不读取 shell 环境变量:在终端 `export KIMI_API_KEY=xxx` 不会生效。原因见下文[供应商凭证](#供应商凭证)。 ## 环境变量的三类作用 环境变量按作用分三类,不能合并成一条线性优先级: 1. **定位配置文件**:`KIMI_CODE_HOME` 决定数据根目录,配置文件路径因此变为 `$KIMI_CODE_HOME/config.toml`。这一步先于其他所有解析,不是普通参数的后备来源。 -2. **运行时开关**:`KIMI_DISABLE_TELEMETRY` 等少量变量直接关闭对应子系统——即使 `config.toml` 里 `telemetry = true`,只要这个变量是真值,遥测就会被禁用。语义是"额外禁用",不是"普通覆盖"。 +2. **运行时开关**:`KIMI_DISABLE_TELEMETRY` 等少量变量直接关闭对应子系统。即使 `config.toml` 里 `telemetry = true`,只要这个变量是真值,遥测就会被禁用。语义是"额外禁用",不是"普通覆盖"。 3. **运行端点与诊断**:`KIMI_CODE_OAUTH_HOST`、`KIMI_CODE_BASE_URL`、`KIMI_LOG_LEVEL` 等在 OAuth 或日志子系统初始化时读取。完整列表见[环境变量](./env-vars.md)。 ## 普通运行参数的优先级 -对模型别名、Plan 模式、权限模式、Skills 目录等普通运行参数,优先级从高到低: +对模型别名、[Plan 模式](../guides/interaction.md#plan-模式)、[yolo 模式](../guides/interaction.md#三种权限模式)、Skills 目录等普通运行参数,优先级从高到低: 1. **命令行选项**(`-m`、`--plan`、`--yolo` 等):仅对本次启动生效 2. **用户配置文件**(`~/.kimi-code/config.toml`):保存长期偏好 @@ -26,10 +26,10 @@ Kimi Code CLI 有三个地方可以影响运行参数:配置文件、命令行 少数环境变量明确覆盖特定配置字段,例如 `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` 的优先级高于 `[background].keep_alive_on_exit`。这类例外在[环境变量](./env-vars.md)和[配置文件](./config-files.md)对应字段里都有标注。 ::: warning -**普通运行参数不会从 shell 环境变量取后备值。** 供应商的 `api_key` / `base_url` 只从 `config.toml`(包括 `[providers..env]` 子表)读取,不会回退到 shell 里 `export` 的变量。唯一的例外是显式的 `KIMI_MODEL_*` 通道——详见[用环境变量定义模型](./env-vars.md#用环境变量定义模型-kimi-model)。 +**普通运行参数不会从 shell 环境变量取后备值。** 供应商的 `api_key` / `base_url` 只从 `config.toml`(包括 `[providers..env]` 子表)读取,不会回退到 shell 里 `export` 的变量。唯一的例外是显式的 `KIMI_MODEL_*` 通道,详见[用环境变量定义模型](./env-vars.md#用环境变量定义模型kimi_model_)。 ::: -目前 CLI 只读取一份用户级配置文件,没有项目级配置文件机制。需要在不同项目间隔离配置时,用 `KIMI_CODE_HOME` 指向不同的数据目录——见下文[典型场景](#典型场景)。 +目前 CLI 只读取一份用户级配置文件,没有项目级配置文件机制。需要在不同项目间隔离配置时,用 `KIMI_CODE_HOME` 指向不同的数据目录,见下文[典型场景](#典型场景)。 ## 供应商凭证 @@ -37,15 +37,15 @@ Kimi Code CLI 有三个地方可以影响运行参数:配置文件、命令行 对单个供应商,凭证按以下顺序解析: -1. `[providers.].api_key` — 配置文件里直接写的密钥,优先级最高 -2. `[providers..env]` 子表里的对应键(`KIMI_API_KEY`、`ANTHROPIC_API_KEY` 等)— `api_key` 为空时才读这里 +1. `[providers.].api_key`:配置文件里直接写的密钥,优先级最高 +2. `[providers..env]` 子表里的对应键(`KIMI_API_KEY`、`ANTHROPIC_API_KEY` 等):`api_key` 为空时才读这里 3. 两者都缺 → 启动报错,提示该供应商缺少凭证 `base_url` 的解析方式相同:先读 `[providers.].base_url`,再读 `[providers..env]` 里的 `*_BASE_URL` 键。 -> `[providers..env]` 子表只是配置文件里的一段 TOML,不会真正写入 shell 环境变量。仅当对应的直接字段(`api_key` / `base_url`)为空时,CLI 才会查这里。 +> `[providers..env]` 子表只是配置文件里的一段 TOML,不会真正写入 shell 环境变量。仅当对应的直接字段(`api_key` / `base_url`)为空时,CLI 才会读取该子表。 -完整的凭证键名列表见[环境变量:供应商凭证键](./env-vars.md#供应商凭证键-写在-config-toml-里)。 +完整的凭证键名列表见[环境变量:供应商凭证键](./env-vars.md#供应商凭证键写在-configtoml-里)。 ## 命令行选项 @@ -55,8 +55,8 @@ Kimi Code CLI 有三个地方可以影响运行参数:配置文件、命令行 | --- | --- | | `-S, --session [id]` | 恢复指定会话;不带 id 时进入交互式选择 | | `-c, --continue` | 续上当前目录的上一次会话 | -| `-y, --yolo` | "Ask When Needed" 模式:常规修改和命令自动完成,Agent 仍可能提问 | -| `--auto` | "Never Ask" 模式:完全不打断,Agent 不会向用户提问 | +| `-y, --yolo` | 自动批准普通工具调用,Agent 仍可能提问 | +| `--auto` | 以 auto 权限模式启动:完全自主,Agent 不会向用户提问 | | `--plan` | 以 Plan 模式启动 | | `-m, --model ` | 指定本次使用的模型别名 | | `-p, --prompt ` | 非交互模式:执行单条提示词后退出 | @@ -76,13 +76,13 @@ Kimi Code CLI 有三个地方可以影响运行参数:配置文件、命令行 ## 典型场景 -**隔离测试环境**——用单独的数据目录,避免污染主配置和会话: +**隔离测试环境**:用单独的数据目录,避免污染主配置和会话: ```sh KIMI_CODE_HOME="$PWD/.kimi-sandbox" kimi ``` -**一次性使用测试密钥**——由于供应商凭证只从配置文件读,把测试密钥写进 `env` 子表: +**一次性使用测试密钥**:由于供应商凭证只从配置文件读,把测试密钥写进 `env` 子表: ```toml [providers.kimi.env] diff --git a/docs/zh/configuration/providers.md b/docs/zh/configuration/providers.md index f97df28030b..87755927a3c 100644 --- a/docs/zh/configuration/providers.md +++ b/docs/zh/configuration/providers.md @@ -1,6 +1,6 @@ # 平台与模型 -Kimi Code CLI 支持同时接入多家 LLM 平台——用 Kimi Code 托管服务一键登录、用 Anthropic API key 接 Claude、用 OpenAI 兼容协议连接第三方推理服务。每个供应商对应一种 API 协议,模型在供应商之上声明自己的名称、上下文长度和能力。本页介绍如何在 `config.toml` 里配置各种供应商。 +Kimi Code CLI 支持同时接入多家模型供应商服务,模型在供应商之上声明自己的名称、上下文长度和能力。本页介绍如何在 `config.toml` 里配置各种供应商。 ## 支持的供应商类型 @@ -8,21 +8,23 @@ Kimi Code CLI 支持同时接入多家 LLM 平台——用 Kimi Code 托管服 | 类型 | 协议 | 典型用途 | | --- | --- | --- | -| `kimi` | OpenAI 兼容 | Kimi Code 托管服务、Kimi Platform API 密钥 | -| `anthropic` | Anthropic Messages | Claude 系列模型 | -| `openai` | OpenAI Chat Completions | OpenAI 及兼容服务、DeepSeek、Qwen 等 | -| `openai_responses` | OpenAI Responses API | OpenAI 较新的 Responses 接口 | -| `google-genai` | Google GenAI | Gemini API | -| `vertexai` | Google GenAI on Vertex | Google Cloud Vertex AI | +| [`kimi`](#kimi) | OpenAI 兼容 | Kimi Code 托管服务、Kimi Platform API 密钥 | +| [`anthropic`](#anthropic) | Anthropic Messages | Claude 系列模型 | +| [`openai`](#openai) | OpenAI Chat Completions | OpenAI 及兼容服务、DeepSeek、Qwen 等 | +| [`openai_responses`](#openai_responses) | OpenAI Responses API | OpenAI 较新的 Responses 接口 | +| [`google-genai`](#google-genai) | Google GenAI | Gemini API | +| [`vertexai`](#vertexai) | Google GenAI on Vertex | Google Cloud Vertex AI | 所有供应商默认以流式方式与模型交互。thinking、视觉、工具调用等能力按模型名前缀自动匹配,通常不需要手动声明。 -**凭证优先级**:`api_key` 直接字段 > `[providers..env]` 子表键 > 两者都缺时启动报错。CLI 不会从 shell 环境变量自动取凭证——详见[配置覆盖:供应商凭证](./overrides.md#供应商凭证)。 +**凭证优先级**:`api_key` 直接字段 > `[providers..env]` 子表键 > 两者都缺时启动报错。CLI 不会从 shell 环境变量自动取凭证,详见[配置覆盖:供应商凭证](./overrides.md#供应商凭证)。 ## `/provider` — 交互式供应商管理 不想手动编辑 TOML?在 TUI 里输入 `/provider` 打开**供应商管理器**,可以以交互方式添加或删除供应商。 +![/provider 供应商管理器](../../media/provider-manager.jpg) + 管理器按来源把供应商显示为一行行条目。操作方式: - ↑/↓ 移动光标,←/→ 翻页 @@ -134,7 +136,7 @@ base_url = "https://your-gateway.example" 与 `google-genai` 共用实现,`type = "vertexai"` 时切换到 Vertex AI 访问路径。 -认证走 Google Cloud 标准 ADC 流程(`gcloud auth application-default login` 或 `GOOGLE_APPLICATION_CREDENTIALS` 服务账号 JSON),这部分与 Kimi Code 无关。**项目 ID 和区域必须写在 `[providers.vertexai.env]` 子表里**——直接在 shell 里 `export GOOGLE_CLOUD_PROJECT` 不会被 CLI 读取。 +认证走 Google Cloud 标准 ADC 流程(`gcloud auth application-default login` 或 `GOOGLE_APPLICATION_CREDENTIALS` 服务账号 JSON),这部分与 Kimi Code 无关。**项目 ID 和区域必须写在 `[providers.vertexai.env]` 子表里**。直接在 shell 里 `export GOOGLE_CLOUD_PROJECT` 不会被 CLI 读取。 ```toml [providers.vertexai] @@ -150,11 +152,8 @@ gcloud auth application-default login # 一次性完成认证 kimi ``` -如需让 Vertex 请求走自定义(如代理)端点,可设置 `base_url`(或 `GOOGLE_VERTEX_BASE_URL` 环境变量);不填时使用 SDK 默认的区域化 `*-aiplatform.googleapis.com` 地址。与 `google-genai` 一样,只填主机根地址——SDK 会自行追加 `/v1beta1/publishers/google/models/…`。 - -## OAuth 与凭证注入 +如需让 Vertex 请求走自定义(如代理)端点,可设置 `base_url`(或 `GOOGLE_VERTEX_BASE_URL` 环境变量);不填时使用 SDK 默认的区域化 `*-aiplatform.googleapis.com` 地址。与 `google-genai` 一样,只填主机根地址。SDK 会自行追加 `/v1beta1/publishers/google/models/…`。 -Kimi Code 托管服务使用 OAuth 而非静态 API 密钥。运行 `/login` 后,内置的认证工具链会自动写入并刷新凭证,`config.toml` 里无需手动配置这部分内容。 ## 下一步 diff --git a/docs/zh/customization/agents.md b/docs/zh/customization/agents.md index 7d8d119aba6..cb849ff923b 100644 --- a/docs/zh/customization/agents.md +++ b/docs/zh/customization/agents.md @@ -1,6 +1,6 @@ # Agent 与 subagent -Kimi Code CLI 中的每次会话都由一个**main agent** 驱动。main agent 理解用户意图、规划步骤、调用工具,并在需要时向外派发**subagent** 处理更聚焦的子任务——例如探索一个陌生代码库、并行审阅多处实现、或在不触碰主上下文的情况下规划一次大型重构。 +Kimi Code CLI 中的每次会话都由一个 **main agent** 驱动。main agent 理解用户意图、规划步骤、调用工具,并在需要时向外派发 **subagent** 处理更聚焦的子任务:探索一个陌生代码库、并行审阅多处实现、或在不触碰主上下文的情况下规划一次大型重构。 subagent 接受 main agent 给出的任务描述,在自己的独立上下文里工作,最后把结论返回。它不会与用户直接对话,中间的思考和工具调用记录也不会混入 main agent 的历史。 @@ -12,13 +12,21 @@ Kimi Code CLI 内置三种 subagent,开箱即用,分别面向不同任务形 - **`explore`**:代码库探索专用,只做只读操作,不修改任何文件。适合在不改动文件的前提下快速搜索、阅读和总结仓库。 - **`plan`**:实现规划与架构设计专用,连 Shell 命令都不提供,专注于"想清楚怎么做"而不是"动手做"。 -`coder` subagent 与 main agent 共享大部分工具集:可以在后台执行 Shell 命令、维护待办列表、进入 Plan 模式、调用 Agent Skills。内置 subagent 都不能继续派发新的 subagent。自定义 Agent 缺省时继承内置委派列表(`coder`、`explore`、`plan`),而这些内置类型自身同样不能再派发,因此委派链默认必然终止——不存在不受限的递归派发。自定义 Agent 可以通过显式声明 [`subagents`](#agent-文件格式) 列表来获得更深的委派链。如果 subagent 结束自己的轮次时仍有后台任务在运行,那么只有在这些后台任务全部落定后,这次运行才会回报完成——main agent 拿到结果时,背后的工作也已经真正完成。 +三种类型之外,使用 subagent 还有三条约定,分别关于工具边界、委派深度和完成时机: + +`coder` subagent 与 main agent 共享大部分工具集:可以在后台执行 Shell 命令、维护待办列表、进入 Plan 模式、调用 Agent Skills。三种内置 subagent 都不能继续派发新的 subagent。 + +自定义 Agent 缺省时继承内置委派列表(`coder`、`explore`、`plan`),这些内置类型自身不能再派发,因此委派链默认必然终止,不存在不受限的递归派发。如需更深的委派链,可以在 Agent 文件中显式声明 [`subagents`](#agent-文件格式) 列表。 + +如果 subagent 结束自己的轮次时仍有后台任务在运行,这次运行会等这些后台任务全部落定后才回报完成。main agent 拿到结果时,背后的工作也已经真正完成。 ## 调用方式 -subagent 由 main agent 自动调度——根据任务复杂度、上下文消耗和子任务的独立性,在适当时机派发,无需用户手动指定。 +调度的完整链路只有三个环节:派发、审批、回收,都不需要手动管理。 + +subagent 由 main agent 自动调度:根据任务复杂度、上下文消耗和子任务的独立性,在适当时机派发,无需用户手动指定。 -每次派发都会在终端以审批请求的形式呈现(除非命中 allow 规则或处于 "Ask When Needed" 模式),方便你审视任务描述。你也可以在对话中直接指示 main agent 使用特定 subagent,例如"先用 explore 把相关文件梳理一遍再动手"。 +每次派发都会在终端以审批请求的形式呈现,方便你审视任务描述,除非你已用 allow 规则放行或处于 YOLO 模式。你也可以在对话中直接指示 main agent 使用特定 subagent,例如"先用 explore 把相关文件梳理一遍再动手"。 subagent 支持在后台运行:完成后结果自动回到 main agent,无需手动轮询。也可以唤回已有的 subagent 实例继续推进同一任务。 @@ -31,7 +39,7 @@ subagent 支持在后台运行:完成后结果自动回到 main agent,无需 - **main agent 上下文保持精炼**,长会话中不会被大量探索性日志撑满。 - **多个 subagent 可以并行运行**,互不干扰。 -需要注意的是,每个 subagent 都会独立消耗模型 token。简单任务没有必要派发 subagent,main agent 直接处理更经济。 +每个 subagent 都会独立消耗模型 token。简单任务没有必要派发 subagent,由 main agent 直接处理更经济。 ## 权限继承 @@ -41,19 +49,23 @@ subagent 的权限规则继承自 main agent:main agent 通过 `/permission` ## 自定义 Agent -除了三个内置 subagent,你还可以用 Markdown 文件定义自己的 Agent。每个文件描述一个 Agent:文件顶部的 Frontmatter(YAML 元数据)声明名称、描述和工具权限,文件正文是它的系统提示词。自定义 Agent 可以作为 subagent 被委派 —— main agent 会自动发现它们,与内置 subagent 并列 —— 也可以在启动时选为 main agent。 +除了三个内置 subagent,你还可以用 Markdown 文件定义自己的 Agent。每个文件描述一个 Agent:文件顶部的 Frontmatter 声明名称、描述和工具权限,文件正文是它的系统提示词。 + +自定义 Agent 可以作为 subagent 被委派:main agent 会自动发现它们,与内置 subagent 并列。自定义 Agent 也可以在启动时选为 main agent。 ### Agent 目录 Kimi Code CLI 按作用域发现 Agent 文件,作用域越具体,优先级越高:**显式(`--agent-file`)> 项目 > 额外 > 用户 > Plugin > 内置**。两个文件定义了相同的 `name` 时,高优先级作用域胜出。每个目录都会递归扫描 `.md` 文件。 **用户级**(对所有项目生效): + - `$KIMI_CODE_HOME/agents/`(默认:`~/.kimi-code/agents/`) - `~/.agents/agents/` Kimi 专属的用户 Agent 目录随 `KIMI_CODE_HOME` 移动,通用的 `~/.agents/agents/` 目录留在真实用户目录下,便于跨工具共享。 -**项目级**(项目根目录 = 从工作目录向上查找、最近的包含 `.git` 的目录): +**项目级**:项目根目录指从工作目录向上查找、最近的包含 `.git` 的目录。可用位置: + - `.kimi-code/agents/` - `.agents/agents/` @@ -63,12 +75,14 @@ Kimi 专属的用户 Agent 目录随 `KIMI_CODE_HOME` 移动,通用的 `~/.age extra_agent_dirs = ["~/team-agents", ".agents/team-agents"] ``` -**Plugin 级**:已启用 plugin 在其 manifest 的 `agents` 字段中声明的目录(省略时自动采用 plugin 根下的 `agents/` 目录),见[插件 Agent](./plugins.md#插件-agent)。Plugin Agent 优先级仅高于内置 Agent。 +**Plugin 级**:已启用 plugin 在其 manifest 的 `agents` 字段中声明的目录,省略时自动采用 plugin 根下的 `agents/` 目录,见 [插件 Agent](./plugins.md#插件-agent)。Plugin Agent 优先级仅高于内置 Agent。 -**内置 Agent** 随 CLI 分发,优先级最低。目录中发现的文件不会仅凭同名覆盖内置 Agent;如确需替换,必须在 Frontmatter 中声明 `override: true`。通过 `--agent-file` 加载的文件视为显式启动意图,可以覆盖同名内置 Agent,优先级高于所有目录作用域,且仅对本次启动生效。另外,`$KIMI_CODE_HOME/SYSTEM.md` 可永久覆盖默认 main agent 的系统提示词(它不参与 Agent 文件发现),其优先级交互见下文 SYSTEM.md 小节。 +**内置 Agent** 随 CLI 分发,优先级最低。目录中发现的文件不会仅凭同名覆盖内置 Agent;如确需替换,必须在 Frontmatter 中声明 `override: true`。通过 `--agent-file` 加载的文件视为显式启动意图,可以覆盖同名内置 Agent,优先级高于所有目录作用域,且仅对本次启动生效。 + +另外,`$KIMI_CODE_HOME/SYSTEM.md` 可永久覆盖默认 main agent 的系统提示词,它不参与 Agent 文件发现,优先级交互见 [SYSTEM.md 小节](#用-systemmd-覆盖-main-agent-的系统提示词)。 ::: warning 信任模型 -Agent 文件属于提示词配置,而项目级文件来自仓库本身 —— 包括你刚刚 clone、尚不可信的仓库。项目作用域的文件可以完全接管内置 Agent:命名为 `agent.md` 并声明 `override: true` 会替换**默认 main agent 的整个系统提示词**,`coder.md` 加 `override: true` 则会替换默认 subagent 类型。与 `AGENTS.md` 内容(作为参考资料注入提示词)不同,override 文件**就是**系统提示词本身,且不写 `tools` 的文件保留全部工具。在不熟悉的仓库中运行 Kimi Code 之前,请以对待脚本同样的谨慎检查其中的 `.kimi-code/agents/` 与 `.agents/agents/` 目录。 +Agent 文件属于提示词配置,而项目级文件来自仓库本身,包括你刚刚 clone、尚不可信的仓库。项目作用域的文件可以完全接管内置 Agent:命名为 `agent.md` 并声明 `override: true` 会替换**默认 main agent 的整个系统提示词**,`coder.md` 加 `override: true` 则会替换默认 subagent 类型。不同于把 `AGENTS.md` 内容作为参考资料注入提示词,override 文件本身就是系统提示词,且不写 `tools` 的文件保留全部工具。在不熟悉的仓库中运行 Kimi Code 之前,请以对待脚本同样的谨慎检查其中的 `.kimi-code/agents/` 与 `.agents/agents/` 目录。 ::: ### Agent 文件格式 @@ -93,23 +107,29 @@ disallowedTools: 你是严格的代码审查者。阅读 diff 后,按严重度分级报告问题…… ``` +各字段的含义如下: + | 字段 | 必填 | 说明 | | --- | --- | --- | -| `name` | 否 | kebab-case 唯一标识。缺省时取文件名(去掉扩展名,如 `review.md` → `review`);解析后名字缺失或不是 kebab-case 的文件会被跳过并告警 | +| `name` | 否 | kebab-case 唯一标识。缺省时取文件名去掉扩展名后的部分;名字缺失或不是 kebab-case 的文件会被跳过并告警 | | `description` | 是 | Agent 的用途。main agent 挑选 subagent 时会看到,请围绕委派决策来写 | | `whenToUse` | 否 | 补充说明何时应使用该 Agent | | `override` | 否 | 是否允许覆盖同名内置 Agent,默认 `false`。`--agent-file` 属于显式启动意图,无需设置此字段 | -| `tools` | 否 | 工具名允许列表,如 `Read`、`Bash`;MCP 工具用 glob 匹配,如 `mcp__github__*`。支持 YAML 列表或逗号分隔字符串(`tools: Read, Grep`)两种写法。缺省表示允许全部工具;单独的 `*` 同样表示允许全部工具;空列表(`tools: []`)表示禁用全部工具 | -| `disallowedTools` | 否 | 禁止列表,写法与匹配规则相同,在 `tools` 之后应用 | -| `subagents` | 否 | 允许委派的 subagent 名称列表,写法与 `tools` 相同(YAML 列表或逗号分隔字符串)。缺省表示继承默认 Agent 的委派列表(内置默认为 `coder`、`explore`、`plan`,它们自身都不能再派发,因此继承得到的链路必然终止);单独的 `*` 表示可委派所有类型。main agent 的有效委派列表还会自动并入所有发现的自定义 Agent,因此自定义 Agent 默认即可被委派 | +| `tools` | 否 | 工具允许列表。MCP 工具用 glob 匹配(如 `mcp__github__*`);支持 YAML 列表或逗号分隔字符串。缺省或单独的 `*` 表示允许全部工具,空列表表示禁用全部工具 | +| `disallowedTools` | 否 | 工具禁止列表,写法与匹配规则和 `tools` 相同,在 `tools` 之后应用 | +| `subagents` | 否 | 允许委派的 subagent 名称列表,写法与 `tools` 相同。缺省继承内置默认委派列表,单独的 `*` 表示可委派所有类型。main agent 的有效委派列表会自动并入所有发现的自定义 Agent | + +内置工具与用户工具按名称精确匹配(区分大小写);以 `mcp__` 开头的条目按 glob 匹配 MCP 工具。以下三种写法永远匹配不到任何工具,在 profile 生效时会给出警告: -内置工具与用户工具按名称精确匹配(区分大小写);以 `mcp__` 开头的条目按 glob 匹配 MCP 工具。有三种写法永远匹配不到任何工具,在 profile 生效时会给出警告:`mcp__` 模式之外使用通配符(`disallowedTools` 里单独的 `*` 什么也禁不掉);不是完整 `mcp__<服务器>__<工具>` 形式的 `mcp__` 字面量(`mcp__github` 匹配不到任何工具 —— 匹配整个服务器要用 `mcp__github__*`);以及任何已注册或内置工具都没有的名字(通常是笔误,如把 `Read` 写成 `read`)。 +- 在 `mcp__` 模式之外使用通配符:`disallowedTools` 里单独的 `*` 什么也禁不掉。 +- 写不全的 `mcp__` 字面量:`mcp__github` 匹配不到任何工具;匹配整个服务器要用 `mcp__github__*`。 +- 任何已注册或内置工具都没有的名字:通常是笔误,如把 `Read` 写成 `read`。 -正文即 Agent 的系统提示词,每次构建提示词时都会作为模板渲染:`${var}` 占位符替换为实时上下文值——未知变量保持原样,单独的 `$` 没有特殊含义,上下文中缺失的变量渲染为空字符串。`${base_prompt}` 会在你放置它的位置嵌入有效默认系统提示词(内置默认,或存在时为你的 `SYSTEM.md` 覆盖),因此文件可以"包裹"默认行为而不是替换它。如果文件会替换默认提示词、但仍要保留已启用 plugin 提供的指令,请把 `${plugin_sections}` 放在希望出现这些指令的位置。可用变量见下文 SYSTEM.md 变量表。 +正文即 Agent 的系统提示词,每次构建提示词时都会作为模板渲染。`${var}` 占位符替换为实时上下文值:未知变量保持原样,单独的 `$` 没有特殊含义,上下文中缺失的变量渲染为空字符串。`${base_prompt}` 会在放置它的位置嵌入有效默认系统提示词(内置默认,或存在时为你的 `SYSTEM.md` 覆盖),因此文件可以包裹默认行为而不是替换它。如果文件替换默认提示词后仍要保留已启用 plugin 提供的指令,把 `${plugin_sections}` 放在希望出现这些指令的位置即可。可用变量见 [SYSTEM.md 变量表](#用-systemmd-覆盖-main-agent-的系统提示词)。 -未知字段会被忽略,新版本写的文件在旧版本上仍可读取。其他 Agent 工具的字段(如 Claude Code 的 `model`、OpenCode 的 `mode`)同样会被忽略;加上 `tools` 的逗号分隔写法和 `name` 缺省回退到文件名,Claude Code 与 OpenCode 风格的 Agent 文件一般可直接加载 —— 只含 `description` 和正文的最小文件可跨工具通用。 +未知字段会被忽略,新版本写的文件在旧版本上仍可读取。其他 Agent 工具的字段(如 Claude Code 的 `model`、OpenCode 的 `mode`)同样会被忽略。加上 `tools` 的逗号分隔写法和 `name` 缺省回退到文件名,Claude Code 与 OpenCode 风格的 Agent 文件一般可直接加载,只含 `description` 和正文的最小文件可跨工具通用。 -目录中发现的非法文件会被跳过并告警,不影响其他文件。通过 `--agent-file` 显式传入的文件必须合法 —— 否则 CLI 会报错并退出。 +目录中发现的非法文件会被跳过并告警,不影响其他文件。通过 `--agent-file` 显式传入的文件必须合法,否则 CLI 会报错并退出。 ::: warning 注意 `tools` 与 `disallowedTools` 不仅决定模型能"看到"哪些工具,还会在执行前再次强制检查。`subagents` 同样双重生效:`Agent` 工具的类型列表只包含允许委派的 subagent,`Agent` 与 `AgentSwarm` 在实际派发前都会强制校验;唤回已有 subagent 不受此限制。权限规则仍是独立的控制层,用于决定哪些操作需要审批。 @@ -124,7 +144,7 @@ disallowedTools: - **`--agent `**:以指定 Agent 作为 main agent 启动会话。名称可以指向内置 Agent 或任何已发现的文件;名称不存在时会报错,并列出可用的 Agent。 - **`--agent-file `**:以最高优先级加载一个 Agent 文件(仅本次启动)并以其启动。该 flag 只接受一个文件:不可重复传入,也不能与 `--agent` 同时使用。 -两个 flag 都仅在新建会话时有效——都不能与 `--session`/`--continue` 组合。Agent 在会话创建时绑定,恢复会话时会自动还原已绑定的 Agent,因此恢复时不需要(也不允许)携带这些 flag。 +两个 flag 都仅在新建会话时有效,不能与 `--session`/`--continue` 组合。Agent 在会话创建时绑定,恢复会话时会自动还原已绑定的 Agent,因此恢复时不需要(也不允许)携带这些 flag。 例如: @@ -133,17 +153,23 @@ kimi --agent reviewer kimi -p --agent reviewer "审查这个分支上的改动" ``` -绑定的 Agent 即会话的身份:在会话首次绑定后即固定,之后不可切换。在 TUI 中,这些 flag 只绑定启动时的会话;之后在同一进程内新建的会话(例如通过 `/new`)使用默认 Agent。 +绑定的 Agent 即会话的身份,在会话首次绑定后即固定,之后不可切换。在 TUI 中,这些 flag 只绑定启动时的会话;之后在同一进程内新建的会话(例如通过 `/new`)使用默认 Agent。 -定制 main agent 时,在正文中引用 `${base_prompt}` 可保持有效默认提示词中已有的环境、工作区指令、Skill 和 plugin 注入生效。如果要替换默认提示词、但只保留 plugin 提供的指令,请改用 `${plugin_sections}`。正文同时不引用 `${base_prompt}` 和 `${plugin_sections}` 时,会完全拥有自己的提示词并排除 plugin 指令,适合自包含的 subagent。 +定制 main agent 时,在正文中引用 `${base_prompt}` 可保留有效默认提示词中已有的环境、工作区指令、Skill 和 plugin 注入。要替换默认提示词、但只保留 plugin 提供的指令,改用 `${plugin_sections}`。正文同时不引用这两个变量时,Agent 拥有完全独立的提示词,plugin 指令不会注入,适合自包含的场景。 ### 用 SYSTEM.md 覆盖 main agent 的系统提示词 -希望永久覆盖 main agent 的系统提示词、而不必每次启动都传入 `--agent` 或 `--agent-file` 时,可以写一份 `$KIMI_CODE_HOME/SYSTEM.md`(默认:`~/.kimi-code/SYSTEM.md`,随 `KIMI_CODE_HOME` 移动)。文件存在且非空期间,它整体替换内置默认 main agent 的系统提示词——但只替换提示词,描述、工具集与允许委派的 subagent 列表仍沿用内置默认值。SYSTEM.md 在包括交互式 TUI 会话在内的所有启动方式下生效。 +希望永久覆盖 main agent 的系统提示词、而不必每次启动都传入 `--agent` 或 `--agent-file` 时,可以写一份 `$KIMI_CODE_HOME/SYSTEM.md`,默认位置为 `~/.kimi-code/SYSTEM.md`,随 `KIMI_CODE_HOME` 移动。文件存在且非空期间,它整体替换内置默认 main agent 的系统提示词;但只替换提示词,描述、工具集与允许委派的 subagent 列表仍沿用内置默认值。SYSTEM.md 在包括交互式 TUI 会话在内的所有启动方式下生效。 -SYSTEM.md 是纯 Markdown 正文,不需要也不读取 Frontmatter。文件缺失或为空时不生效;读取失败时会告警并回退到内置提示词。优先级上,显式意图仍然胜出:项目作用域中声明了 `override: true` 的同名 Agent 文件、通过 `--agent-file` 传入的文件都排在 SYSTEM.md 之前,用 `--agent` 选择其他 Agent 时 SYSTEM.md 也不会生效;而在用户作用域内部,SYSTEM.md 优先于 `agents/` 目录中扫描到的同名文件。 +SYSTEM.md 是纯 Markdown 正文,不需要也不读取 Frontmatter。文件缺失或为空时不生效;读取失败时会告警并回退到内置提示词。 -与普通 Agent 文件的正文一样,SYSTEM.md 在每次构建提示词时作为模板渲染——正文中的 `${var}` 占位符会被替换为实时上下文: +优先级上,显式意图仍然胜出: + +- 项目作用域中声明了 `override: true` 的同名 Agent 文件、通过 `--agent-file` 传入的文件都排在 SYSTEM.md 之前。 +- 用 `--agent` 选择其他 Agent 时,SYSTEM.md 不生效。 +- 在用户作用域内部,SYSTEM.md 优先于 `agents/` 目录中扫描到的同名文件。 + +与普通 Agent 文件的正文一样,SYSTEM.md 在每次构建提示词时作为模板渲染,正文中的 `${var}` 占位符会被替换为实时上下文: | 变量 | 内容 | | --- | --- | @@ -153,11 +179,14 @@ SYSTEM.md 是纯 Markdown 正文,不需要也不读取 Frontmatter。文件缺 | `${cwd_listing}` | 工作目录的文件列表 | | `${os}` | 操作系统类型 | | `${shell}` | Shell 名称与路径,例如 `bash (\`/bin/bash\`)` | +| `${now}` | 当前时间(ISO 格式) | | `${additional_dirs_info}` | 加入工作区的额外目录信息;没有时为空 | -| `${base_prompt}` | 默认系统提示词。在 `SYSTEM.md` 中指内置默认提示词;在 Agent 文件中指有效默认提示词(内置默认,或存在时为你的 `SYSTEM.md` 覆盖) | +| `${base_prompt}` | 默认系统提示词。在 `SYSTEM.md` 中指内置默认提示词;在 Agent 文件中指有效默认提示词(内置默认,或存在时的 `SYSTEM.md` 覆盖) | | `${plugin_sections}` | 已启用 plugin 提供的完整 Plugin Instructions 块;没有已启用 plugin 提供指令时为空 | -未知变量原样保留,单独的 `$` 没有特殊含义;上下文中缺失的变量渲染为空字符串。另有四个预组合块——`${windows_notes}`、`${additional_dirs_section}`、`${skills_section}`、`${plugin_sections}`——渲染对应的内置提示词段落,不适用时为空字符串。内置默认提示词已经包含 `${plugin_sections}`;当 `${base_prompt}` 已展开为该提示词时,不要再重复加入此变量。利用这些变量可以重建内置提示词的骨架,例如: +未知变量原样保留,单独的 `$` 没有特殊含义;上下文中缺失的变量渲染为空字符串。另有四个预组合块 `${windows_notes}`、`${additional_dirs_section}`、`${skills_section}`、`${plugin_sections}`,渲染对应的内置提示词段落,不适用时为空字符串。 + +内置默认提示词已经包含 `${plugin_sections}`;当 `${base_prompt}` 已展开为该提示词时,不要再重复加入此变量。利用这些变量可以重建内置提示词的骨架,例如: ```markdown You are Kimi, running at ${cwd} on ${os}. diff --git a/docs/zh/customization/hooks.md b/docs/zh/customization/hooks.md index b23ec914314..6ca70e94e4e 100644 --- a/docs/zh/customization/hooks.md +++ b/docs/zh/customization/hooks.md @@ -10,14 +10,14 @@ Hooks(钩子)是一种自动触发机制:你预先告诉 Kimi Code CLI"每 配置一条 hook 规则,需要指定三件事:**在什么事件上触发**、**匹配哪些目标**、**运行哪个脚本**。 -触发时,CLI 会把事件的详细信息(触发原因、工具名称、命令内容等)打包成 JSON(一种结构化文本格式),通过**标准输入**(stdin,程序运行时用来接收外部数据的通道)传给你的脚本。脚本读取这些信息后,决定怎么响应。 +触发时,CLI 会把事件的详细信息(触发原因、工具名称、命令内容等)打包成 JSON,通过**标准输入**(stdin,程序运行时用来接收外部数据的通道)传给脚本。脚本读取这些信息后,决定怎么响应。 脚本的响应结果由两样东西决定: - **退出码**(exit code,程序结束时向操作系统报告的状态数字):`0` 表示放行,`2` 表示阻断,其他数字默认放行 -- **标准输出**(stdout,就是你用 `console.log` 或 `print` 打印出来的内容):可以附带说明文字 +- **标准输出**(stdout,脚本打印到终端的内容):可以附带说明文字 -即使脚本报错、超时,CLI 也**不会因此中断你的工作**——这种"出错就放行"的设计叫 fail-open(失败开放),避免 hook 异常变成绊脚石。 +即使脚本报错或超时,CLI 也**不会因此中断你的工作**。这种"出错就放行"的设计称为 fail-open(失败开放),避免 hook 异常阻塞主流程。 ::: warning 注意 正因为 fail-open,Hooks 适合做提醒和轻量拦截,但**不应作为唯一的安全防线**。对真正高风险的操作,仍需依赖权限审批和人工确认。 @@ -39,11 +39,11 @@ command = "terminal-notifier -title Kimi -message 'Task done'" ## 配置 -所有 hook 规则写在 `~/.kimi-code/config.toml` 的 `[[hooks]]` 数组里,每一项是一条规则: +所有 hook 规则写在 `~/.kimi-code/config.toml` 的 `[[hooks]]` 数组里: | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | -| `event` | `string` | 是 | 触发事件名,必须是下文「事件一览」表中的某一项 | +| `event` | `string` | 是 | 触发事件名,取值见 [事件一览](#事件一览) | | `matcher` | `string` | 否 | 用正则表达式(一种字符串匹配语法)过滤事件目标;不填则匹配全部 | | `command` | `string` | 是 | 触发时要运行的 Shell 命令 | | `timeout` | `integer` | 否 | 超时秒数,范围 1–600;默认 30 秒 | @@ -52,7 +52,14 @@ command = "terminal-notifier -title Kimi -message 'Task done'" **同一事件匹配多条规则时**,所有命中的 hook 并行运行;`command` 完全相同的多条规则只运行一次。 -Hook 命令的工作目录是当前会话的项目目录。非 Windows 平台上,hook 进程放在独立进程组里,超时时先发信号让它有机会善后,之后才强制终止。 +Hook 命令的工作目录是当前会话的项目目录。 + +
+进程组与超时处理 + +非 Windows 平台上,hook 进程运行在独立进程组中;超时后 CLI 先发送信号让脚本有机会善后,再强制终止。 + +
### 事件数据格式 @@ -68,7 +75,7 @@ Hook 命令的工作目录是当前会话的项目目录。非 Windows 平台上 } ``` -具体事件还会附带额外字段(如工具名称、命令内容),见下方事件一览。所有字段名使用下划线命名(snake_case)。 +具体事件还会附带额外字段(如工具名称、命令内容),见 [事件一览](#事件一览)。所有字段名使用下划线命名(snake_case)。 ## 返回值 @@ -92,38 +99,38 @@ Hook 命令的工作目录是当前会话的项目目录。非 Windows 平台上 } ``` -::: info 哪些事件支持阻断? -只有**可阻断事件**(`PreToolUse`、`Stop`、`UserPromptSubmit`)的返回值会影响主流程。其余事件属于**观察型事件**——触发后即发即忘,不管脚本返回什么,主流程都不会改变。 +::: info 说明 +只有**可阻断事件**(`PreToolUse`、`Stop`、`UserPromptSubmit`)的返回值会影响主流程。其余事件属于**观察型事件**:触发后即发即忘,不管脚本返回什么,主流程都不会改变。 ::: ## 事件一览 | 事件 | Matcher 匹配的是 | 会触发阻断? | 说明 | | --- | --- | --- | --- | -| `UserPromptSubmit` | 用户提交的文本内容 | ✓ | 用户发送消息时触发;返回文本会附加到上下文;若阻断,本轮不调用模型 | -| `UserPromptQueued` | 排队消息的文本内容 | — | 上一回合仍在运行、消息进入队列时触发;payload 含 `prompt_id`、`prompt` 和 `queue_length`(观察用) | -| `PreToolUse` | 工具名 | ✓ | 工具调用前触发(权限检查前);阻断后工具不会执行 | +| `UserPromptSubmit` | 用户提交的文本内容 | ✓ | 用户发送消息时触发;返回文本会附加到上下文,阻断则本轮不调用模型 | +| `UserPromptQueued` | 排队消息的文本内容 | — | 上一回合仍在运行、新消息进入队列时触发;payload 含 `prompt_id`、`prompt`、`queue_length` | +| `PreToolUse` | 工具名 | ✓ | 工具调用前、权限检查前触发;阻断后工具不会执行 | | `Stop` | 空字符串 | ✓ | 模型准备结束本轮时触发;阻断后可追加一条消息让模型继续 | -| `TurnStarted` | 回合来源类型(如 `user`、`task`、`system_trigger`) | — | 新回合开始时触发;payload 含 `turn_id`、`origin_kind`、`origin_name` 和 `prompt`(观察用) | -| `PostToolUse` | 工具名 | — | 工具成功执行后触发(观察用) | -| `PostToolUseFailure` | 工具名 | — | 工具失败或被阻断后触发(观察用) | -| `PermissionRequest` | 工具名 | — | 即将等待用户审批前触发(观察用) | -| `PermissionResult` | 工具名 | — | 审批结束后触发(观察用) | -| `SessionStart` | `startup` 或 `resume` | — | 新会话启动或历史会话恢复后触发;payload 含 `source`、`model` 和 `profile` | +| `TurnStarted` | 回合来源类型(如 `user`、`task`、`system_trigger`) | — | 新回合开始时触发;payload 含 `turn_id`、`origin_kind`、`origin_name`、`prompt` | +| `PostToolUse` | 工具名 | — | 工具成功执行后触发 | +| `PostToolUseFailure` | 工具名 | — | 工具失败或被阻断后触发 | +| `PermissionRequest` | 工具名 | — | 即将等待用户审批前触发 | +| `PermissionResult` | 工具名 | — | 审批结束后触发 | +| `SessionStart` | `startup` 或 `resume` | — | 新会话启动或历史会话恢复后触发;payload 含 `source`、`model`、`profile` | | `SessionEnd` | `exit` 或 `archive` | — | 会话关闭后触发;`archive` 表示会话被归档而非退出 | -| `SessionHeartbeat` | 空字符串 | — | 会话存活期间每 60 秒触发一次;仅当配置了本事件时计时器才会运行。payload 含 `uptime_ms`(观察用) | +| `SessionHeartbeat` | 空字符串 | — | 会话存活期间每 60 秒触发一次,仅配置本事件时计时器才运行;payload 含 `uptime_ms` | | `SubagentStart` | subagent 名称 | — | subagent 开始运行前触发 | -| `SubagentStop` | subagent 名称 | — | subagent 成功完成后触发(观察用) | -| `TaskStarted` | 任务类型(`agent`、`process` 或 `question`) | — | 后台任务启动时触发;payload 含 `task_id`、`description` 和 `detached`(观察用) | -| `StopFailure` | 错误类型 | — | 本轮因错误失败后触发(观察用) | -| `Interrupt` | 空字符串 | — | 用户中断本轮时触发(例如按下 Esc);超时或其他程序性中断不会触发。中断时 `Stop` 不会触发,由本事件替代。payload 含 `reason` 字段(观察用) | +| `SubagentStop` | subagent 名称 | — | subagent 成功完成后触发 | +| `TaskStarted` | 任务类型(`agent`、`process` 或 `question`) | — | 后台任务启动时触发;payload 含 `task_id`、`description`、`detached` | +| `StopFailure` | 错误类型 | — | 本轮因错误失败后触发 | +| `Interrupt` | 空字符串 | — | 用户中断本轮时触发(如按 Esc);超时等程序性中断不触发,此时 `Stop` 由本事件替代;payload 含 `reason` | | `PreCompact` | `manual` 或 `auto` | — | 上下文压缩开始前触发;返回值被完全忽略 | -| `PostCompact` | `manual` 或 `auto` | — | 上下文压缩完成后触发(观察用) | -| `Notification` | 通知类型(如 `task.completed`) | — | 后台任务状态变化时触发(观察用) | +| `PostCompact` | `manual` 或 `auto` | — | 上下文压缩完成后触发 | +| `Notification` | 通知类型(如 `task.completed`) | — | 后台任务状态变化时触发 | ## 示例:阻断危险 Shell 命令 -下面的 hook 在 Agent 调用 `Bash` 工具前检查命令内容,发现 `rm -rf` 就阻断: +下面的 hook 在 Agent 调用 `Bash` 工具前检查命令内容,命中 `rm -rf` 时阻断: ```toml [[hooks]] diff --git a/docs/zh/customization/mcp.md b/docs/zh/customization/mcp.md index 02dc59015a6..3235d11b8d0 100644 --- a/docs/zh/customization/mcp.md +++ b/docs/zh/customization/mcp.md @@ -1,6 +1,6 @@ # Model Context Protocol -[Model Context Protocol(MCP)](https://modelcontextprotocol.io/) 是一个开放协议,让模型可以安全地调用外部进程或服务暴露的工具——例如读取 GitHub issues、查询数据库、操作本地文件系统。Kimi Code CLI 作为 MCP client 接入这些外部工具,并把它们与内置工具(`Read`、`Bash`、`Grep` 等)一起暴露给 Agent 使用,行为上没有差异。 +[Model Context Protocol(MCP)](https://modelcontextprotocol.io/) 是一个开放协议,让模型可以安全地调用外部进程或服务暴露的工具:读取 GitHub issues、查询数据库、操作本地文件系统。Kimi Code CLI 作为 MCP client 接入这些外部工具,把它们与内置工具一起暴露给 Agent 使用,行为上没有差异。 ## 接入方式 @@ -8,7 +8,7 @@ Kimi Code CLI 支持三种 MCP server 接入方式: - **stdio**:CLI 以子进程方式启动本地 MCP server,通过标准输入输出通信。适合本地命令行工具。 - **HTTP**:CLI 连接一个已在运行的 HTTP 端点。适合远程服务或需要持久运行的进程。 -- **SSE**:CLI 连接旧式 HTTP+SSE 端点(Server-Sent Events,一种流式 HTTP 机制)。新 MCP server 优先使用 HTTP;只有服务仍仅暴露旧式 SSE 传输时,才设置 `transport: "sse"`。 +- **SSE**:CLI 连接旧式 HTTP+SSE 端点。新 MCP server 优先使用 HTTP;只有服务仍仅暴露旧式 SSE 传输时,才设置 `transport: "sse"`。 ## 配置 @@ -21,9 +21,9 @@ MCP server 配置写在 `mcp.json` 中,分两层: 在 TUI 中运行 `/mcp-config` 可以交互式地新增、编辑或删除 server,无需手动编辑 JSON 文件。运行 `/mcp` 可查看当前所有 server 的连接状态。 -从配置中删除某个 server 不会打断进行中的会话:该 server 在 `/mcp` 中仍显示为 `removed`,其工具在这些会话中保持可见,但调用会失败并返回移除提示;新会话则完全不会注册这些工具。反过来,会话进行中新增的 server——无论是编辑 `mcp.json` 还是安装 plugin——都不会注册到已打开的会话中,只会加入之后创建的会话。 +从配置中删除某个 server 不会打断进行中的会话:该 server 在 `/mcp` 中仍显示为 `removed`,其工具在这些会话中保持可见,但调用会失败并返回移除提示;新会话则完全不会注册这些工具。反过来,编辑 `mcp.json` 或安装 plugin 新增的 server 也不会注册到已打开的会话,只会加入之后创建的会话。 -当 Kimi Code 在不受信任的文件夹中发现项目级 MCP server 时,工作区信任提示会显示每个 server 的传输方式和启动目标。提示默认选中 `Trust this folder`;请先核对列出的命令与参数或远程 URL,再确认信任。信任文件夹后,该工作区的项目级 MCP server 才会启用。 +当 Kimi Code 在不受信任的文件夹中发现项目级 MCP server 时,工作区信任提示会显示每个 server 的传输方式和启动目标。提示默认选中 `Trust this folder`;核对列出的命令与参数或远程 URL 后确认即可,选择 `Don't trust` 则该工作区的项目级 MCP server 不会启用。 `mcp.json` 的结构: @@ -56,8 +56,8 @@ MCP server 配置写在 `mcp.json` 中,分两层: | `headers` | `Record` | HTTP、SSE | 附加到每次请求的静态请求头 | | `bearerTokenEnvVar` | `string` | HTTP、SSE | 存放 bearer token 的环境变量名 | | `enabled` | `boolean` | 全部 | 设为 `false` 可禁用该 server | -| `startupTimeoutMs` | `number` | 全部 | 连接超时,取值范围为 `1` 到 `2147483647` 毫秒,默认 `30000` | -| `toolTimeoutMs` | `number` | 全部 | 单次工具调用超时,取值范围为 `1` 到 `2147483647` 毫秒 | +| `startupTimeoutMs` | `number` | 全部 | 连接超时,默认 `30000` 毫秒 | +| `toolTimeoutMs` | `number` | 全部 | 单次工具调用超时(毫秒) | | `enabledTools` | `string[]` | 全部 | 工具白名单 | | `disabledTools` | `string[]` | 全部 | 工具黑名单 | @@ -75,7 +75,7 @@ Plugins 也可以在 manifest 中声明 MCP servers。Plugin 声明的 servers MCP 工具按 `mcp____` 格式命名,例如 `mcp__github__create_issue`。权限规则中支持 `*` 和 `**` 通配,例如 `mcp__github__*` 命中该 server 下所有工具。MCP 工具参数不参与权限匹配。 -未命中权限规则的调用会触发审批请求;在审批弹窗中选择"Approve for this session"后,本次会话内的后续同类调用自动放行。 +未命中权限规则的调用会触发审批请求;在审批弹窗中选择“Approve for this session”后,本次会话内的后续同类调用自动放行。 也可以在 `config.toml` 的 `[[permission.rules]]` 中预置永久规则: @@ -89,7 +89,7 @@ decision = "deny" pattern = "mcp__filesystem__write_file" ``` -权限规则的完整语法见[配置文件](../configuration/config-files.md#permission)。 +权限规则的完整语法见 [配置文件](../configuration/config-files.md#permission)。 ## 安全性 @@ -100,7 +100,7 @@ pattern = "mcp__filesystem__write_file" - 对高风险工具(写文件、执行命令等)维持手动审批,避免用 `mcp__*` 通配放行全部工具 ::: warning 注意 -在 "Ask When Needed" 模式下,MCP 工具调用会被自动批准。仅在完全信任所接入的 MCP server 时使用此模式。 +在 [YOLO 模式](../guides/interaction.md#三种权限模式)下,MCP 工具调用会被自动批准。仅在完全信任所接入的 MCP server 时使用此模式。 ::: ## 下一步 diff --git a/docs/zh/customization/plugins.md b/docs/zh/customization/plugins.md index 2163ce1ae93..e0a1ce64258 100644 --- a/docs/zh/customization/plugins.md +++ b/docs/zh/customization/plugins.md @@ -1,17 +1,17 @@ # Plugins -Plugins 把可复用的 Kimi Code CLI 能力打包成可安装单元——可以添加 [Agent Skills](./skills.md)、自定义 [Agent](./agents.md)、在会话启动时自动加载指定 Skill、提供系统提示词指令,也可以声明 MCP servers 来提供真实工具能力。适合把工作流共享给团队、连接外部服务,或从[官方插件](#官方插件)安装扩展。 +Plugins 把可复用的 Kimi Code CLI 能力打包成可安装单元:可以添加 [Agent Skills](./skills.md)、自定义 [Agent](./agents.md),可以指定会话启动时自动加载的 Skill、提供系统提示词指令,也可以声明 MCP servers 提供真实工具能力。适合把工作流共享给团队、连接外部服务,或从 [官方插件](#官方插件)安装扩展。 ## 安装与管理 -在 TUI 中运行 `/plugins` 打开 plugin 管理器。它是一个面板,有四个 tab: +在 TUI 中运行 `/plugins` 打开 plugin 管理器,面板内有四个 tab: -- **Installed**:管理已装的 +- **Installed**:管理已安装的 plugin - **Official**:Kimi 官方 marketplace plugin - **Curated**:默认 marketplace 中来自 Kimi 合作伙伴的第三方 plugin - **Custom**:从 URL 安装 -用 `Tab` / `Shift-Tab` 切换。常用按键: +面板内按键: | 按键 | 操作 | | --- | --- | @@ -20,11 +20,11 @@ Plugins 把可复用的 Kimi Code CLI 能力打包成可安装单元——可以 | `D` | 移除选中的已安装 plugin(Installed tab) | | `M` | 管理选中 plugin 的 MCP servers(Installed tab) | | `R` | 重新加载 `installed.json` 和所有 manifest(Installed tab) | -| `Enter` | Installed tab:有更新时安装更新,否则查看 plugin 详情 · Official/Curated tab:安装或更新 · Custom tab:安装 | +| `Enter` | Installed:有更新时安装更新,否则查看 plugin 详情;Official/Curated:安装或更新;Custom:安装 | | `I` | 查看 plugin 详情(Installed tab) | | `Esc` | 返回或取消 | -也可以直接使用斜杠命令: +也可以使用斜杠命令: | 命令 | 说明 | | --- | --- | @@ -53,14 +53,14 @@ Plugins 把可复用的 Kimi Code CLI 能力打包成可安装单元——可以 ### 注意事项 -- Plugin 变更需要通过 `/reload` 或新会话生效。安装、启用/禁用、移除后,运行 `/reload` 或 `/new`;当前会话不会更新。 +- 安装、启用/禁用、移除 plugin 后,当前会话不会更新,运行 `/reload` 或 `/new` 后生效。 - 本地安装会被拷贝到 `$KIMI_CODE_HOME/plugins/managed//`,CLI 始终从这份托管副本运行。安装后编辑原始源目录不会生效,需重新安装。 - 移除 plugin 只会删除安装记录,托管副本和原始源文件仍保留在磁盘上。 - Plugin 目前按用户安装,对所有项目生效,暂不支持项目级安装范围。 ### 自定义 marketplace JSON -浏览自定义目录时,把 JSON 路径或 URL 传给 `/plugins marketplace `;或通过 [`KIMI_CODE_PLUGIN_MARKETPLACE_URL`](../configuration/env-vars.md) 覆盖默认 marketplace。`plugins` 数组中每个条目需要 `id` 和 `source`(本地路径、zip URL 或 GitHub URL): +浏览自定义目录时,把 JSON 路径或 URL 传给 `/plugins marketplace `,或通过 [`KIMI_CODE_PLUGIN_MARKETPLACE_URL`](../configuration/env-vars.md) 覆盖默认 marketplace。`plugins` 数组中每个条目需要 `id` 和 `source` 两个字段,`source` 支持本地路径、zip URL 和 GitHub URL: ```json { @@ -87,7 +87,7 @@ Plugins 把可复用的 Kimi Code CLI 能力打包成可安装单元——可以 官方插件的安装与升级流程一致: -1. 运行 `/plugins`,tab键选择 **Official** +1. 运行 `/plugins`,按 `Tab` 键选中 **Official** tab 2. 找到要安装的插件,按 `Enter` 安装 3. 安装完成后运行 `/reload` 或 `/new` 激活 @@ -95,19 +95,19 @@ Plugins 把可复用的 Kimi Code CLI 能力打包成可安装单元——可以 Kimi WebBridge 分两步安装:完成上述步骤后,还需要[安装浏览器扩展](#install-the-browser-extension)才能使用。 ::: -官方插件更新后会在使用旧版时提示更新,不会自动更新,要升级到新版本,重复上述安装步骤即可。 +官方插件不会自动更新,使用旧版时会提示更新。升级到新版本只需重复上述安装步骤。 ### Kimi Datasource -Kimi Datasource 是 Kimi Code 官方数据插件,让你用自然语言直接查询金融行情、财经资讯、宏观经济、企业工商、学术文献、中国法律法规和国际组织官方数据,无需手动调用接口或申请数据账号。 +Kimi Datasource 是 Kimi Code 官方数据插件。用自然语言直接查询金融行情、财经资讯、宏观经济、企业工商、学术文献、中国法律法规和国际组织官方数据,无需手动调用接口或申请数据账号。 数据来源包括世界银行、IMF、OECD、FRED、WHO、FAO、国家统计局、Wind、S&P Capital IQ、SEC EDGAR、财新、新华财经、恒生聚源等权威机构与知名数据库,信源可溯源。 -使用前需先通过 `/login` 完成 Kimi Code 账号 OAuth 登录,数据查询会消耗你的 Kimi Code 套餐额度。 +> 使用前需先通过 `/login` 完成 Kimi Code 账号 OAuth 登录。数据查询会消耗 Kimi Code 套餐额度。 #### 使用方式 -1. 直接用自然语言描述你的需求,Kimi Code 会自动调用数据能力 +1. 直接用自然语言描述需求,Kimi Code 会自动调用数据能力 2. 通过 `/skill:kimi-datasource` 明确触发数据查询 Skill #### 能做什么 @@ -147,15 +147,15 @@ Kimi Datasource 是 Kimi Code 官方数据插件,让你用自然语言直接 #### 数据覆盖 | 类别 | 覆盖范围 | -|---|---| -| 股票与金融市场 | Wind、S&P Capital IQ、SEC EDGAR 等知名数据库,能力涵盖 A 股、港股、美股等主要市场的行情、技术指标、财报估值、分析师预期,以及 8,000+ 美股上市公司的官方披露文件 | -| 财经资讯与行业数据 | 财新、新华财经等知名数据平台,能力涵盖市场资讯与快讯、上市公司公告、监管政策、债券基金期货数据、企业失信记录、上市公司产业链关系 | -| 宏观经济 | 世界银行、IMF、OECD、FRED、国家统计局等知名数据库及 WHO、FAO 等国际组织官方统计,能力涵盖全球 189 个国家 50 年以上时间序列与中国全国/省/市指标:GDP、贸易、人口、汇率、CPI、国际收支、GDP 预测等 | -| 中国标准 | 国家标准(GB)、行业标准、地方标准和团体标准的编号、名称、发布状态与详情,部分国标和公开团标提供官方全文入口 | -| 企业数据 | 中国大陆境内企业工商信息、股权穿透、司法风险、关联图谱 | +| --- | --- | +| 股票与金融市场 | Wind、S&P Capital IQ、SEC EDGAR 等;A 股、港股、美股行情、技术指标、财报估值、分析师预期,8,000+ 美股上市公司官方披露文件 | +| 财经资讯与行业数据 | 财新、新华财经等;市场资讯与快讯、上市公司公告、监管政策、债券基金期货数据、企业失信记录、产业链关系 | +| 宏观经济 | 世界银行、IMF、OECD、FRED、国家统计局及 WHO、FAO 等;全球 189 个国家 50 年以上时间序列,中国全国/省/市指标(GDP、贸易、人口、汇率、CPI、国际收支) | +| 中国标准 | 国家标准(GB)、行业标准、地方标准、团体标准的编号、名称、发布状态与详情;部分国标和公开团标提供官方全文入口 | +| 企业数据 | 中国大陆企业工商信息、股权穿透、司法风险、关联图谱 | | 学术文献 | 物理、数学、计算机、金融、经济等领域百万量级论文,支持预印本查询 | -| 法律法规 | 元典智库等知名法律数据库,能力涵盖中国法律法规与司法案例:各效力层次的法规检索与详情,普通及权威判例检索 | -| 智能筛选 | 恒生聚源等知名数据库,能力涵盖自然语言选股、选基金、选基金经理,以及宏观行业数据、研报、公告与新闻 | +| 法律法规 | 元典智库等;中国法律法规与司法案例,含各效力层次法规检索与详情、权威判例检索 | +| 智能筛选 | 恒生聚源等;自然语言选股、选基金、选基金经理,及宏观行业数据、研报、公告与新闻 | #### 计费与限制 @@ -166,23 +166,23 @@ Kimi Datasource 是 Kimi Code 官方数据插件,让你用自然语言直接 ### Kimi WebBridge -Kimi WebBridge 让 AI 直接操控你的浏览器,带着你的登录状态和 Cookie,AI 可以像你一样打开网页、阅读内容、点击按钮、填写表单、截图保存,把重复繁琐的网页操作交给它完成。产品介绍见 [Kimi WebBridge 官网](https://www.kimi.com/zh-cn/features/webbridge)。 +Kimi WebBridge 让 AI 直接操控你的浏览器,带着你的登录状态和 Cookie 打开网页、阅读内容、点击按钮、填写表单、截图保存,把重复的网页操作交给它完成。产品介绍见 [Kimi WebBridge 官网](https://www.kimi.com/zh-cn/features/webbridge)。 #### 安装浏览器扩展 -通过 `/plugins` 安装后,还需要在浏览器中安装 Kimi WebBridge 扩展,AI 才能操控你的浏览器。有两种安装方式: +通过 `/plugins` 安装后,还需要在浏览器中安装 Kimi WebBridge 扩展才能使用。有两种安装方式: **方式一:应用商店安装(推荐)** -打开 [Chrome 应用商店](https://chromewebstore.google.com/detail/kimi-webbridge/fldmhceldgbpfpkbgopacenieobmligc)或 [Edge 应用商店](https://microsoftedge.microsoft.com/addons/detail/kimi-webbridge/bnlffdbcfnanfbknnlaflhlhkocccckg),点击添加即可。 +打开 [Chrome 应用商店](https://chromewebstore.google.com/detail/kimi-webbridge/fldmhceldgbpfpkbgopacenieobmligc) 或 [Edge 应用商店](https://microsoftedge.microsoft.com/addons/detail/kimi-webbridge/bnlffdbcfnanfbknnlaflhlhkocccckg),点击添加即可。 **方式二:手动安装** 无法访问应用商店时使用这种方式,按以下步骤操作: -1. [下载扩展安装包](https://kimi-web-img.moonshot.cn/webbridge/latest/extension/kimi-webbridge-extension.zip)并解压 +1. [下载扩展安装包](https://kimi-web-img.moonshot.cn/webbridge/latest/extension/kimi-webbridge-extension.zip) 并解压 2. 在浏览器地址栏输入 `chrome://extensions/` 打开扩展管理页,开启右上角的**开发者模式** ![开启开发者模式](../../media/webbridge-dev-mode.jpeg) @@ -191,13 +191,13 @@ Kimi WebBridge 让 AI 直接操控你的浏览器,带着你的登录状态和 ![加载未打包的扩展程序](../../media/webbridge-load-unpacked.jpeg) -4. 装好后,浏览器工具栏会出现 Kimi WebBridge 图标,看到图标即安装成功,之后就可以让 AI 帮你操作网页了。 +4. 安装完成后,浏览器工具栏会出现 Kimi WebBridge 图标,即表示安装成功 ![工具栏出现 Kimi WebBridge 图标](../../media/webbridge-install-success.jpeg) #### 能做什么 -- **网页操作自动化**:你说话,AI 帮你点网页、填表单、读内容、截图,重复性的网页操作交给它就好 +- **网页操作自动化**:你说话,AI 帮你点网页、填表单、读内容、截图,把重复性的网页操作交给它 - **社媒热点选题**:自动浏览 X(Twitter)、微博、小红书的热门话题,筛选你感兴趣的方向,逐个打开高赞内容截图、提取核心观点,整理成素材库并给出选题建议 - **求职信息搜集**:在招聘网站按条件筛选岗位(关键词、城市、岗位类型),把岗位名称、链接、公司、薪资、投递方式整理成表格 - **竞品分析**:自动在多个 AI 产品间批量发问并采集回答,生成横向对比报告 @@ -205,14 +205,14 @@ Kimi WebBridge 让 AI 直接操控你的浏览器,带着你的登录状态和 ### Kimi Computer Use -Kimi Computer Use 让 AI 直接操作你的桌面应用,可以完成点击、拖拽、滚动、输入等操作。macOS 版全程在后台静默运行,不抢占你的鼠标(少量弹窗操作仍会唤起前台 App);Windows 版的差异见[下文注意事项](#windows-版注意事项)。 +Kimi Computer Use 让 AI 直接操作你的桌面应用,可以完成点击、拖拽、滚动、输入等操作。macOS 版全程在后台静默运行,不抢占你的鼠标;少量弹窗操作仍会唤起前台 App。Windows 版的差异见 [Windows 版注意事项](#windows-版注意事项)。 #### 授权(macOS) 安装后首次使用时,Kimi Computer Use 会弹出授权窗口,按照提示操作即可: -1. 点击**辅助功能**和**屏幕录制**右侧的**去授权**,在系统设置中开启这两项权限。前者用于执行点击、输入与滚动,后者用于读取屏幕内容、识别需要操作的位置 -2. 在**接入本地 Agent**中打开 **Kimi Code** 开关,重启 Kimi Code 后生效 +1. 点击**辅助功能**和**屏幕录制**右侧的**去授权**,在系统设置中开启这两项权限。前者用于执行点击、输入与滚动,后者用于读取屏幕内容、识别需要操作的位置。 +2. 在**接入本地 Agent**中打开 **Kimi Code** 开关,重启 Kimi Code 后生效。
@@ -222,7 +222,6 @@ Kimi Computer Use 让 AI 直接操作你的桌面应用,可以完成点击、 #### Windows 版注意事项 - - **会短暂占用键鼠**:Windows 版无法像 macOS 版那样稳定地全程后台输入,执行操作时可能短暂激活目标窗口并使用你的鼠标键盘 - **系统要求**:Windows 10 version 1903(Build 18362)或更新版本 / Windows 11,x64;需要真实交互式桌面会话,Windows Server 需要 Desktop Experience - **无需额外授权**:Windows 不需要 macOS 那样的**辅助功能**和**屏幕录制**权限 @@ -231,9 +230,9 @@ Kimi Computer Use 让 AI 直接操作你的桌面应用,可以完成点击、 #### 能做什么 - **在桌面软件整理和录入信息**:让 AI 把散落在各处的信息整理进备忘录、表格或笔记软件,不用手动逐条输入 -- **测试网站和应用流程**:将重复的测试步骤交给AI,截图确认渲染和跳转是否正常 -- **处理重复操作**:反复打开、复制、粘贴、检查类型的工作,让AI在后台静默完成,不抢占鼠标 -- **搞定没有接口的软件**:操作没有 CLI 或 API 的桌面端应用,例如让它把剪映里这段视频的片头剪掉三秒再导出 +- **测试网站和应用流程**:将重复的测试步骤交给 AI,截图确认渲染和跳转是否正常 +- **处理重复操作**:反复打开、复制、粘贴、检查类型的工作,让 AI 在后台静默完成,不抢占鼠标 +- **操作无接口的软件**:操作没有 CLI 或 API 的桌面端应用,例如把剪映里这段视频的片头剪掉三秒再导出 ::: warning 注意 涉及资金、账号和对外发布的操作不建议使用此能力。 @@ -273,24 +272,28 @@ Plugin 是一个带 manifest 的目录或 zip 文件。Manifest 可以放在以 | 字段 | 说明 | | --- | --- | -| `name` | 必填,作为 plugin id。必须匹配 `[a-z0-9][a-z0-9_-]{0,63}` | +| `name` | 必填,作为 plugin id,必须匹配 `[a-z0-9][a-z0-9_-]{0,63}` | | `version`、`description`、`keywords`、`author`、`homepage`、`license` | 展示元数据 | | `interface` | 在 `/plugins` 中展示的字段:`displayName`、`shortDescription`、`longDescription`、`developerName`、`websiteURL` | | `skills` | 一个或多个 `./` 路径,必须位于 plugin 根目录内。省略时根目录的 `SKILL.md` 被当作单个 Skill root | -| `agents` | 一个或多个 `./` 路径,必须位于 plugin 根目录内,指向含有 [Agent 文件](./agents.md#自定义-agent)的目录。省略时根下的 `agents/` 目录(若存在)被自动采用 | +| `agents` | 一个或多个 `./` 路径,必须位于 plugin 根目录内,指向含有 [Agent 文件](./agents.md#自定义-agent) 的目录。省略时若根目录存在 `agents/` 目录则自动采用 | | `sessionStart.skill` | 在新会话或恢复会话开始时,把指定 plugin Skill 加载到 main agent | | `skillInstructions` | 每次加载此 plugin 的 Skill 时一并附带的额外说明 | | `systemPrompt` | plugin 启用期间提供给 Agent 系统提示词的内联指令 | | `systemPromptPath` | 指向 UTF-8 文本文件的 `./` 路径;同时设置 `systemPrompt` 时,文件内容拼接在内联指令之后 | | `mcpServers` | MCP server 声明,默认启用,可从 `/plugins` 中禁用 | -| `hooks` | 在 plugin 启用期间于生命周期事件上运行的 hook 规则;见[插件中的 Hooks](#插件中的-hooks) | -| `commands` | 一个或多个 `./` 路径,指向目录或 `.md` 文件,把其中的 Markdown 文件注册为斜杠命令;见[插件斜杠命令](#插件斜杠命令) | +| `hooks` | 在 plugin 启用期间于生命周期事件上运行的 hook 规则,见 [插件中的 Hooks](#插件中的-hooks) | +| `commands` | 一个或多个 `./` 路径,指向目录或 `.md` 文件,把其中的 Markdown 文件注册为斜杠命令,见 [插件斜杠命令](#插件斜杠命令) | `tools`、`apps`、`inject`、`configFile` 等不支持的运行时字段会显示为 diagnostics 并被忽略。 ### 系统提示词指令 -短指令可以直接写在 `systemPrompt`,较长内容则用 `systemPromptPath` 指向 plugin 根目录内的文件。两个字段同时存在时,内联文本在前,文件内容在后。文件内容在安装或重载 plugin 时读取,因此修改文件后需要 `/plugins reload` 才会生效。例如: +Plugin 通过 `systemPrompt` 和 `systemPromptPath` 两个字段向 Agent 的系统提示词注入指令。本节按三块说明:写法与读取时机、大小限制、两个引擎的差异。 + +### 写法与读取时机 + +短指令可以直接写在 `systemPrompt`,较长内容则用 `systemPromptPath` 指向 plugin 根目录内的文件。两个字段同时存在时,内联文本在前,文件内容在后。文件内容在安装或重载 plugin 时读取,修改文件后需要 `/plugins reload` 才会生效。例如: ```json { @@ -299,17 +302,28 @@ Plugin 是一个带 manifest 的目录或 zip 文件。Manifest 可以放在以 } ``` +内置 Agent 提示词会自动包含已启用 plugin 的指令。自定义 `SYSTEM.md` 或 Agent 文件完全拥有自己的模板,应在希望出现 plugin 指令的位置加入 `${plugin_sections}`。如果自定义模板包含 `${base_prompt}`,且该有效默认提示词已经包含 plugin 块,则不要再重复加入 `${plugin_sections}`。变量完整列表见 [自定义 Agent 与 SYSTEM.md](./agents.md#用-systemmd-覆盖-main-agent-的系统提示词)。 + +### 大小限制 + +`systemPrompt` 字段与 `systemPromptPath` 文件各限制为 32 KB(UTF-8 字节),超限内容会被忽略并显示在 plugin 的 diagnostics 中。一次提示词构建最多注入所有已启用 plugin 合计 64 KB 的指令,超出预算的贡献会被跳过并给出警告;单个 plugin 的内联文本与文件合计超过该预算时同样整体跳过。 + +### 两个引擎的差异 + 系统提示词贡献在两个 Agent 引擎上都生效。交互式 TUI、`kimi -p` 和 `kimi web` 默认使用 v2 引擎;设置 `KIMI_CODE_LEGACY_FLAG=1` 后,本地 CLI 界面会改用旧版引擎。 -`systemPrompt` 字段与 `systemPromptPath` 文件各限制为 32 KB(UTF-8 字节):超限内容会被忽略,并显示在 plugin 的 diagnostics 中。一次提示词构建最多注入所有已启用 plugin 合计 64 KB 的指令;超出预算的贡献会被跳过并给出警告——单个 plugin 的内联文本与文件合计超过该预算时同样整体跳过。 +新会话和新建 Agent 会读取当前已启用 plugin 的指令,正在进行的请求继续使用已有的系统提示词。`/plugins reload` 会刷新 plugin Skill 列表,并请求重建活跃 Agent 的提示词;需要让变更在下一轮前明确收敛时使用该命令。切换 plugin 的 MCP server 不会改变系统提示词指令。 + +
+两个引擎下的指令刷新行为 -新会话和新建 Agent 会读取当前已启用 plugin 的指令。正在进行的请求会继续使用已有的系统提示词。`/plugins reload` 会刷新 plugin Skill 列表,并请求重建活跃 Agent 的提示词;如果需要让变更在下一轮前明确收敛,请使用这个命令。在 v2 引擎中,安装、启用、禁用或移除 plugin 会立即更新 catalog,后续的提示词重建(例如压缩上下文或修改工具策略后)可能会读取新的指令。legacy 引擎会让每个活跃 session 保留自己的 plugin 快照,直到 `/plugins reload` 或创建新 session。从磁盘恢复的 session 会先使用持久化的提示词,后续重建再遵循对应引擎的行为。切换 plugin 的 MCP server 不会改变系统提示词指令。 +在 v2 引擎中,安装、启用、禁用或移除 plugin 会立即更新 catalog,后续的提示词重建可能会读取新的指令。legacy 引擎中每个活跃 session 保留自己的 plugin 快照,直到 `/plugins reload` 或创建新 session。从磁盘恢复的 session 先使用持久化的提示词,后续重建再遵循对应引擎的行为。 -内置 Agent 提示词会自动包含已启用 plugin 的指令。自定义 `SYSTEM.md` 或 Agent 文件完全拥有自己的模板,因此应在希望出现 plugin 指令的位置加入 `${plugin_sections}`。如果自定义模板包含 `${base_prompt}`,且该有效默认提示词已经包含 plugin 块,就不要再重复加入 `${plugin_sections}`。完整变量表见 [自定义 Agent 与 SYSTEM.md](./agents.md#用-system-md-覆盖-main-agent-的系统提示词)。 +
## 插件斜杠命令 -斜杠命令把一段常用提示词存成 `/命令`,输入它就能触发,省得每次重打。 +斜杠命令把一段常用提示词存成 `/命令`,输入即可触发。 下面是一个最小完整例子,插件目录结构: @@ -330,7 +344,7 @@ manifest(`kimi.plugin.json`)用 `commands` 字段指出命令文件的位置 } ``` -命令文件 `commands/report.md`。顶部两行 `---` 之间是 frontmatter(描述命令的元数据),下面的正文是触发时发给 Agent 的提示词: +命令文件 `commands/report.md` 中,顶部两行 `---` 之间是 frontmatter,其下正文是触发时发给 Agent 的提示词: ```markdown --- @@ -340,7 +354,7 @@ description: 拉取指定股票的财报并总结 拉取 $ARGUMENTS 的最新财报数据,总结营收、利润和关键风险。 ``` -装好并启用后,在对话里输入: +安装并启用后,在对话里输入: ```text /kimi-finance:report TSLA @@ -352,22 +366,22 @@ Kimi 会把正文里的 `$ARGUMENTS` 替换成 `TSLA`,再执行这段提示词 `commands` 填一个 `./` 路径或路径数组,指向 plugin 根目录内的目录或 `.md` 文件: -- 指向**目录**:递归收集其中所有 `.md` 文件,每个各成为一个命令。 +- 指向**目录**:递归收集其中所有 `.md` 文件,每个文件各成为一个命令。 - 指向**单个 `.md` 文件**:只注册这一个。 -- 指向非 `.md` 或不存在的路径:显示为 diagnostics(`/plugins` 面板里的诊断提示)并被忽略。 +- 指向非 `.md` 或不存在的路径:显示为 diagnostics 并被忽略。 ### 编写命令文件 -命令文件分两部分:可选的 **frontmatter**(顶部两行 `---` 之间的元数据,可写 `name`、`description`)和**正文**(`---` 之后的提示词)。两个字段省略时的回退规则: +命令文件分两部分:可选的 **frontmatter**(顶部两行 `---` 之间,可写 `name`、`description`)和**正文**(`---` 之后的提示词)。两个字段省略时的回退规则: -- `name`(命令名):省略时用文件相对 `commands` 路径的路径命名(去 `.md`、`/` 分隔),如 `commands/frontend/component.md` → `frontend/component`;frontmatter 里显式写的优先。 -- `description`(命令列表里的说明):省略时取正文首行非空文字(超 240 字符截断);正文也为空则显示 `No description provided.`。 +- `name`(命令名):省略时按文件相对 `commands` 的路径命名,去掉 `.md`、以 `/` 分隔,如 `commands/frontend/component.md` 注册为 `frontend/component`;frontmatter 里显式写的优先 +- `description`(命令列表里的说明):省略时取正文首行非空文字,超 240 字符截断;正文也为空则显示 `No description provided.` ### 调用命令与传参 -命令自动以插件 id 作前缀(即命名空间),注册成 `<插件名>:<命令名>`,所以上面的命令实际叫 `/kimi-finance:report`,不同插件的同名命令因此不会冲突。 +命令自动以插件 id 作前缀注册成 `<插件名>:<命令名>`,所以上面的命令实际叫 `/kimi-finance:report`,不同插件的同名命令因此不会冲突。 -命令后输入的文字会替换正文里的 `$ARGUMENTS`(上例中 `TSLA` 替换掉 `$ARGUMENTS`)。若正文没写 `$ARGUMENTS` 却传了参数,参数不会丢弃,而是以 `ARGUMENTS: <你输入的内容>` 追加到正文末尾。 +命令后输入的文字会替换正文里的 `$ARGUMENTS`。若正文没写 `$ARGUMENTS` 却传了参数,参数不会丢弃,而是以 `ARGUMENTS: <你输入的内容>` 追加到正文末尾。 ## Skills 与会话启动 @@ -389,7 +403,7 @@ my-plugin/ ## 插件 Agent -Plugin 可以携带自定义 Agent:在 manifest 的 `agents` 字段里声明一个或多个 `./` 目录(或直接在 plugin 根下放置 `agents/` 目录),其中的 Agent 文件与[自定义 Agent](./agents.md#自定义-agent) 格式相同,会在 plugin 启用期间作为 subagent 被 main agent 自动发现和委派。 +Plugin 可以携带自定义 Agent:在 manifest 的 `agents` 字段里声明一个或多个 `./` 目录,或直接在 plugin 根下放置 `agents/` 目录。其中的 Agent 文件与 [自定义 Agent](./agents.md#自定义-agent) 格式相同,会在 plugin 启用期间作为 subagent 被 main agent 自动发现和委派。 ```text my-plugin/ @@ -398,7 +412,7 @@ my-plugin/ reviewer.md ``` -Plugin Agent 的优先级低于其他文件来源:同名时用户级、额外目录、项目级和 `--agent-file` 的 Agent 都会覆盖 plugin 提供的版本;替换内置 Agent 同样需要在 frontmatter 里显式写 `override: true`。安装、启用、禁用或移除 plugin 后,Agent 列表在新会话(或 `/reload`)时刷新;v2 引擎的当前会话还会在 `/plugins reload` 后刷新。 +Plugin Agent 的优先级低于其他文件来源:同名时用户级、额外目录、项目级和 `--agent-file` 的 Agent 都会覆盖 plugin 提供的版本;替换内置 Agent 同样需要在 frontmatter 里显式写 `override: true`。安装、启用、禁用或移除 plugin 后,Agent 列表在新会话或 `/reload` 时刷新;v2 引擎的当前会话还会在 `/plugins reload` 后刷新。 ## Plugin 中的 MCP servers @@ -443,7 +457,7 @@ Plugin MCP servers 会在 `/reload` 后或新会话中启动。启用或禁用 ## 插件中的 Hooks -plugin 可以在其 manifest 中声明 hook 规则,在 plugin 启用期间于生命周期事件上运行。每一项使用与 [`config.toml` 中的 `[[hooks]]` 规则](./hooks.md#配置)相同的字段(`event`、`matcher`、`command`、`timeout`): +plugin 可以在其 manifest 中声明 hook 规则,在 plugin 启用期间于生命周期事件上运行。每一项的字段与 [`config.toml` 中的 `[[hooks]]` 规则](./hooks.md#配置) 相同(`event`、`matcher`、`command`、`timeout`): ```json { @@ -458,19 +472,26 @@ plugin 可以在其 manifest 中声明 hook 规则,在 plugin 启用期间于 } ``` -plugin hooks 复用与全局 hooks 相同的机制——事件列表、stdin JSON 载荷以及退出码和返回值如何影响主流程,详见 [Hooks](./hooks.md)。区别如下: +plugin hooks 复用与全局 hooks 相同的机制。事件列表、stdin JSON 载荷、退出码与返回值对主流程的影响,详见 [Hooks](./hooks.md)。两者区别: - plugin 的 hooks 仅在 plugin **启用**期间生效;禁用 plugin 后其 hooks 停止运行。 -- 每条 hook 的工作目录为 plugin 根目录,因此 `command` 可以使用 plugin 内的 `./` 路径。 +- 每条 hook 的工作目录为 plugin 根目录,`command` 可以使用 plugin 内的 `./` 路径。 - hook 进程会额外收到两个环境变量:`KIMI_CODE_HOME` 和 `KIMI_PLUGIN_ROOT`(plugin 根目录)。 -仅安装 plugin 本身不会运行其 hooks——它们只在 plugin 启用期间、匹配的事件触发时运行。 +仅安装 plugin 本身不会运行其 hooks;它们只在 plugin 启用期间、匹配的事件触发时运行。 ## 安全模型 -Plugin 的加载范围有限,以下操作不会在安装或会话启动时发生: +Plugin 的加载范围有限,安装和运行时的安全边界如下: - 不会执行命令型 plugin tools 或旧式工具运行时 - 所有路径在解析符号链接后仍必须位于 plugin 根目录内 -- 已启用 plugin 的 MCP servers 会在 `/reload` 后或新会话中启动,且可随时从 `/plugins` 禁用 -- 损坏的 manifest 或不安全路径会显示在 `/plugins info ` 的 diagnostics 中,不影响其他会话 +- 已启用 plugin 的 MCP servers 在 `/reload` 后或新会话中启动,可随时从 `/plugins` 禁用 +- 损坏的 manifest 或不安全路径显示在 `/plugins info ` 的 diagnostics 中,不影响其他会话 + +## 下一步 + +- [Agent Skills](./skills.md) — 了解 SKILL.md 格式,编写 plugin 携带的 Skill +- [自定义 Agent](./agents.md) — 了解 Agent 文件格式与目录作用域优先级 +- [MCP](./mcp.md) — 了解 plugin 中 MCP server 声明复用的 schema +- [Hooks](./hooks.md) — 了解 plugin hooks 复用的全局 hook 机制 diff --git a/docs/zh/customization/skills.md b/docs/zh/customization/skills.md index a6472210a1e..a392deae79d 100644 --- a/docs/zh/customization/skills.md +++ b/docs/zh/customization/skills.md @@ -1,8 +1,8 @@ # Agent Skills -Agent Skills 是 Kimi Code CLI 扩展模型能力的轻量机制。一个 Skill 就是一份带 YAML frontmatter 的 Markdown 文档,描述某项专业知识或工作流程——例如项目的代码风格规范、PR review 流程、提交消息格式。 +Agent Skills 是 Kimi Code CLI 扩展模型能力的轻量机制。一个 Skill 就是一份带 YAML frontmatter 的 Markdown 文档,描述某项专业知识或工作流程:项目的代码风格规范、PR review 流程、提交消息格式。 -相比每次把同样的指引粘到提示词里,Skill 的优势在于:内容沉淀在文件里、可以跨项目和团队复用、可以通过斜杠命令一键加载,也可以让模型在需要时自动调用。 +与每次把同样的指引粘到提示词里相比,Skill 把内容沉淀在文件里,可以跨项目和团队复用,既可以通过斜杠命令一键加载,也可以让模型在需要时自动调用。 ## 创建 Skill @@ -39,12 +39,12 @@ arguments: | 字段 | 说明 | | --- | --- | -| `name` | Skill 名称。目录型 `SKILL.md` 中为必填;扁平 `.md` 文件省略时使用文件名。名称大小写不敏感 | -| `description` | 一行总结,模型用它来判断何时使用这个 Skill。目录型 `SKILL.md` 中为必填;扁平 `.md` 文件省略时回退到正文第一行非空内容(截至 240 字符) | -| `type` | Skill 类型:`prompt`(默认)、`inline`(与 `prompt` 语义相同)、`flow`(只支持手动调用,不支持模型自动调用)。其他值会被跳过 | -| `whenToUse` | 触发场景描述。也接受 `when-to-use`、`when_to_use` 写法 | -| `disableModelInvocation` | 设为 `true` 时禁止模型自动调用此 Skill。也接受 `disable-model-invocation`、`disable_model_invocation` 写法 | -| `arguments` | 命名参数列表,可写成字符串数组或空白分隔的字符串(如 `arguments: target mode`)。声明后,正文可用 `$` 读取参数 | +| `name` | Skill 名称,大小写不敏感。目录型 `SKILL.md` 必填,扁平 `.md` 省略时取文件名 | +| `description` | 一行总结,模型用它判断何时使用。目录型必填,扁平 `.md` 省略时取正文第一行非空内容(截至 240 字符) | +| `type` | 类型:`prompt`(默认)、`inline`(同 `prompt`)、`flow`(仅手动调用)。其他值被跳过 | +| `whenToUse` | 触发场景描述,也接受 `when-to-use`、`when_to_use` 写法 | +| `disableModelInvocation` | 设为 true 禁止模型自动调用,也接受 `disable-model-invocation`、`disable_model_invocation` 写法 | +| `arguments` | 命名参数列表,字符串数组或空白分隔字符串(如 `arguments: target mode`)。声明后正文可用 `$` 读取 | ::: warning 注意 目录型 `SKILL.md` 中 `name` 和 `description` **必须**显式填写,省略任意一项均会导致解析失败。 @@ -59,17 +59,17 @@ arguments: - `$`:`arguments` 中声明的命名参数 - `${KIMI_SKILL_DIR}`:当前 Skill 文件所在目录 -位置参数支持单双引号包裹,如 `/skill:commit "fix login" patch` 中 `$0` 展开为 `fix login`。若正文不含任何参数占位符,调用时附带的文本会以 `\n\nARGUMENTS: <文本>` 的形式追加到正文末尾。 +位置参数支持单双引号包裹:在 `/skill:commit "fix login" patch` 中,`$0` 展开为 `fix login`。若正文不含任何参数占位符,调用时附带的文本会以 `\n\nARGUMENTS: <文本>` 的形式追加到正文末尾。 ## Skill 存放位置 -Kimi Code CLI 按作用域分四档扫描,越具体的作用域优先级越高:**Project > User > Extra > Built-in** +Kimi Code CLI 按作用域分四档扫描,越具体的作用域优先级越高:**Project > User > Extra > Built-in**。 **用户级**(对所有项目生效): - `$KIMI_CODE_HOME/skills/`(默认:`~/.kimi-code/skills/`) - `~/.agents/skills/` -Kimi 专属用户级 Skill 目录会随 `KIMI_CODE_HOME` 移动,因此隔离数据根时也会隔离 Kimi 专属 Skills。通用 `~/.agents/skills/` 目录仍放在真实 OS home 下,以便跨工具共享。 +Kimi 专属用户级 Skill 目录会随 `KIMI_CODE_HOME` 移动,隔离数据根时也会隔离 Kimi 专属 Skills。通用 `~/.agents/skills/` 目录仍放在真实 OS home 下,以便跨工具共享。 **项目级**(项目根 = 工作目录向上最近的含 `.git` 的目录): - `.kimi-code/skills/` @@ -81,7 +81,7 @@ Kimi 专属用户级 Skill 目录会随 `KIMI_CODE_HOME` 移动,因此隔离 extra_skill_dirs = ["~/team-skills", ".agents/team-skills"] ``` -**内置 Skills** 随 CLI 一起分发,优先级最低。它们为常见任务提供开箱即用的工作流,例如配置 MCP server、定制 TUI 主题和编辑配置文件。完整列表详见[内置 Skill 命令](../reference/slash-commands.md#内置-skill-命令)。其中介绍 Kimi Code 自身的部分可以通过顶层 [`builtin_product_skills`](../configuration/config-files.md#顶层字段) 字段关闭。 +**内置 Skills** 随 CLI 一起分发,优先级最低,为常见任务提供开箱即用的工作流,例如配置 MCP server、定制 TUI 主题和编辑配置文件。完整列表详见[内置 Skill 命令](../reference/slash-commands.md#内置-skill-命令)。其中介绍 Kimi Code 自身的部分可以通过顶层 [`builtin_product_skills`](../configuration/config-files.md#顶层字段) 字段关闭。 ## 调用 Skill @@ -92,7 +92,7 @@ extra_skill_dirs = ["~/team-skills", ".agents/team-skills"] /skill:git-commits 修复登录接口的并发问题 ``` -模型也可以根据 `description` 和 `whenToUse` 自动调用 Skill(除非 `disableModelInvocation` 设为 `true` 或 `type` 为 `flow`)。Skill 调用时最多允许嵌套 3 层,超过后会被终止。 +模型也可以根据 `description` 和 `whenToUse` 自动调用 Skill。`disableModelInvocation` 设为 true 或 `type` 设为 flow 时不自动调用。Skill 调用最多允许嵌套 3 层,超过后会被终止。 ## 完整示例 @@ -122,7 +122,7 @@ arguments: - 值得肯定的地方 ``` -保存为 `$KIMI_CODE_HOME/skills/review-pr/SKILL.md`(未设置 `KIMI_CODE_HOME` 时为 `~/.kimi-code/skills/review-pr/SKILL.md`),检查清单放在同目录的 `references/checklist.md`,重开会话后即可通过 `/skill:review-pr #1234` 调用,其中 `#1234` 会展开到 `$pr_ref`。 +将文件保存为 `$KIMI_CODE_HOME/skills/review-pr/SKILL.md`,未设置 `KIMI_CODE_HOME` 时为 `~/.kimi-code/skills/review-pr/SKILL.md`。检查清单放在同目录的 `references/checklist.md`。重开会话后即可调用,例如 `/skill:review-pr #1234`,其中的参数会展开到 `$pr_ref`。 ## 下一步 diff --git a/docs/zh/customization/themes.md b/docs/zh/customization/themes.md index 2fd5e843075..ce4eb83ed65 100644 --- a/docs/zh/customization/themes.md +++ b/docs/zh/customization/themes.md @@ -8,16 +8,16 @@ Kimi Code CLI 可以使用内置配色,也可以使用自定义 JSON 主题文 | Token | `dark` | `light` | 控制什么 | | --- | --- | --- | --- | -| `primary` | `#4FA8FF` | `#1565C0` | 最常用色。链接、行内代码、几乎所有对话框的选中项、编辑器聚焦边框、Plan/运行中徽章、spinner | -| `accent` | `#5BC0BE` | `#00838F` | 次级强调。审批 `▶` 前缀、设备码框、图片占位、BTW/队列面板、注册表导入 | -| `text` | `#E0E0E0` | `#1A1A1A` | 正文。对话框正文、todo 标题、footer 模型名、Markdown 标题、助手/工具消息子弹头、列表符号 | +| `primary` | `#4FA8FF` | `#1565C0` | 最常用色。链接、行内代码、对话框选中项、聚焦边框、徽章、spinner | +| `accent` | `#5BC0BE` | `#00838F` | 次级强调。审批 `▶` 前缀、设备码框、图片占位、面板、注册表导入 | +| `text` | `#E0E0E0` | `#1A1A1A` | 正文。对话框正文、todo 标题、footer 模型名、Markdown 标题、列表符号 | | `textStrong` | `#F5F5F5` | `#1A1A1A` | 加粗强调文字。输入类对话框、状态消息 | -| `textDim` | `#888888` | `#454545` | 次级、变暗文字。思考、提示、描述、已完成 todo、Markdown 引用、footer 状态栏 | -| `textMuted` | `#6B6B6B` | `#5F5F5F` | 最浅文字。计数、滚动信息、描述、Markdown 链接 URL、代码块边框 | +| `textDim` | `#888888` | `#454545` | 次级、变暗文字。思考、提示、已完成 todo、Markdown 引用、footer 状态栏 | +| `textMuted` | `#6B6B6B` | `#5F5F5F` | 最浅文字。计数、滚动信息、Markdown 链接 URL、代码块边框 | | `border` | `#5A5A5A` | `#737373` | 面板与编辑器的普通边框、Markdown 分隔线 | | `borderFocus` | `#E8A838` | `#92660A` | 聚焦/注意边框,目前仅审批面板使用 | | `success` | `#4EC87E` | `#0E7A38` | 成功态。`✓`、已启用、完成 | -| `warning` | `#E8A838` | `#92660A` | 警告态。"Ask When Needed" / "Never Ask" 徽章、过期标记、Plan 模式提示 | +| `warning` | `#E8A838` | `#92660A` | 警告态。auto/yolo 徽章、过期标记、Plan 模式提示 | | `error` | `#E85454` | `#B91C1C` | 错误态。错误信息、失败的工具输出 | | `diffAdded` | `#4EC87E` | `#0E7A38` | diff 新增行 | | `diffRemoved` | `#E85454` | `#B91C1C` | diff 删除行 | @@ -26,11 +26,11 @@ Kimi Code CLI 可以使用内置配色,也可以使用自定义 JSON 主题文 | `diffGutter` | `#6B6B6B` | `#737373` | diff 行号槽 | | `diffMeta` | `#888888` | `#5F5F5F` | diff 元信息 / hunk 头 | | `roleUser` | `#FFCB6B` | `#9A4A00` | 用户消息的子弹头与文字、技能激活名 | -| `shellMode` | `#BD93F9` | `#7C3AED` | Shell 模式(`!`)的提示符、编辑器边框,以及回显的 `$ 命令` 行 | +| `shellMode` | `#BD93F9` | `#7C3AED` | Shell 模式(`!`)的提示符、编辑器边框、回显的命令行 | ## 使用 custom-theme skill -你不需要手写 JSON。运行内置 `/custom-theme [附加文本]` skill 命令进入自定义主题流程;这个 skill 可以帮你选颜色,把文件写到 `~/.kimi-code/themes/`,校验十六进制色值,并告诉你如何应用。 +你不需要手写 JSON。运行内置的 `/custom-theme [附加文本]` skill 进入自定义主题流程:它会帮你选颜色,把文件写到 `~/.kimi-code/themes/`,校验十六进制色值,并告诉你如何应用。 调用示例: @@ -38,7 +38,7 @@ Kimi Code CLI 可以使用内置配色,也可以使用自定义 JSON 主题文 - `/custom-theme Make a light theme based on Solarized, but keep errors easy to see.` - `/custom-theme Tweak my ember theme so diffs have higher contrast.` -激活后,skill 通常会先问你想用浅色还是深色基准、偏好的风格或调色板,以及是否有必须包含的精确颜色。如果你用它编辑已有主题,请确保它先读取并备份文件,再覆盖写入。 +激活后,skill 通常会先问你想用浅色还是深色基准、偏好的风格或调色板,以及是否有必须包含的精确颜色。如果用它编辑已有主题,确保它先读取并备份文件,再覆盖写入。 ## 创建一个主题 @@ -47,9 +47,9 @@ Kimi Code CLI 可以使用内置配色,也可以使用自定义 JSON 主题文 - `~/.kimi-code/themes/` - 如果设置了 `KIMI_CODE_HOME` 环境变量,则是 `$KIMI_CODE_HOME/themes/` -目录不存在就自己建一个。**文件名就是主题名**:`ember.json` 会在 `/theme` 里显示为 `Custom: ember`。 +目录不存在就自己建一个。文件名就是主题名:`ember.json` 会在 `/theme` 里显示为 `Custom: ember`。 -一个最小的主题只需要写你想改的颜色,其余自动沿用**基准调色板**(默认是 `dark`): +一个最小的主题只需要写你想改的颜色,其余自动沿用基准调色板(默认是 `dark`): ```json { @@ -65,7 +65,7 @@ Kimi Code CLI 可以使用内置配色,也可以使用自定义 JSON 主题文 - `name`(必填):主题的标识名。 - `displayName`(可选):人类可读的名字。 -- `base`(可选):未指定的 token 沿用哪个内置调色板——`"dark"`(默认)或 `"light"`。做**浅色**主题时设为 `"base": "light"`,这样你没写的 token 在浅色背景上仍然可读(否则会回退到 dark 调色板)。 +- `base`(可选):未指定的 token 沿用哪个内置调色板,`"dark"`(默认)或 `"light"`。做浅色主题时设为 `"light"`,否则未写的 token 会沿用 dark 调色板,在浅色背景上可能不可读。 - `colors`(可选):要覆盖的颜色 token,值是 6 位十六进制色值(如 `#FE8019`)。 使用 [内置颜色 token](#内置颜色-token) 里的 token 名。没有写到的 token 会自动回退到所选基准调色板的对应值,所以你完全可以只覆盖一部分: @@ -84,8 +84,8 @@ Kimi Code CLI 可以使用内置配色,也可以使用自定义 JSON 主题文 两种方式: -1. **`/theme` 命令**(推荐):打开主题选择器,自定义主题会以 `Custom: <文件名>` 出现。选择器**每次打开都会重新扫描主题目录**,所以你新加的主题文件**无需重启**就能看到。 -2. **`tui.toml`**:把 `theme` 设成你的主题名: +1. **`/theme` 命令**(推荐):打开主题选择器,自定义主题会以 `Custom: <文件名>` 出现。选择器每次打开都会重新扫描主题目录,新加的主题文件无需重启就能看到。 +2. **[`tui.toml`](../configuration/config-files.md#tuitoml)**:把 `theme` 设成你的主题名: ```toml # ~/.kimi-code/tui.toml @@ -102,11 +102,15 @@ Kimi Code CLI 可以使用内置配色,也可以使用自定义 JSON 主题文 ## 编辑正在使用的主题 -如果你修改的是**当前正在生效**的那个主题文件,改动不会自动重新加载。让新颜色生效有两种办法: +如果你修改的是当前正在生效的主题文件,改动不会自动重新加载。让新颜色生效有两种办法: -- 运行 `/reload-tui`——它会重新读取 `tui.toml` 并重新应用当前主题(包括重新读取主题文件); +- 运行 `/reload-tui`,它会重新读取 `tui.toml` 并重新应用当前主题(包括重新读取主题文件); - 或者在 `/theme` 里先切到另一个主题,再切回来。 ::: warning 注意 -在 `/theme` 里**重新选中同一个主题**不会触发重载(只会提示 “Theme unchanged”)。要重载已激活主题的改动,用上面两种办法之一。 +在 `/theme` 里重新选中同一个主题不会触发重载,只会提示 "Theme unchanged"。要重载已激活主题的改动,用上面两种办法之一。 ::: + +## 下一步 + +- [配置文件](../configuration/config-files.md#tuitoml) — `tui.toml` 的完整字段说明,包括 `theme` 配置项 From 26dd6ce6aec4456867af010b55dff92ba58f04ee Mon Sep 17 00:00:00 2001 From: 7Sageer Date: Thu, 3 Sep 2026 16:49:27 +0800 Subject: [PATCH 05/19] fix(telemetry): deduplicate session_started and model switch events (#3499) * fix(telemetry): deduplicate session_started and model switch events * fix(telemetry): keep engine session_started for direct v2 SDK clients and avoid model_switch race * fix(telemetry): preserve model_switch when activation rebinds the same alias * fix(telemetry): route TUI reload through harness * test: update /reload message-flow test for harness reload route --- apps/kimi-code/src/tui/commands/config.ts | 4 +- apps/kimi-code/src/tui/commands/provider.ts | 23 ++- apps/kimi-code/src/tui/commands/reload.ts | 7 +- .../src/tui/controllers/auth-flow.ts | 41 +++-- .../test/tui/commands/experiments.test.ts | 5 +- .../test/tui/commands/provider.test.ts | 70 ++++++++- .../test/tui/commands/reload.test.ts | 6 +- .../test/tui/controllers/auth-flow.test.ts | 146 ++++++++++++++++++ .../test/tui/kimi-tui-message-flow.test.ts | 7 +- packages/node-sdk/src/kimi-harness.ts | 4 +- packages/node-sdk/src/sdk-rpc-client-v2.ts | 27 ++++ .../node-sdk/test/sdk-rpc-client-v2.test.ts | 54 ++++++- 12 files changed, 366 insertions(+), 28 deletions(-) create mode 100644 apps/kimi-code/test/tui/controllers/auth-flow.test.ts diff --git a/apps/kimi-code/src/tui/commands/config.ts b/apps/kimi-code/src/tui/commands/config.ts index 3e9fa21660d..c798983aaa8 100644 --- a/apps/kimi-code/src/tui/commands/config.ts +++ b/apps/kimi-code/src/tui/commands/config.ts @@ -804,9 +804,9 @@ export async function applyExperimentalFeatureChanges( host.refreshSlashCommandAutocomplete(); host.restoreEditor(); if (host.session !== undefined) { - await host.session.reloadSession(); + const reloadedSession = await host.harness.reloadSession({ id: host.session.id }); await host.reloadCurrentSessionView( - host.session, + reloadedSession, 'Experimental features updated. Session reloaded.', ); } else { diff --git a/apps/kimi-code/src/tui/commands/provider.ts b/apps/kimi-code/src/tui/commands/provider.ts index 6ef4108b459..3a2f22e8ee5 100644 --- a/apps/kimi-code/src/tui/commands/provider.ts +++ b/apps/kimi-code/src/tui/commands/provider.ts @@ -306,18 +306,35 @@ export async function setDefaultModel( effort, model === undefined ? undefined : effectiveModelForHost(host, model), ); + if (host.session === undefined && host.engineV2) { + // A first prompt may still be inside lazy creation: wait it out so the + // pick lands on the new session instead of racing its assembly (same + // coordination as the /model path). + await host.waitForLazyCreation(); + } await host.harness.setConfig({ defaultModel: alias, thinking, }); - await host.authFlow.refreshConfigAfterLogin(); + // Whether activation made the engine emit model_switch (it reached a live + // session AND changed the bound alias — both engines track only an actual + // change). Recorded at activation time rather than snapshotted at entry: a + // lazy session can come live while the config writes above are pending; a + // session created BY activation (v1) or a same-alias rebind does not count + // — both bind the model without an engine event. + let engineTrackedSwitch = await host.authFlow.refreshConfigAfterLogin(); // refreshConfigAfterLogin reactivates from the persisted config, so a pick // the gate keeps session-only never reaches the runtime — apply it after // the refresh, or the persisted value would clobber it. if (thinking.effort === undefined && effort !== 'off' && effort !== 'on') { - await host.authFlow.activateModelAfterLogin(alias, effort); + engineTrackedSwitch = + (await host.authFlow.activateModelAfterLogin(alias, effort)) || engineTrackedSwitch; + } + // When the engine never emitted (no live session, or the alias was already + // bound), the TUI stays the sole producer for the pick. + if (!engineTrackedSwitch) { + host.track('model_switch', { model: alias }); } - host.track('model_switch', { model: alias }); host.showStatus(`Default model set to ${alias} with thinking ${effort}.`); } diff --git a/apps/kimi-code/src/tui/commands/reload.ts b/apps/kimi-code/src/tui/commands/reload.ts index 041ec2d246a..81b95ee484f 100644 --- a/apps/kimi-code/src/tui/commands/reload.ts +++ b/apps/kimi-code/src/tui/commands/reload.ts @@ -21,8 +21,11 @@ export async function handleReloadCommand(host: SlashCommandHost): Promise const session = host.session; if (session !== undefined) { - await session.reloadSession({ forcePluginSessionStartReminder: true }); - await host.reloadCurrentSessionView(session, 'Session reloaded.'); + const reloadedSession = await host.harness.reloadSession({ + id: session.id, + forcePluginSessionStartReminder: true, + }); + await host.reloadCurrentSessionView(reloadedSession, 'Session reloaded.'); } const config = await host.harness.getConfig({ reload: true }); diff --git a/apps/kimi-code/src/tui/controllers/auth-flow.ts b/apps/kimi-code/src/tui/controllers/auth-flow.ts index 0940e445a7c..5c06488b90a 100644 --- a/apps/kimi-code/src/tui/controllers/auth-flow.ts +++ b/apps/kimi-code/src/tui/controllers/auth-flow.ts @@ -75,14 +75,27 @@ export class AuthFlowController { this.host.setStartupReady(); } - async activateModelAfterLogin(model: string, effort?: string): Promise { + /** + * Apply a model pick to the runtime. Returns whether the activation made + * the engine emit `model_switch` — it reached an already-live session AND + * changed the bound alias (both engines track the event only on an actual + * alias change). `false` when no live session existed (v2 defers creation + * to the first prompt; v1 binds the model at creation without an event) or + * the alias was already bound, so callers mirroring the engine's telemetry + * must stay the producer for exactly those paths. Thinking-effort changes + * are orthogonal: the engine's `thinking_toggle` fires from `setThinking` + * regardless of this flag. + */ + async activateModelAfterLogin(model: string, effort?: string): Promise { const { host } = this; if (host.session !== undefined) { - await host.session.setModel(model); + const session = host.session; + const modelChanged = (await session.getStatus()).model !== model; + await session.setModel(model); if (effort !== undefined) { - await host.session.setThinking(effort); + await session.setThinking(effort); } - return; + return modelChanged; } if (host.engineV2) { @@ -96,7 +109,7 @@ export class AuthFlowController { patch.lazySessionThinking = effort as ThinkingEffort; } host.setAppState(patch); - return; + return false; } const options: MutableCreateSessionOptions = { @@ -131,9 +144,15 @@ export class AuthFlowController { host.updateTerminalTitle(); void host.refreshSkillCommands(host.session); void host.refreshPluginCommands(host.session); + return false; } - async refreshConfigAfterLogin(): Promise { + /** + * Re-read config and reactivate the persisted model after login or a + * config-refreshing command. Returns whatever the activation reports (see + * {@link activateModelAfterLogin}); `false` when no activation ran. + */ + async refreshConfigAfterLogin(): Promise { const { host } = this; const config = await host.harness.getConfig({ reload: true }); const availableModels = config.models ?? {}; @@ -148,16 +167,19 @@ export class AuthFlowController { await host.hydrateLazyConfigDefaults(); } host.setAppState({ availableModels, availableProviders }); - return; + return false; } - await this.activateModelAfterLogin(defaultModel, thinkingEffortFromConfig(config.thinking)); + const activated = await this.activateModelAfterLogin( + defaultModel, + thinkingEffortFromConfig(config.thinking), + ); if (host.session === undefined && host.engineV2) { // Session-less v2: also hydrate permission/plan defaults from the // refreshed config, same as startup. await host.hydrateLazyConfigDefaults(); host.setAppState({ availableModels, availableProviders }); - return; + return activated; } const appStatePatch: Partial = { availableModels, @@ -166,6 +188,7 @@ export class AuthFlowController { maxContextTokens: selected.maxContextSize, }; host.setAppState(appStatePatch); + return activated; } async refreshConfigAfterLogout(): Promise { diff --git a/apps/kimi-code/test/tui/commands/experiments.test.ts b/apps/kimi-code/test/tui/commands/experiments.test.ts index 9130e36356f..abeb8557d2a 100644 --- a/apps/kimi-code/test/tui/commands/experiments.test.ts +++ b/apps/kimi-code/test/tui/commands/experiments.test.ts @@ -42,6 +42,7 @@ function makeHost() { getExperimentalFeatures: vi.fn(async () => [ feature({ enabled: false, source: 'config', configValue: false }), ]), + reloadSession: vi.fn(async () => session), }, session, refreshSlashCommandAutocomplete: vi.fn(), @@ -56,6 +57,7 @@ function makeHost() { harness: { setConfig: ReturnType; getExperimentalFeatures: ReturnType; + reloadSession: ReturnType; }; refreshSlashCommandAutocomplete: ReturnType; reloadCurrentSessionView: ReturnType; @@ -88,7 +90,8 @@ describe('experimental feature command handlers', () => { expect(isExperimentalFlagEnabled('micro_compaction')).toBe(false); expect(host.refreshSlashCommandAutocomplete).toHaveBeenCalled(); expect(host.restoreEditor).toHaveBeenCalled(); - expect(host.session.reloadSession).toHaveBeenCalledOnce(); + expect(host.harness.reloadSession).toHaveBeenCalledWith({ id: host.session.id }); + expect(host.session.reloadSession).not.toHaveBeenCalled(); expect(host.reloadCurrentSessionView).toHaveBeenCalledWith( host.session, 'Experimental features updated. Session reloaded.', diff --git a/apps/kimi-code/test/tui/commands/provider.test.ts b/apps/kimi-code/test/tui/commands/provider.test.ts index 92efe4edb52..c338f0abfc2 100644 --- a/apps/kimi-code/test/tui/commands/provider.test.ts +++ b/apps/kimi-code/test/tui/commands/provider.test.ts @@ -13,7 +13,13 @@ import { describe, expect, it, vi } from 'vitest'; import type { SlashCommandHost } from '#/tui/commands'; import { setDefaultModel } from '#/tui/commands/provider'; -function makeHost() { +function makeHost( + options: { + refreshReachedLiveSession?: boolean; + activateReachedLiveSession?: boolean; + engineV2?: boolean; + } = {}, +) { const appState = { availableModels: { // Declares no efforts; the Anthropic profile inference supplies @@ -30,12 +36,14 @@ function makeHost() { }; const host = { state: { appState }, + engineV2: options.engineV2 === true, + waitForLazyCreation: vi.fn(async () => {}), harness: { setConfig: vi.fn(async () => ({})), }, authFlow: { - refreshConfigAfterLogin: vi.fn(async () => {}), - activateModelAfterLogin: vi.fn(async () => {}), + refreshConfigAfterLogin: vi.fn(async () => options.refreshReachedLiveSession === true), + activateModelAfterLogin: vi.fn(async () => options.activateReachedLiveSession === true), }, track: vi.fn(), showStatus: vi.fn(), @@ -45,6 +53,8 @@ function makeHost() { refreshConfigAfterLogin: ReturnType; activateModelAfterLogin: ReturnType; }; + waitForLazyCreation: ReturnType; + track: ReturnType; }; return { host }; } @@ -65,6 +75,9 @@ describe('setDefaultModel', () => { expect( host.authFlow.activateModelAfterLogin.mock.invocationCallOrder[0]!, ).toBeGreaterThan(host.authFlow.refreshConfigAfterLogin.mock.invocationCallOrder[0]!); + // Without a session the engine never sees the pick, so the TUI stays the + // sole model_switch producer. + expect(host.track).toHaveBeenCalledWith('model_switch', { model: 'opus' }); }); it('does not re-apply the effort when the pick persists', async () => { @@ -90,4 +103,55 @@ describe('setDefaultModel', () => { }); expect(host.authFlow.activateModelAfterLogin).not.toHaveBeenCalled(); }); + + it('leaves model_switch to the engine when activation changed the bound alias', async () => { + const { host } = makeHost({ refreshReachedLiveSession: true }); + + await setDefaultModel(host, 'opus', 'high'); + + // refreshConfigAfterLogin routed through session.setModel with a changed + // alias, which the engine already tracks — a TUI-side event would + // double-count the switch. + expect(host.track).not.toHaveBeenCalled(); + }); + + it('leaves model_switch to the engine when a lazy session came live mid-flow and rebounded', async () => { + // Session-less at entry, but the first prompt's lazy creation completes + // while setConfig / the refresh are pending, so the session-only re-apply + // lands on the now-live session and actually switches its alias (engine + // emits). + const { host } = makeHost({ activateReachedLiveSession: true }); + + await setDefaultModel(host, 'opus', 'xhigh'); + + expect(host.authFlow.activateModelAfterLogin).toHaveBeenCalledWith('opus', 'xhigh'); + expect(host.track).not.toHaveBeenCalled(); + }); + + it('emits model_switch when a v1-created session only rebinds the same alias', async () => { + // v1 session-less + session-only effort: the refresh creates the session + // with the picked model (creation emits nothing), then the re-apply + // reaches that live session but its setModel is an alias no-op (no engine + // event either) — the TUI must stay the producer for the pick. + const { host } = makeHost({ + refreshReachedLiveSession: false, + activateReachedLiveSession: false, + }); + + await setDefaultModel(host, 'opus', 'xhigh'); + + expect(host.authFlow.activateModelAfterLogin).toHaveBeenCalledWith('opus', 'xhigh'); + expect(host.track).toHaveBeenCalledWith('model_switch', { model: 'opus' }); + }); + + it('waits for an in-flight lazy creation before activating (v2)', async () => { + const { host } = makeHost({ engineV2: true }); + + await setDefaultModel(host, 'opus', 'high'); + + expect(host.waitForLazyCreation).toHaveBeenCalled(); + expect( + host.waitForLazyCreation.mock.invocationCallOrder[0]!, + ).toBeLessThan(host.harness.setConfig.mock.invocationCallOrder[0]!); + }); }); diff --git a/apps/kimi-code/test/tui/commands/reload.test.ts b/apps/kimi-code/test/tui/commands/reload.test.ts index e0d9352401e..ee48c05d2f9 100644 --- a/apps/kimi-code/test/tui/commands/reload.test.ts +++ b/apps/kimi-code/test/tui/commands/reload.test.ts @@ -78,9 +78,11 @@ auto_install = false await handleReloadCommand(host); - expect(session.reloadSession).toHaveBeenCalledWith({ + expect(host.harness.reloadSession).toHaveBeenCalledWith({ + id: session.id, forcePluginSessionStartReminder: true, }); + expect(session.reloadSession).not.toHaveBeenCalled(); expect(host.reloadCurrentSessionView).toHaveBeenCalledWith( session, 'Session reloaded.', @@ -205,6 +207,7 @@ function makeHost({ state, session, harness: { + reloadSession: vi.fn(async () => session), getConfig: vi.fn(async () => ({ models: { fresh: { provider: 'test', model: 'fresh-model', maxContextSize: 1000 }, @@ -227,6 +230,7 @@ function makeHost({ showStatus: vi.fn(), } as unknown as SlashCommandHost & { readonly harness: { + readonly reloadSession: ReturnType; readonly getConfig: ReturnType; readonly getExperimentalFeatures: ReturnType; }; diff --git a/apps/kimi-code/test/tui/controllers/auth-flow.test.ts b/apps/kimi-code/test/tui/controllers/auth-flow.test.ts new file mode 100644 index 00000000000..e562c71afd2 --- /dev/null +++ b/apps/kimi-code/test/tui/controllers/auth-flow.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + AuthFlowController, + type AuthFlowHost, +} from '#/tui/controllers/auth-flow'; + +function makeHost( + options: { + engineV2?: boolean; + withSession?: boolean; + defaultModel?: string; + boundModel?: string; + } = {}, +) { + const appState = { + workDir: '/tmp/work', + additionalDirs: [] as string[], + planMode: false, + model: 'old-model', + thinkingEffort: 'off', + }; + const session = + options.withSession === true + ? { + id: 'ses-live', + getStatus: vi.fn(async () => ({ model: options.boundModel ?? 'old-model' })), + setModel: vi.fn(async () => ({ model: 'k2', providerName: 'managed' })), + setThinking: vi.fn(async () => {}), + } + : undefined; + const host = { + state: { appState }, + session, + engineV2: options.engineV2 === true, + harness: { + createSession: vi.fn(async () => ({ id: 'ses-new', summary: { title: null } })), + getConfig: vi.fn(async () => ({ + defaultModel: options.defaultModel, + models: { k2: { provider: 'managed:kimi-code', model: 'kimi-k2', maxContextSize: 200_000 } }, + providers: {}, + })), + }, + options: { startup: {} }, + setAppState: vi.fn((patch: Record) => Object.assign(appState, patch)), + setStartupReady: vi.fn(), + resetSessionRuntime: vi.fn(), + setSession: vi.fn(async (next: unknown) => { + (host as { session: unknown }).session = next; + }), + syncRuntimeState: vi.fn(async () => {}), + appendStartupNotice: vi.fn(), + hydrateLazyConfigDefaults: vi.fn(async () => {}), + sessionEventHandler: { startSubscription: vi.fn() }, + fetchSessions: vi.fn(async () => {}), + updateTerminalTitle: vi.fn(), + refreshSkillCommands: vi.fn(async () => {}), + refreshPluginCommands: vi.fn(async () => {}), + } as unknown as AuthFlowHost & { + session: unknown; + harness: { + createSession: ReturnType; + getConfig: ReturnType; + }; + setAppState: ReturnType; + }; + return { host, appState, session }; +} + +describe('activateModelAfterLogin', () => { + it('reports an engine-tracked switch when the pick changes the bound alias', async () => { + const { host, session } = makeHost({ withSession: true }); + const authFlow = new AuthFlowController(host); + + const engineTrackedSwitch = await authFlow.activateModelAfterLogin('k2', 'high'); + + expect(engineTrackedSwitch).toBe(true); + expect(session!.setModel).toHaveBeenCalledWith('k2'); + expect(session!.setThinking).toHaveBeenCalledWith('high'); + }); + + it('reports no engine switch when the live session already binds the alias', async () => { + const { host, session } = makeHost({ withSession: true, boundModel: 'k2' }); + const authFlow = new AuthFlowController(host); + + // setModel is an alias no-op here, so neither engine emits model_switch — + // callers must stay the producer. The effort still goes through + // setThinking, whose thinking_toggle is the engine's own event. + const engineTrackedSwitch = await authFlow.activateModelAfterLogin('k2', 'high'); + + expect(engineTrackedSwitch).toBe(false); + expect(session!.setModel).toHaveBeenCalledWith('k2'); + expect(session!.setThinking).toHaveBeenCalledWith('high'); + }); + + it('only patches app state and reports no engine switch on the session-less v2 path', async () => { + const { host, appState } = makeHost({ engineV2: true }); + const authFlow = new AuthFlowController(host); + + const engineTrackedSwitch = await authFlow.activateModelAfterLogin('k2', 'high'); + + expect(engineTrackedSwitch).toBe(false); + expect(host.harness.createSession).not.toHaveBeenCalled(); + expect(appState.model).toBe('k2'); + expect(appState).toMatchObject({ lazySessionThinking: 'high' }); + }); + + it('creates the session on the session-less v1 path and still reports no engine switch', async () => { + const { host } = makeHost(); + const authFlow = new AuthFlowController(host); + + // The v1 creation binds the model without an engine model_switch event, + // so callers must treat this path as "no engine switch" even though + // host.session is defined afterwards. + const engineTrackedSwitch = await authFlow.activateModelAfterLogin('k2', 'high'); + + expect(engineTrackedSwitch).toBe(false); + expect(host.harness.createSession).toHaveBeenCalledWith( + expect.objectContaining({ model: 'k2', thinking: 'high' }), + ); + expect(host.session).toMatchObject({ id: 'ses-new' }); + }); +}); + +describe('refreshConfigAfterLogin', () => { + it('reports false without activating when no default model is configured', async () => { + const { host } = makeHost({ withSession: true }); + const authFlow = new AuthFlowController(host); + + const engineTrackedSwitch = await authFlow.refreshConfigAfterLogin(); + + expect(engineTrackedSwitch).toBe(false); + }); + + it('propagates the activation result for the persisted default model', async () => { + const live = makeHost({ withSession: true, defaultModel: 'k2' }); + const reachedLive = await new AuthFlowController(live.host).refreshConfigAfterLogin(); + expect(reachedLive).toBe(true); + expect(live.session!.setModel).toHaveBeenCalledWith('k2'); + + const lazy = makeHost({ engineV2: true, defaultModel: 'k2' }); + const reachedLazy = await new AuthFlowController(lazy.host).refreshConfigAfterLogin(); + expect(reachedLazy).toBe(false); + expect(lazy.host.harness.createSession).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts b/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts index 0528888f14f..dcc5c9414bc 100644 --- a/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts +++ b/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts @@ -301,6 +301,7 @@ function makeHarness(session = makeSession(), overrides: Record createSession: vi.fn(async () => session), resumeSession: vi.fn(async () => session), forkSession: vi.fn(async () => session), + reloadSession: vi.fn(async () => session), listSessions: vi.fn(async () => []), exportSession: vi.fn(async () => ({ zipPath: '/tmp/fake-session.zip', @@ -2113,11 +2114,15 @@ command = "vim" driver.handleUserInput('/reload'); await vi.waitFor(() => { - expect(session.reloadSession).toHaveBeenCalledOnce(); + expect(harness.reloadSession).toHaveBeenCalledWith({ + id: session.id, + forcePluginSessionStartReminder: true, + }); }); await vi.waitFor(() => { expect(driver.state.appState.theme).toBe('light'); }); + expect(session.reloadSession).not.toHaveBeenCalled(); expect(harness.track).toHaveBeenCalledWith('input_command', { command: 'reload' }); const transcript = stripSgr(renderTranscript(driver)); expect(transcript).toContain('hello before reload'); diff --git a/packages/node-sdk/src/kimi-harness.ts b/packages/node-sdk/src/kimi-harness.ts index c4e766f958e..101de82b65e 100644 --- a/packages/node-sdk/src/kimi-harness.ts +++ b/packages/node-sdk/src/kimi-harness.ts @@ -650,8 +650,8 @@ export class KimiHarness { // caller-supplied sessionStartedProperties that happen to share a key. // `client_id` is always null here: a single-process host has no // per-connection client id (that concept only exists for daemon clients, - // see core-impl.ts). Kept as an explicit key so both producers share the - // same session_started schema. + // see core-impl.ts). Kept as an explicit key so this row carries the + // same client-attribution shape as the daemon-client producer there. client_id: null, client_name: this.identity?.productName ?? null, client_version: this.identity?.version ?? null, diff --git a/packages/node-sdk/src/sdk-rpc-client-v2.ts b/packages/node-sdk/src/sdk-rpc-client-v2.ts index 59f9205e3ee..db57f0e2905 100644 --- a/packages/node-sdk/src/sdk-rpc-client-v2.ts +++ b/packages/node-sdk/src/sdk-rpc-client-v2.ts @@ -543,12 +543,17 @@ export class SDKRpcClientV2 extends SDKRpcClientBase { * section gates engine events the same way the v2 print runner gates them; * the host keeps owning the client's lifecycle (flush / shutdown stay with * the host, matching the v1 core's arrangement). + * + * The engine's own `session_started` is forwarded unless + * {@link suppressEngineSessionStarted} was called — see its doc for why the + * harness-assembled client drops that row. */ private installEngineTelemetry(client: TelemetryClient | undefined): void { if (client === undefined) return; const telemetry = this.app.accessor.get(ITelemetryService); telemetry.addAppender({ track: (record) => { + if (this.engineSessionStartedSuppressed && record.event === 'session_started') return; client.track(record.event, record.properties); }, }); @@ -557,6 +562,23 @@ export class SDKRpcClientV2 extends SDKRpcClientBase { }); } + private engineSessionStartedSuppressed = false; + + /** + * Drop the engine's own `session_started` from telemetry forwarding. Called + * by `createKimiHarnessV2` at assembly time: the harness emits that event + * for every session it opens (create / resume / reload / fork) with the + * richer client-attribution schema, so the engine's + * `{resumed, experimental_flags}` copy would double-count every open. + * Direct `SDKRpcClientV2` consumers never call this and keep the engine row + * — it is their only `session_started` producer. Hosts without a harness + * (run-v2-print, kap-server) wire their own appenders and are unaffected + * either way. + */ + suppressEngineSessionStarted(): void { + this.engineSessionStartedSuppressed = true; + } + /** * Exposed experimental flag ids in the `session_started` wire shape (sorted, * comma-joined), read live from the in-process engine's flag service. The @@ -2709,6 +2731,11 @@ export class SDKRpcClientV2 extends SDKRpcClientBase { export function createKimiHarnessV2(options: KimiHarnessOptions): KimiHarness { const rpc = new SDKRpcClientV2(options); + // The harness below emits session_started for every session it opens with + // the richer client-attribution schema; drop the engine's thinner copy from + // forwarding so each open is counted once. Direct SDKRpcClientV2 consumers + // keep the engine row. + rpc.suppressEngineSessionStarted(); return new KimiHarness(rpc, { identity: rpc.identity, uiMode: options.uiMode, diff --git a/packages/node-sdk/test/sdk-rpc-client-v2.test.ts b/packages/node-sdk/test/sdk-rpc-client-v2.test.ts index 8e0b05b3f24..172b6215a23 100644 --- a/packages/node-sdk/test/sdk-rpc-client-v2.test.ts +++ b/packages/node-sdk/test/sdk-rpc-client-v2.test.ts @@ -1358,7 +1358,7 @@ describe('SDKRpcClientV2 engine telemetry', () => { } }); - it('reports the same enabled experimental flags on every session_started row', async () => { + it('emits session_started once per open, with the harness schema and enabled experimental flags', async () => { const homeDir = await mkdtemp(join(tmpdir(), 'kimi-sdk-v2-tel-flags-')); tempDirs.push(homeDir); const workDir = await mkdtemp(join(tmpdir(), 'kimi-sdk-v2-tel-flags-work-')); @@ -1372,20 +1372,66 @@ describe('SDKRpcClientV2 engine telemetry', () => { }); try { const session = await harness.createSession({ workDir }); + // The harness row is the sole producer: the forwarding appender drops + // the engine's own session_started, or every open would double-count. const started = records.filter((record) => record.event === 'session_started'); - expect(started.length).toBeGreaterThanOrEqual(2); + expect(started).toHaveLength(1); + expect(started[0]).toMatchObject({ + sessionId: session.id, + properties: { + client_name: 'kimi-code-cli', + client_version: '0.0.0-test', + ui_mode: 'shell', + resumed: false, + }, + }); for (const record of started) { const flags = String(record.properties?.['experimental_flags'] ?? '').split(','); expect(flags).toContain('subagent_fork'); expect(flags).toContain('wait_for'); } - const distinct = new Set(started.map((record) => record.properties?.['experimental_flags'])); - expect(distinct.size).toBe(1); await session.close(); + await harness.resumeSession({ id: session.id }); + const afterResume = records.filter((record) => record.event === 'session_started'); + expect(afterResume).toHaveLength(2); + expect(afterResume[1]).toMatchObject({ + sessionId: session.id, + properties: { resumed: true }, + }); + const distinct = new Set(afterResume.map((record) => record.properties?.['experimental_flags'])); + expect(distinct.size).toBe(1); } finally { await harness.close(); } }); + + it('keeps forwarding the engine session_started to a direct SDKRpcClientV2 consumer', async () => { + const homeDir = await mkdtemp(join(tmpdir(), 'kimi-sdk-v2-tel-direct-')); + tempDirs.push(homeDir); + const workDir = await mkdtemp(join(tmpdir(), 'kimi-sdk-v2-tel-direct-work-')); + tempDirs.push(workDir); + const records: TelemetryRecord[] = []; + const client = new SDKRpcClientV2({ + homeDir, + identity: TEST_IDENTITY, + telemetry: recordingTelemetry(records), + }); + try { + // No harness wraps this client, so nothing else emits session_started — + // the engine's own row must survive forwarding. + const summary = await client.createSession({ workDir }); + const started = records.filter((record) => record.event === 'session_started'); + expect(started).toHaveLength(1); + expect(started[0]).toMatchObject({ properties: { resumed: false } }); + await client.closeSession({ sessionId: summary.id }); + await client.resumeSession({ id: summary.id }); + const afterResume = records.filter((record) => record.event === 'session_started'); + expect(afterResume).toHaveLength(2); + expect(afterResume[1]).toMatchObject({ properties: { resumed: true } }); + } finally { + await client.close(); + } + }); }); describe('removeProviderFromConfig', () => { From a0209469160770ad7440f1ad41eb8e35b8426b03 Mon Sep 17 00:00:00 2001 From: Haozhe Date: Thu, 3 Sep 2026 17:51:10 +0800 Subject: [PATCH 06/19] refactor(agent-core-v2): remove the staleGuard feature (#3517) * refactor(agent-core-v2): remove the staleGuard feature Drop the read-before-edit runtime guard: Edit/Write executions are no longer vetoed when the target file was never read or its mtime changed since the last read, and successful Read/Edit/Write no longer refresh a recorded mtime. Removes the staleGuard replayable state key and the staleGuard.recorded / staleGuard.cleared durable wire events; old wires keep replaying through the unknown-type skip path. apps/vis keeps projecting and rendering those historical records via locally declared legacy record types. * fix(agent-core-v2): skip retired wire record types silently during restore Restore reports every journal record whose type has no registered event class through onUnexpectedError. Sessions written before the staleGuard removal can hold a staleGuard.recorded entry per successful Read/Edit/Write, so loading one floods the log with WireError stacks. Keep a retired-type list of record types that were once durable vocabulary; restore skips them without reporting, while genuinely unknown records stay on the error path. --- apps/vis/server/src/lib/agent-record-types.ts | 26 +- .../agent-core-v2/docs/state-manifest.d.ts | 6 +- .../agent-core-v2/docs/wire-manifest.d.ts | 24 +- .../src/features/staleGuard/staleGuard.ts | 10 - .../features/staleGuard/staleGuardFeature.ts | 19 - .../src/features/staleGuard/staleGuardOps.ts | 41 -- .../features/staleGuard/staleGuardService.ts | 146 ----- packages/agent-core-v2/src/index.ts | 1 - .../src/state/eventDispatcherService.ts | 9 +- .../features/staleGuard/staleGuard.test.ts | 532 ------------------ packages/agent-core-v2/test/index.test.ts | 2 - .../test/state/builtinReplayableKeys.ts | 2 - .../test/state/eventDispatcher.test.ts | 2 + 13 files changed, 31 insertions(+), 789 deletions(-) delete mode 100644 packages/agent-core-v2/src/features/staleGuard/staleGuard.ts delete mode 100644 packages/agent-core-v2/src/features/staleGuard/staleGuardFeature.ts delete mode 100644 packages/agent-core-v2/src/features/staleGuard/staleGuardOps.ts delete mode 100644 packages/agent-core-v2/src/features/staleGuard/staleGuardService.ts delete mode 100644 packages/agent-core-v2/test/features/staleGuard/staleGuard.test.ts diff --git a/apps/vis/server/src/lib/agent-record-types.ts b/apps/vis/server/src/lib/agent-record-types.ts index ae541c0ff1d..f9082ba6c85 100644 --- a/apps/vis/server/src/lib/agent-record-types.ts +++ b/apps/vis/server/src/lib/agent-record-types.ts @@ -84,10 +84,6 @@ import type { PermissionRecordApprovalResult } from '@moonshot-ai/agent-core-v2/ import type { RuntimeSetBinding } from '@moonshot-ai/agent-core-v2/agent/runtimeBinding/runtimeBindingOps'; import type { SwarmModeEnter, SwarmModeExit } from '@moonshot-ai/agent-core-v2/features/swarm/swarmOps'; import type { TowerModeEnter, TowerModeExit } from '@moonshot-ai/agent-core-v2/features/tower/towerOps'; -import type { - StaleGuardCleared, - StaleGuardRecorded, -} from '@moonshot-ai/agent-core-v2/features/staleGuard/staleGuardOps'; import type { ToolsUpdateStore } from '@moonshot-ai/agent-core-v2/features/todo/todoOps'; /** A wire record with v2's literal `type` discriminant restored. v2 declares @@ -114,6 +110,22 @@ export interface MicroCompactionApplyRecord { readonly time?: number; } +/** v2-dropped durable record: removed with the staleGuard feature, but old + * wires still contain it. */ +export interface StaleGuardRecordedRecord { + readonly type: 'staleGuard.recorded'; + readonly path: string; + readonly mtimeMs: number; + readonly time?: number; +} + +/** v2-dropped durable record: removed with the staleGuard feature, but old + * wires still contain it. */ +export interface StaleGuardClearedRecord { + readonly type: 'staleGuard.cleared'; + readonly time?: number; +} + /** The wire file header record. Declared locally (rather than via v2's * `WireMetadataRecord`) so the union member keeps concrete field types — * the upstream interface carries an index signature that would widen @@ -169,8 +181,6 @@ export type AgentRecord = | WireRecordOf<'prompt.completed', PromptCompleted> | WireRecordOf<'prompt.steered', PromptSteered> | WireRecordOf<'runtime.set_binding', RuntimeSetBinding> - | WireRecordOf<'staleGuard.cleared', StaleGuardCleared> - | WireRecordOf<'staleGuard.recorded', StaleGuardRecorded> | WireRecordOf<'swarm_mode.enter', SwarmModeEnter> | WireRecordOf<'swarm_mode.exit', SwarmModeExit> | WireRecordOf<'task.started', TaskStarted> @@ -195,7 +205,9 @@ export type AgentRecord = | WireRecordOf<'turn.step.retrying', TurnStepRetrying> | WireRecordOf<'usage.record', UsageRecord> | ContextUpdateTokenCountRecord - | MicroCompactionApplyRecord; + | MicroCompactionApplyRecord + | StaleGuardRecordedRecord + | StaleGuardClearedRecord; /** Extract one record kind from the union. */ export type AgentRecordOf = Extract< diff --git a/packages/agent-core-v2/docs/state-manifest.d.ts b/packages/agent-core-v2/docs/state-manifest.d.ts index 783f8ce4454..72b14bf3284 100644 --- a/packages/agent-core-v2/docs/state-manifest.d.ts +++ b/packages/agent-core-v2/docs/state-manifest.d.ts @@ -27,7 +27,7 @@ // references become '(circular)', and class instances collapse to a '(ClassName)' // marker — the wire shape of an entry is the JSON projection of the type here. // -// Index (App: 0 keys · Workspace: 6 keys · Session: 9 keys · Agent: 83 keys) +// Index (App: 0 keys · Workspace: 6 keys · Session: 9 keys · Agent: 82 keys) // App // Workspace // workspaceDirs.ephemeralDirs src/workspace/workspaceDirs/workspaceDirsService.ts @@ -101,7 +101,6 @@ // runtime.binding src/agent/runtimeBinding/runtimeBindingService.ts // runtimeBinding src/agent/runtimeBinding/runtimeBindingOps.ts // shellCommand.tasks src/agent/shellCommand/shellCommandService.ts -// staleGuard src/features/staleGuard/staleGuardOps.ts // stepRetry.failedAttempts src/agent/stepRetry/stepRetryService.ts // stepRetry.lastFailedDriverId src/agent/stepRetry/stepRetryService.ts // swarm src/features/swarm/swarmOps.ts @@ -1519,9 +1518,6 @@ export interface AgentStateSnapshot { readonly id?: string; readonly revisionCount?: Readonly>; }; - // src/features/staleGuard/staleGuardOps.ts - // replayable · durable — folds: StaleGuardRecorded, StaleGuardCleared - 'staleGuard': /* StaleGuardModelState — packages/agent-core-v2/src/features/staleGuard/staleGuardOps.ts */ Map; // src/features/swarm/swarmOps.ts // replayable · durable — folds: SwarmModeEnter, SwarmModeExit 'swarm': 'task' | 'tool' | 'manual' | null; diff --git a/packages/agent-core-v2/docs/wire-manifest.d.ts b/packages/agent-core-v2/docs/wire-manifest.d.ts index 89e6a8b9656..2dae0c93ed3 100644 --- a/packages/agent-core-v2/docs/wire-manifest.d.ts +++ b/packages/agent-core-v2/docs/wire-manifest.d.ts @@ -24,7 +24,7 @@ // cross-reducers), blobs (the folding states whose blob codec offloads inline // media to blob storage), owner (the source file declaring the class). -// Index (62 record types) +// Index (60 record types) // config.update profile src/agent/profile/profileOps.ts // context.append_loop_event contextMemory, turn src/agent/contextMemory/contextEvents.ts // context.append_message contextMemory, plan, task.notificationDelivery src/agent/contextMemory/contextEvents.ts @@ -62,8 +62,6 @@ // prompt.completed promptResolution src/agent/prompt/promptService.ts // prompt.steered promptResolution src/agent/prompt/promptService.ts // runtime.set_binding runtimeBinding src/agent/runtimeBinding/runtimeBindingOps.ts -// staleGuard.cleared staleGuard src/features/staleGuard/staleGuardOps.ts -// staleGuard.recorded staleGuard src/features/staleGuard/staleGuardOps.ts // swarm_mode.enter swarm src/features/swarm/swarmOps.ts // swarm_mode.exit contextMemory, swarm src/features/swarm/swarmOps.ts // task.started task src/agent/task/taskOps.ts @@ -598,24 +596,6 @@ interface RuntimeSetBindingPayload { runtimeId: string; } -/** - * states: staleGuard - * owner: src/features/staleGuard/staleGuardOps.ts - */ -interface StaleGuardClearedPayload { - _name: 'staleGuard.cleared'; -} - -/** - * states: staleGuard - * owner: src/features/staleGuard/staleGuardOps.ts - */ -interface StaleGuardRecordedPayload { - _name: 'staleGuard.recorded'; - path: string; - mtimeMs: number; -} - /** * states: swarm * owner: src/features/swarm/swarmOps.ts @@ -973,8 +953,6 @@ interface WirePayloadMap { "prompt.completed": PromptCompletedPayload; "prompt.steered": PromptSteeredPayload; "runtime.set_binding": RuntimeSetBindingPayload; - "staleGuard.cleared": StaleGuardClearedPayload; - "staleGuard.recorded": StaleGuardRecordedPayload; "swarm_mode.enter": SwarmModeEnterPayload; "swarm_mode.exit": SwarmModeExitPayload; "task.started": TaskStartedPayload; diff --git a/packages/agent-core-v2/src/features/staleGuard/staleGuard.ts b/packages/agent-core-v2/src/features/staleGuard/staleGuard.ts deleted file mode 100644 index 83c05e90066..00000000000 --- a/packages/agent-core-v2/src/features/staleGuard/staleGuard.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; - -export interface IStaleGuardService { - readonly _serviceBrand: undefined; - - recordedMtimeMs(path: string): number | undefined; -} - -export const IStaleGuardService: ServiceIdentifier = - createDecorator('staleGuardService'); diff --git a/packages/agent-core-v2/src/features/staleGuard/staleGuardFeature.ts b/packages/agent-core-v2/src/features/staleGuard/staleGuardFeature.ts deleted file mode 100644 index 46f323e410b..00000000000 --- a/packages/agent-core-v2/src/features/staleGuard/staleGuardFeature.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ScopeActivation } from '#/_base/di/instantiation'; -import { Feature } from '#/features/feature'; -import { registerFeature } from '#/features/featureRegistry'; - -import { IStaleGuardService } from './staleGuard'; -import { StaleGuardService } from './staleGuardService'; - -export class StaleGuardFeature extends Feature { - static override readonly name = 'staleGuard'; - - constructor() { - super(); - this.contributeAgentService(IStaleGuardService, StaleGuardService, { - activation: ScopeActivation.OnScopeCreated, - }); - } -} - -registerFeature(StaleGuardFeature); diff --git a/packages/agent-core-v2/src/features/staleGuard/staleGuardOps.ts b/packages/agent-core-v2/src/features/staleGuard/staleGuardOps.ts deleted file mode 100644 index 3016deb533d..00000000000 --- a/packages/agent-core-v2/src/features/staleGuard/staleGuardOps.ts +++ /dev/null @@ -1,41 +0,0 @@ -/* oxlint-disable typescript-eslint/no-unsafe-declaration-merging, eslint-plugin-import/namespace -- Event2 class+payload-interface declaration merging is the sanctioned event-declaration idiom. */ -import { z } from 'zod'; - -import { Event2 } from '#/app/event/event2'; -import { defineState } from '#/state/state'; - -export type StaleGuardModelState = Map; - -const staleGuardRecordedSchema = z.object({ - path: z.string(), - mtimeMs: z.number(), -}); - -export class StaleGuardRecorded extends Event2> { - static override readonly type = 'staleGuard.recorded'; - static override readonly durable = true; - static override readonly schema = staleGuardRecordedSchema; -} -export interface StaleGuardRecorded extends z.infer {} - -const staleGuardClearedSchema = z.object({}); - -export class StaleGuardCleared extends Event2> { - static override readonly type = 'staleGuard.cleared'; - static override readonly durable = true; - static override readonly schema = staleGuardClearedSchema; -} -export interface StaleGuardCleared extends z.infer {} - -export const staleGuardKey = defineState( - 'staleGuard', - (): StaleGuardModelState => new Map(), -).replayable({ - schema: z.custom(), -}) - .on(StaleGuardRecorded, (s, e) => { - s.set(e.path, e.mtimeMs); - }) - .on(StaleGuardCleared, (s) => { - s.clear(); - }); diff --git a/packages/agent-core-v2/src/features/staleGuard/staleGuardService.ts b/packages/agent-core-v2/src/features/staleGuard/staleGuardService.ts deleted file mode 100644 index 3946e4c93cc..00000000000 --- a/packages/agent-core-v2/src/features/staleGuard/staleGuardService.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { Disposable } from '#/_base/di/lifecycle'; -import { IAgentStateService } from '#/agent/state/agentState'; -import { IAgentRuntimeService } from '#/agent/runtimeBinding/agentRuntime'; -import { denyToolExecution } from '#/agent/toolExecutor/beforeToolExecuteEvent'; -import { IAgentToolExecutorService } from '#/agent/toolExecutor/toolExecutor'; -import type { - BeforeToolExecuteEvent, - ToolDidExecuteContext, -} from '#/agent/toolExecutor/toolHooks'; -import type { ToolCall } from '#/kosong/contract/message'; -import type { HostFileStat } from '#/os/interface/hostFileSystem'; -import { IEventDispatcher } from '#/state/eventDispatcher'; -import type { ToolAccesses, ToolFileAccessOperation } from '#/tool/toolContract'; - -import { IStaleGuardService } from './staleGuard'; -import { StaleGuardCleared, StaleGuardRecorded, staleGuardKey } from './staleGuardOps'; - -const WRITE_OPERATIONS: readonly ToolFileAccessOperation[] = ['write', 'readwrite']; -const READ_OPERATIONS: readonly ToolFileAccessOperation[] = ['read']; - -function accessedFilePath( - accesses: ToolAccesses | undefined, - operations: readonly ToolFileAccessOperation[], -): string | undefined { - for (const access of accesses ?? []) { - if (access.kind === 'file' && operations.includes(access.operation)) return access.path; - } - return undefined; -} - -function stringArg(args: unknown, key: string): string | undefined { - if (typeof args !== 'object' || args === null) return undefined; - const value = (args as Record)[key]; - return typeof value === 'string' ? value : undefined; -} - -function callPathArg(call: ToolCall): string | undefined { - if (typeof call.arguments !== 'string') return undefined; - try { - return stringArg(JSON.parse(call.arguments), 'path'); - } catch { - return undefined; - } -} - -export class StaleGuardService extends Disposable implements IStaleGuardService { - declare readonly _serviceBrand: undefined; - - constructor( - @IAgentStateService private readonly states: IAgentStateService, - @IEventDispatcher private readonly dispatcher: IEventDispatcher, - @IAgentRuntimeService private readonly runtime: IAgentRuntimeService, - @IAgentToolExecutorService toolExecutor: IAgentToolExecutorService, - ) { - super(); - this.states.contributeState(staleGuardKey); - this._register(toolExecutor.onBeforeExecuteTool((event) => this.guardWrite(event))); - this._register( - toolExecutor.hooks.onDidExecuteTool.register('staleGuard', async (ctx, next) => { - await this.observeExecution(ctx); - await next(); - }), - ); - this._register( - this.runtime.onDidChange(() => { - void this.dispatcher.dispatch(new StaleGuardCleared({})); - }), - ); - } - - recordedMtimeMs(path: string): number | undefined { - return this.states.get(staleGuardKey).get(path); - } - - private guardWrite(event: BeforeToolExecuteEvent): void { - const name = event.toolCall.name; - if (name !== 'Edit' && name !== 'Write') return; - const path = accessedFilePath(event.execution.accesses, WRITE_OPERATIONS); - if (path === undefined) return; - const displayPath = stringArg(event.args, 'path') ?? path; - if (coveredByEarlierRead(event, displayPath)) return; - event.waitUntil(async () => { - const error = await this.checkWritable(path, displayPath); - return error === undefined ? undefined : { veto: denyToolExecution(error) }; - }); - } - - private async observeExecution(ctx: ToolDidExecuteContext): Promise { - if (ctx.outcome !== 'executed' || ctx.result.isError === true) return; - const name = ctx.toolCall.name; - if (name === 'Read') { - const path = accessedFilePath(ctx.accesses, READ_OPERATIONS); - if (path !== undefined) await this.recordCurrentMtime(path); - return; - } - if (name === 'Edit' || name === 'Write') { - const path = accessedFilePath(ctx.accesses, WRITE_OPERATIONS); - if (path !== undefined) await this.recordCurrentMtime(path); - } - } - - private async checkWritable(path: string, displayPath: string): Promise { - const stat = await this.statFile(path); - if (stat === undefined || stat.mtimeMs === undefined) return undefined; - const recorded = this.recordedMtimeMs(path); - if (recorded === undefined) { - return ( - `"${displayPath}" has not been read by this agent yet. ` + - 'Read the file before writing to it.' - ); - } - if (recorded !== stat.mtimeMs) { - return ( - `"${displayPath}" has been modified on disk since this agent last read it. ` + - 'Read the file again before writing to it.' - ); - } - return undefined; - } - - private async recordCurrentMtime(path: string): Promise { - const stat = await this.statFile(path); - if (stat?.mtimeMs === undefined) return; - await this.dispatcher.dispatch(new StaleGuardRecorded({ path, mtimeMs: stat.mtimeMs })); - } - - private async statFile(path: string): Promise { - const lease = this.runtime.acquire(['fs']); - try { - const stat = await lease.runtime.fs!.stat(path); - return stat.isFile ? stat : undefined; - } catch { - return undefined; - } finally { - lease.dispose(); - } - } -} - -function coveredByEarlierRead(event: BeforeToolExecuteEvent, rawPath: string): boolean { - for (const call of event.toolCalls) { - if (call.id === event.toolCall.id) return false; - if (call.name === 'Read' && callPathArg(call) === rawPath) return true; - } - return false; -} diff --git a/packages/agent-core-v2/src/index.ts b/packages/agent-core-v2/src/index.ts index 391e9f83a1d..4310c71a8c8 100644 --- a/packages/agent-core-v2/src/index.ts +++ b/packages/agent-core-v2/src/index.ts @@ -365,7 +365,6 @@ export * from '#/features/goal/goalService'; export * from '#/features/goal/goalOps'; export * from '#/features/goal/types'; import '#/features/goal/goalFeature'; -import '#/features/staleGuard/staleGuardFeature'; export * from '#/features/tower/flag'; export * from '#/features/tower/tower'; export * from '#/features/tower/towerFeature'; diff --git a/packages/agent-core-v2/src/state/eventDispatcherService.ts b/packages/agent-core-v2/src/state/eventDispatcherService.ts index f952f6f1f9a..c7ba7918a81 100644 --- a/packages/agent-core-v2/src/state/eventDispatcherService.ts +++ b/packages/agent-core-v2/src/state/eventDispatcherService.ts @@ -52,6 +52,11 @@ import { const MAX_DRAIN = 100; const HISTORY_TAIL = 500; +const RETIRED_WIRE_RECORD_TYPES: ReadonlySet = new Set([ + 'staleGuard.recorded', + 'staleGuard.cleared', +]); + export class CycleError extends StateError { constructor(readonly depth: number, readonly eventTypes: readonly string[]) { super( @@ -781,7 +786,9 @@ export class EventDispatcherService extends Service implements IEventDispatcher if (record.type === 'metadata') continue; const cls = this.folded.events.get(record.type); if (cls === undefined) { - this.reportSkippedRecord(record.type, recordIndex, false); + if (!RETIRED_WIRE_RECORD_TYPES.has(record.type)) { + this.reportSkippedRecord(record.type, recordIndex, false); + } recordIndex++; continue; } diff --git a/packages/agent-core-v2/test/features/staleGuard/staleGuard.test.ts b/packages/agent-core-v2/test/features/staleGuard/staleGuard.test.ts deleted file mode 100644 index db060de533d..00000000000 --- a/packages/agent-core-v2/test/features/staleGuard/staleGuard.test.ts +++ /dev/null @@ -1,532 +0,0 @@ -import { mkdtemp, readFile, rm, utimes, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; - -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; - -import { SyncDescriptor } from '#/_base/di/descriptors'; -import { DisposableStore, toDisposable } from '#/_base/di/lifecycle'; -import { TestInstantiationService } from '#/_base/di/test'; -import { IAgentBlobService } from '#/agent/blob/agentBlobService'; -import { IAgentStateService } from '#/agent/state/agentState'; -import { AgentStateService } from '#/agent/state/agentStateService'; -import { IAgentRuntimeService } from '#/agent/runtimeBinding/agentRuntime'; -import { IAgentToolExecutorService } from '#/agent/toolExecutor/toolExecutor'; -import type { - BeforeExecuteDecision, - BeforeToolExecuteEvent, - ToolDidExecuteContext, -} from '#/agent/toolExecutor/toolHooks'; -import { IEventBus } from '#/app/event/eventBus'; -import { EventBusService } from '#/app/event/eventBusService'; -import type { ToolCall } from '#/kosong/contract/message'; -import { IStaleGuardService } from '#/features/staleGuard/staleGuard'; -import { StaleGuardService } from '#/features/staleGuard/staleGuardService'; -import { HostFileSystem } from '#/os/backends/node-local/hostFsService'; -import type { HostFileStat, IHostFileSystem } from '#/os/interface/hostFileSystem'; -import { IEventDispatcher } from '#/state/eventDispatcher'; -import { EventDispatcherService } from '#/state/eventDispatcherService'; -import { ToolAccesses, type ExecutableToolResult } from '#/tool/toolContract'; -import { IWireService } from '#/wire/wire'; -import type { WireRecord } from '#/wire/record'; - -import { createTestAgent } from '../../harness'; -import { stubWireJournal } from '../../wire/stubs'; - -const noopBlob: IAgentBlobService = { - _serviceBrand: undefined, - offloadParts: async (parts) => parts, - loadParts: async (parts) => parts, - isBlobRef: () => false, -}; - -interface CapturedHooks { - readonly before: ((event: BeforeToolExecuteEvent) => unknown)[]; - readonly did: ((ctx: ToolDidExecuteContext, next: () => Promise) => Promise)[]; -} - -function stubToolExecutor(captured: CapturedHooks): IAgentToolExecutorService { - return { - _serviceBrand: undefined, - onBeforeExecuteTool: (listener: (event: BeforeToolExecuteEvent) => unknown) => { - captured.before.push(listener); - return toDisposable(() => {}); - }, - hooks: { - onDidExecuteTool: { - register: ( - _name: string, - handler: (ctx: ToolDidExecuteContext, next: () => Promise) => Promise, - ) => { - captured.did.push(handler); - return toDisposable(() => {}); - }, - }, - }, - } as unknown as IAgentToolExecutorService; -} - -let activeFs: IHostFileSystem; -let fireRuntimeChange: () => void = () => {}; - -function stubRuntime(): IAgentRuntimeService { - return { - _serviceBrand: undefined, - onDidChange: (listener: () => void) => { - fireRuntimeChange = listener; - return toDisposable(() => {}); - }, - acquire: () => ({ - runtime: { fs: activeFs }, - track: (resource: unknown) => resource, - dispose: () => {}, - }), - } as unknown as IAgentRuntimeService; -} - -function stubFs(stat: Partial | Error): IHostFileSystem { - return { - _serviceBrand: undefined, - stat: async () => { - if (stat instanceof Error) throw stat; - return { isFile: true, isDirectory: false, size: 0, ...stat }; - }, - } as unknown as IHostFileSystem; -} - -function enoent(): Error { - return Object.assign(new Error('ENOENT: no such file or directory'), { code: 'ENOENT' }); -} - -function outputText(result: ExecutableToolResult | undefined): string { - const output = result?.output; - if (typeof output !== 'string') throw new TypeError('expected string output'); - return output; -} - -async function runBeforeExecute( - captured: CapturedHooks, - input: { name: string; args?: unknown; accesses?: ToolAccesses; batch?: ToolCall[] }, -): Promise { - const pending: (() => Promise)[] = []; - let veto: ExecutableToolResult | undefined; - const toolCall = { - type: 'function', - id: 'call_1', - name: input.name, - arguments: JSON.stringify(input.args ?? {}), - } as ToolCall; - const event = { - turnId: 0, - signal: new AbortController().signal, - toolCall, - toolCalls: input.batch ?? [toolCall], - args: input.args, - execution: { accesses: input.accesses }, - veto: (result: ExecutableToolResult) => { - veto = result; - }, - allow: () => {}, - pass: () => {}, - waitUntil: (factory: () => Promise) => { - pending.push(factory); - }, - } as unknown as BeforeToolExecuteEvent; - for (const listener of captured.before) await listener(event); - for (const factory of pending) { - const decision = await factory(); - if (decision?.veto !== undefined) veto = decision.veto; - } - return veto; -} - -async function runDidExecute( - captured: CapturedHooks, - input: { name: string; accesses?: ToolAccesses; isError?: boolean }, -): Promise { - const ctx = { - turnId: 0, - signal: new AbortController().signal, - toolCall: { id: 'call_1', name: input.name }, - toolCalls: [], - args: {}, - outcome: 'executed', - accesses: input.accesses, - result: input.isError === true ? { output: 'failed', isError: true } : { output: 'ok' }, - } as unknown as ToolDidExecuteContext; - for (const handler of captured.did) await handler(ctx, async () => {}); -} - -describe('StaleGuardService', () => { - let disposables: DisposableStore; - let records: WireRecord[]; - let hooks: CapturedHooks; - let freshness: IStaleGuardService; - - function buildStack(journal: WireRecord[]): { - freshness: IStaleGuardService; - dispatcher: IEventDispatcher; - hooks: CapturedHooks; - } { - const captured: CapturedHooks = { before: [], did: [] }; - const ix = disposables.add(new TestInstantiationService()); - ix.set(IEventBus, new SyncDescriptor(EventBusService)); - ix.set(IAgentBlobService, noopBlob); - ix.set(IWireService, stubWireJournal(journal)); - ix.set(IAgentStateService, new AgentStateService()); - ix.set(IEventDispatcher, new SyncDescriptor(EventDispatcherService)); - ix.set(IAgentToolExecutorService, stubToolExecutor(captured)); - ix.set(IAgentRuntimeService, stubRuntime()); - ix.set(IStaleGuardService, new SyncDescriptor(StaleGuardService)); - return { - freshness: ix.get(IStaleGuardService), - dispatcher: ix.get(IEventDispatcher), - hooks: captured, - }; - } - - beforeEach(() => { - disposables = new DisposableStore(); - records = []; - activeFs = stubFs({}); - const stack = buildStack(records); - hooks = stack.hooks; - freshness = stack.freshness; - }); - - afterEach(() => { - disposables.dispose(); - }); - - it('records the mtime of a successfully read file into state and the wire journal', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile('/tmp/a.txt') }); - - expect(freshness.recordedMtimeMs('/tmp/a.txt')).toBe(111); - expect(records).toEqual([ - { type: 'staleGuard.recorded', path: '/tmp/a.txt', mtimeMs: 111, time: expect.any(Number) }, - ]); - }); - - it('does not record when the read failed', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - - await runDidExecute(hooks, { - name: 'Read', - accesses: ToolAccesses.readFile('/tmp/a.txt'), - isError: true, - }); - - expect(freshness.recordedMtimeMs('/tmp/a.txt')).toBeUndefined(); - expect(records).toEqual([]); - }); - - it('ignores tools without file semantics', async () => { - const veto = await runBeforeExecute(hooks, { name: 'Bash', args: { command: 'ls' } }); - expect(veto).toBeUndefined(); - - activeFs = stubFs({ mtimeMs: 111 }); - await runDidExecute(hooks, { name: 'Bash' }); - expect(records).toEqual([]); - }); - - it('vetoes editing an existing file the agent never read', async () => { - activeFs = stubFs({ mtimeMs: 5 }); - - const veto = await runBeforeExecute(hooks, { - name: 'Edit', - args: { path: '/tmp/a.txt', old_string: 'a', new_string: 'b' }, - accesses: ToolAccesses.readWriteFile('/tmp/a.txt'), - }); - - expect(veto?.isError).toBe(true); - expect(outputText(veto)).toContain('has not been read'); - expect(outputText(veto)).toContain('/tmp/a.txt'); - }); - - it('allows the write when the on-disk mtime matches the last read', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile('/tmp/a.txt') }); - - const veto = await runBeforeExecute(hooks, { - name: 'Write', - args: { path: '/tmp/a.txt', content: 'x' }, - accesses: ToolAccesses.writeFile('/tmp/a.txt'), - }); - - expect(veto).toBeUndefined(); - }); - - it('vetoes the write when the file changed on disk since the last read', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile('/tmp/a.txt') }); - activeFs = stubFs({ mtimeMs: 222 }); - - const veto = await runBeforeExecute(hooks, { - name: 'Edit', - args: { path: '/tmp/a.txt', old_string: 'a', new_string: 'b' }, - accesses: ToolAccesses.readWriteFile('/tmp/a.txt'), - }); - - expect(veto?.isError).toBe(true); - expect(outputText(veto)).toContain('modified on disk'); - }); - - it('allows a write covered by an earlier Read of the same path in the same batch', async () => { - activeFs = stubFs({ mtimeMs: 5 }); - const readCall: ToolCall = { - type: 'function', - id: 'call_0', - name: 'Read', - arguments: JSON.stringify({ path: '/tmp/a.txt' }), - }; - const writeCall: ToolCall = { - type: 'function', - id: 'call_1', - name: 'Write', - arguments: JSON.stringify({ path: '/tmp/a.txt', content: 'x' }), - }; - - const veto = await runBeforeExecute(hooks, { - name: 'Write', - args: { path: '/tmp/a.txt', content: 'x' }, - accesses: ToolAccesses.writeFile('/tmp/a.txt'), - batch: [readCall, writeCall], - }); - - expect(veto).toBeUndefined(); - }); - - it('still vetoes when the earlier batch Read targets a different path', async () => { - activeFs = stubFs({ mtimeMs: 5 }); - const readCall: ToolCall = { - type: 'function', - id: 'call_0', - name: 'Read', - arguments: JSON.stringify({ path: '/tmp/other.txt' }), - }; - const writeCall: ToolCall = { - type: 'function', - id: 'call_1', - name: 'Write', - arguments: JSON.stringify({ path: '/tmp/a.txt', content: 'x' }), - }; - - const veto = await runBeforeExecute(hooks, { - name: 'Write', - args: { path: '/tmp/a.txt', content: 'x' }, - accesses: ToolAccesses.writeFile('/tmp/a.txt'), - batch: [readCall, writeCall], - }); - - expect(veto?.isError).toBe(true); - expect(outputText(veto)).toContain('has not been read'); - }); - - it('clears recorded mtimes when the runtime changes', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile('/tmp/a.txt') }); - expect(freshness.recordedMtimeMs('/tmp/a.txt')).toBe(111); - - fireRuntimeChange(); - - expect(freshness.recordedMtimeMs('/tmp/a.txt')).toBeUndefined(); - expect(records).toContainEqual({ - type: 'staleGuard.cleared', - time: expect.any(Number), - }); - const veto = await runBeforeExecute(hooks, { - name: 'Edit', - args: { path: '/tmp/a.txt', old_string: 'a', new_string: 'b' }, - accesses: ToolAccesses.readWriteFile('/tmp/a.txt'), - }); - expect(outputText(veto)).toContain('has not been read'); - }); - - it('allows writing a file that does not exist yet', async () => { - activeFs = stubFs(enoent()); - - const veto = await runBeforeExecute(hooks, { - name: 'Write', - args: { path: '/tmp/new.txt', content: 'x' }, - accesses: ToolAccesses.writeFile('/tmp/new.txt'), - }); - - expect(veto).toBeUndefined(); - }); - - it('skips the check when the runtime stat carries no mtimeMs', async () => { - activeFs = stubFs({}); - - const veto = await runBeforeExecute(hooks, { - name: 'Edit', - args: { path: '/tmp/a.txt', old_string: 'a', new_string: 'b' }, - accesses: ToolAccesses.readWriteFile('/tmp/a.txt'), - }); - - expect(veto).toBeUndefined(); - }); - - it('skips the check when the path is not a regular file', async () => { - activeFs = stubFs({ isFile: false, isDirectory: true, mtimeMs: 5 }); - - const veto = await runBeforeExecute(hooks, { - name: 'Write', - args: { path: '/tmp/dir', content: 'x' }, - accesses: ToolAccesses.writeFile('/tmp/dir'), - }); - - expect(veto).toBeUndefined(); - }); - - it('refreshes the record after a successful write so consecutive writes are not blocked', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile('/tmp/a.txt') }); - - activeFs = stubFs({ mtimeMs: 222 }); - await runDidExecute(hooks, { name: 'Edit', accesses: ToolAccesses.readWriteFile('/tmp/a.txt') }); - - expect(freshness.recordedMtimeMs('/tmp/a.txt')).toBe(222); - const veto = await runBeforeExecute(hooks, { - name: 'Edit', - args: { path: '/tmp/a.txt', old_string: 'a', new_string: 'b' }, - accesses: ToolAccesses.readWriteFile('/tmp/a.txt'), - }); - expect(veto).toBeUndefined(); - }); - - it('rebuilds recorded mtimes from the wire journal on restore', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile('/tmp/a.txt') }); - - const replayed = buildStack([...records]); - await replayed.dispatcher.restore(); - - expect(replayed.freshness.recordedMtimeMs('/tmp/a.txt')).toBe(111); - activeFs = stubFs({ mtimeMs: 999 }); - const veto = await runBeforeExecute(replayed.hooks, { - name: 'Edit', - args: { path: '/tmp/a.txt', old_string: 'a', new_string: 'b' }, - accesses: ToolAccesses.readWriteFile('/tmp/a.txt'), - }); - expect(outputText(veto)).toContain('modified on disk'); - }); - - it('keeps records isolated between independent agent stacks', async () => { - activeFs = stubFs({ mtimeMs: 111 }); - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile('/tmp/a.txt') }); - - const other = buildStack([]); - - expect(other.freshness.recordedMtimeMs('/tmp/a.txt')).toBeUndefined(); - const veto = await runBeforeExecute(other.hooks, { - name: 'Edit', - args: { path: '/tmp/a.txt', old_string: 'a', new_string: 'b' }, - accesses: ToolAccesses.readWriteFile('/tmp/a.txt'), - }); - expect(outputText(veto)).toContain('has not been read'); - }); - - it('detects an external mtime change through the real filesystem', async () => { - const dir = await mkdtemp(join(tmpdir(), 'file-freshness-')); - const file = join(dir, 'a.txt'); - await writeFile(file, 'one', 'utf8'); - try { - activeFs = new HostFileSystem(); - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile(file) }); - - const past = new Date(Date.now() - 60_000); - await utimes(file, past, past); - - const veto = await runBeforeExecute(hooks, { - name: 'Edit', - args: { path: file, old_string: 'one', new_string: 'two' }, - accesses: ToolAccesses.readWriteFile(file), - }); - expect(outputText(veto)).toContain('modified on disk'); - - await runDidExecute(hooks, { name: 'Read', accesses: ToolAccesses.readFile(file) }); - const allowed = await runBeforeExecute(hooks, { - name: 'Edit', - args: { path: file, old_string: 'one', new_string: 'two' }, - accesses: ToolAccesses.readWriteFile(file), - }); - expect(allowed).toBeUndefined(); - } finally { - await rm(dir, { recursive: true, force: true }); - } - }); -}); - -describe('StaleGuardService in the agent test harness', () => { - it('is assembled by the feature seam with no manual registration', async () => { - const ctx = createTestAgent(); - try { - const svc = ctx.get(IStaleGuardService); - expect(svc).toBeDefined(); - expect(typeof svc.recordedMtimeMs).toBe('function'); - } finally { - await ctx.dispose(); - } - }); - - it('rejects an Edit with a stale-mtime error after an external modification', async () => { - const dir = await mkdtemp(join(tmpdir(), 'file-freshness-e2e-')); - const file = join(dir, 'a.txt'); - await writeFile(file, 'alpha beta', 'utf8'); - const ctx = createTestAgent(); - try { - await ctx.rpc.setPermission({ mode: 'yolo' }); - - const readCall: ToolCall = { - type: 'function', - id: 'call_read', - name: 'Read', - arguments: JSON.stringify({ path: file }), - }; - ctx.mockNextResponse({ type: 'text', text: 'Reading the file.' }, readCall); - ctx.mockNextResponse({ type: 'text', text: 'Read complete.' }); - await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Read the file' }] }); - await ctx.untilTurnEnd(); - - const past = new Date(Date.now() - 60_000); - await utimes(file, past, past); - - const editCall: ToolCall = { - type: 'function', - id: 'call_edit', - name: 'Edit', - arguments: JSON.stringify({ path: file, old_string: 'beta', new_string: 'gamma' }), - }; - ctx.mockNextResponse({ type: 'text', text: 'Editing the file.' }, editCall); - ctx.mockNextResponse({ type: 'text', text: 'Done.' }); - await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Edit the file' }] }); - await ctx.untilTurnEnd(); - - expect(toolResultText(ctx.llmCalls.at(-1)!.history)).toContain('modified on disk'); - expect(await readFile(file, 'utf8')).toBe('alpha beta'); - } finally { - await ctx.dispose(); - await rm(dir, { recursive: true, force: true }); - } - }); -}); - -function toolResultText(history: readonly { role: string; content: readonly unknown[] }[]): string { - return history - .filter((message) => message.role === 'tool') - .flatMap((message) => message.content) - .map((part) => { - if ( - part !== null && - typeof part === 'object' && - (part as { type?: unknown }).type === 'text' - ) { - const text = (part as { text?: unknown }).text; - return typeof text === 'string' ? text : ''; - } - return ''; - }) - .join('\n'); -} diff --git a/packages/agent-core-v2/test/index.test.ts b/packages/agent-core-v2/test/index.test.ts index 3cb93e5ef00..dfe27904a56 100644 --- a/packages/agent-core-v2/test/index.test.ts +++ b/packages/agent-core-v2/test/index.test.ts @@ -83,8 +83,6 @@ const V2_RECORD_TYPES: ReadonlySet = new Set([ 'task.started', 'task.terminated', 'task.waitDelivered', - 'staleGuard.recorded', - 'staleGuard.cleared', 'interaction.request', 'interaction.resolved', 'plan.revision', diff --git a/packages/agent-core-v2/test/state/builtinReplayableKeys.ts b/packages/agent-core-v2/test/state/builtinReplayableKeys.ts index 5bc043b6094..759ee2c3233 100644 --- a/packages/agent-core-v2/test/state/builtinReplayableKeys.ts +++ b/packages/agent-core-v2/test/state/builtinReplayableKeys.ts @@ -1,7 +1,6 @@ import type { ReplayableStateKey } from '#/state/state'; import { contextMemoryKey } from '#/agent/contextMemory/contextOps'; -import { staleGuardKey } from '#/features/staleGuard/staleGuardOps'; import { fullCompactionKey } from '#/agent/fullCompaction/compactionOps'; import { interruptionReminderKey } from '#/agent/interruptionReminder/interruptionReminderOps'; import { llmRequestTraceKey } from '#/agent/llmRequester/llmRequestOps'; @@ -27,7 +26,6 @@ import { towerBaseKey, towerKey, towerOwnerKey } from '#/features/tower/towerOps export const BUILTIN_REPLAYABLE_STATE_KEYS: readonly ReplayableStateKey[] = [ contextMemoryKey, - staleGuardKey, fullCompactionKey, interruptionReminderKey, llmRequestTraceKey, diff --git a/packages/agent-core-v2/test/state/eventDispatcher.test.ts b/packages/agent-core-v2/test/state/eventDispatcher.test.ts index 22e5545dc06..be4ce5c86a6 100644 --- a/packages/agent-core-v2/test/state/eventDispatcher.test.ts +++ b/packages/agent-core-v2/test/state/eventDispatcher.test.ts @@ -368,6 +368,8 @@ describe('EventDispatcherService', () => { IWireService, stubWireJournal([ { type: 'state.test.unknown', value: 1, time: 1 }, + { type: 'staleGuard.recorded', path: '/tmp/a.txt', mtimeMs: 111, time: 1 }, + { type: 'staleGuard.cleared', time: 1 }, { type: 'state.test.item.add', item: 42, time: 2 }, { type: 'state.test.item.add', item: 'ok', time: 3 }, ]), From ed215c61cb54f094ee2c45dbfbe70ee997804d94 Mon Sep 17 00:00:00 2001 From: 7Sageer Date: Thu, 3 Sep 2026 17:54:19 +0800 Subject: [PATCH 07/19] fix(telemetry): drop null values from flattened event payloads (#3518) --- .../src/app/telemetry/cloudTransport.ts | 8 +++++-- .../test/app/telemetry/cloudAppender.test.ts | 23 +++++++++++++++++++ packages/telemetry/src/transport.ts | 8 +++++-- packages/telemetry/test/telemetry.test.ts | 14 +++++++++-- 4 files changed, 47 insertions(+), 6 deletions(-) diff --git a/packages/agent-core-v2/src/app/telemetry/cloudTransport.ts b/packages/agent-core-v2/src/app/telemetry/cloudTransport.ts index 59ac07bd393..dc2c32f2c42 100644 --- a/packages/agent-core-v2/src/app/telemetry/cloudTransport.ts +++ b/packages/agent-core-v2/src/app/telemetry/cloudTransport.ts @@ -282,7 +282,9 @@ export function flattenEvent(event: EnrichedCloudEvent): Record, prefix: string, v if (value === null || typeof value !== 'object' || Array.isArray(value)) return; for (const [key, nestedValue] of Object.entries(value)) { assertPrimitive(`${prefix}.${key}`, nestedValue); - target[`${prefix}_${key}`] = nestedValue; + if (nestedValue !== null) { + target[`${prefix}_${key}`] = nestedValue; + } } } diff --git a/packages/agent-core-v2/test/app/telemetry/cloudAppender.test.ts b/packages/agent-core-v2/test/app/telemetry/cloudAppender.test.ts index 55464e09260..d933e0513c6 100644 --- a/packages/agent-core-v2/test/app/telemetry/cloudAppender.test.ts +++ b/packages/agent-core-v2/test/app/telemetry/cloudAppender.test.ts @@ -411,6 +411,29 @@ describe('CloudAppender', () => { ).toHaveLength(0); }); + it('drops null values from the outbound payload', async () => { + const requests: CapturedRequest[] = []; + const appender = new CloudAppender( + baseOptions({ + homeDir, + deviceId: 'dev123', + fetchImpl: makeFetch((req) => { + requests.push(req); + return okResponse(); + }), + }), + ); + + appender.track({ event: 'evt', context: {}, properties: { empty: null, keep: 'yes' } }); + await appender.flush(); + + expect(requests).toHaveLength(1); + const event = requests[0]?.body.events[0]; + expect(event?.['property_keep']).toBe('yes'); + expect(event).not.toHaveProperty('property_empty'); + expect(event).not.toHaveProperty('session_id'); + }); + it('drops non-primitive properties and reports the violation', async () => { const errors: unknown[] = []; setUnexpectedErrorHandler((err) => errors.push(err)); diff --git a/packages/telemetry/src/transport.ts b/packages/telemetry/src/transport.ts index 7f1544a78c3..5f1d31d0a92 100644 --- a/packages/telemetry/src/transport.ts +++ b/packages/telemetry/src/transport.ts @@ -265,7 +265,9 @@ export function flattenEvent(event: EnrichedTelemetryEvent): Record, prefix: strin if (value === null || typeof value !== 'object' || Array.isArray(value)) return; for (const [key, nestedValue] of Object.entries(value)) { assertPrimitive(`${prefix}.${key}`, nestedValue); - target[`${prefix}_${key}`] = nestedValue; + if (nestedValue !== null) { + target[`${prefix}_${key}`] = nestedValue; + } } } diff --git a/packages/telemetry/test/telemetry.test.ts b/packages/telemetry/test/telemetry.test.ts index 46e82be7cec..51cf18388a5 100644 --- a/packages/telemetry/test/telemetry.test.ts +++ b/packages/telemetry/test/telemetry.test.ts @@ -498,12 +498,18 @@ describe('payload assembly', () => { expect(() => buildPayload([arrayProperty], 'device-1')).toThrow(/property.list/); }); - it('passes null primitive values through and leaves the input event untouched', () => { + it('drops null values from the payload and leaves the input event untouched', () => { const event = { ...sampleEvent('nullable'), + device_id: null, + session_id: null, properties: { empty: null, }, + context: { + version: '1.2.3', + empty: null, + }, }; const originalProperties = event.properties; const originalContext = event.context; @@ -512,8 +518,12 @@ describe('payload assembly', () => { expect(payload.events[0]).toMatchObject({ event: 'kfc_nullable', - property_empty: null, + context_version: '1.2.3', }); + expect(payload.events[0]).not.toHaveProperty('device_id'); + expect(payload.events[0]).not.toHaveProperty('session_id'); + expect(payload.events[0]).not.toHaveProperty('property_empty'); + expect(payload.events[0]).not.toHaveProperty('context_empty'); expect(event.properties).toBe(originalProperties); expect(event.context).toBe(originalContext); expect(event.event).toBe('nullable'); From b199e3326de28d5094ca5f18816a74ab336c51e0 Mon Sep 17 00:00:00 2001 From: Kai Date: Thu, 3 Sep 2026 19:26:30 +0800 Subject: [PATCH 08/19] feat(agent-core-v2): remind the model of its context budget and point compaction notes at the wire journal (#3423) * feat(agent-core-v2): remind the model of its context budget and point compaction notes at the wire journal Add the contextBudget feature: a context_budget reminder that restates used/max/trigger tokens as usage crosses half, three quarters and ninety percent of the compaction trigger, and a compaction_ahead reminder delivered once per window when the trigger is within ten percent of the context window, so the model can persist and verify state while it can still call tools. Both read IAgentFullCompactionService.budget(), which derives from the same CompactionTriggerBudget that drives auto compaction, and both are stripped from the summarizer input. Behind compaction_recovery_pointer, compaction records the wire journal line range it covered (wireLines on context.apply_compaction, folded into the replayable fullCompaction.wireRanges key) and appends a Context Recovery footer to the model-facing contextSummary with the on-disk wire.jsonl path, every earlier window's line range, and a primer on reading the journal; the UI-facing summary stays the note plus TODO. Read returns wire.jsonl lines under the sessions directory untruncated and spill-exempt so a single record can be read back after Grep locates it, and the compaction instruction tells the summarizer a recovery pointer follows the note. Both flags default on; KIMI_CODE_EXPERIMENTAL_CONTEXT_BUDGET_REMINDERS=0 and KIMI_CODE_EXPERIMENTAL_COMPACTION_RECOVERY_POINTER=0 disable them. Telemetry gains context_budget_reminder, compaction_ahead_reminder, and ahead_* fields on compaction_finished. * feat(agent-core-v2): ship context budget reminders and the recovery pointer without flags - Remove the two experimental flags; both behaviors now ship unconditionally and the compaction instruction carries the recovery note in its template. - Lower-bound recovery windows at the latest context.clear journal record so a window never points into history the user discarded. - Add the appended recovery footer's estimated tokens to summaryOutputTokens so tokens_after and the post-compaction token floor stay honest. * fix(agent-core-v2): cap event log reads and refuse empty-history compaction - Cap a single wire.jsonl record read at 150k chars, below the window-minus-trigger margin, so one read can never push the context past the model window; the note points at sed | jq for longer records. - Keep at least the last record when tail-reading the event log instead of returning silently empty output with a contradictory note. - Fail the compaction when an overflow shrink would drop every message, instead of compacting an empty history and replacing the context with a groundless note. * fix(agent-core-v2): drop the redundant ninety bucket and soften ahead-reminder wording - Remove the 90% context-budget bucket: the compaction-ahead threshold is always at or below it, so it only echoed the stronger last-chance reminder moments later. - Stop suggesting a commit as a way to persist state before compaction; files and the todo list cover it without prompting unwanted commits. - Make the event-log note's primer reference conditional on a compaction having run. * chore: merge the compaction changesets into one --- .changeset/compaction-context-budget.md | 5 + .../agent-core-v2/docs/state-manifest.d.ts | 8 +- .../src/agent/contextMemory/contextEvents.ts | 3 + .../src/agent/contextMemory/contextMemory.ts | 2 + .../contextMemory/contextMemoryService.ts | 1 + .../fullCompaction/compaction-instruction.md | 2 + .../fullCompaction/compactionInstruction.ts | 15 + .../src/agent/fullCompaction/compactionOps.ts | 17 + .../fullCompaction/context-recovery-footer.md | 10 + .../agent/fullCompaction/contextRecovery.ts | 28 ++ .../agent/fullCompaction/fullCompaction.ts | 6 + .../fullCompaction/fullCompactionService.ts | 89 ++++- .../src/agent/fullCompaction/strategy.ts | 30 ++ .../toolResultTruncation.ts | 2 + .../toolResultTruncationService.ts | 9 +- .../src/agent/tools/os/read/read.md | 1 + .../src/agent/tools/os/read/read.ts | 1 + .../src/agent/tools/os/read/readTool.ts | 51 ++- .../agent-core-v2/src/app/telemetry/events.ts | 43 +++ .../contextBudget/compaction-ahead.md | 8 + .../features/contextBudget/context-budget.md | 5 + .../contextBudget/contextBudgetFeature.ts | 15 + .../contextBudget/contextBudgetReminder.ts | 124 +++++++ .../contextBudget/contextBudgetService.ts | 125 +++++++ .../src/features/reminder/reminderService.ts | 6 +- packages/agent-core-v2/src/index.ts | 5 + packages/agent-core-v2/src/wire/record.ts | 5 + packages/agent-core-v2/src/wire/wire.ts | 3 + .../agent-core-v2/src/wire/wireService.ts | 33 ++ .../fullCompaction/fullCompaction.test.ts | 308 +++++++++++++++++- .../agent/fullCompaction/strategy.test.ts | 71 ++++ .../test/agent/loop/loop.test.ts | 4 +- .../agent-core-v2/test/agent/loop/stubs.ts | 2 +- .../test/agent/task/taskService.test.ts | 3 + .../agent/toolExecutor/toolExecutor.test.ts | 1 + .../test/agent/toolResultTruncation/stubs.ts | 1 + .../toolResultTruncation.test.ts | 14 + .../contextBudget/contextBudget.test.ts | 178 ++++++++++ packages/agent-core-v2/test/index.test.ts | 1 + .../os/backends/node-local/tools/read.test.ts | 94 +++++- .../test/state/builtinReplayableKeys.ts | 3 +- .../test/state/eventDispatcher.test.ts | 3 + packages/agent-core-v2/test/tool/tool.test.ts | 10 +- packages/agent-core-v2/test/wire/stubs.ts | 3 + .../test/wire/wireService.test.ts | 68 +++- 45 files changed, 1377 insertions(+), 39 deletions(-) create mode 100644 .changeset/compaction-context-budget.md create mode 100644 packages/agent-core-v2/src/agent/fullCompaction/compactionInstruction.ts create mode 100644 packages/agent-core-v2/src/agent/fullCompaction/context-recovery-footer.md create mode 100644 packages/agent-core-v2/src/agent/fullCompaction/contextRecovery.ts create mode 100644 packages/agent-core-v2/src/features/contextBudget/compaction-ahead.md create mode 100644 packages/agent-core-v2/src/features/contextBudget/context-budget.md create mode 100644 packages/agent-core-v2/src/features/contextBudget/contextBudgetFeature.ts create mode 100644 packages/agent-core-v2/src/features/contextBudget/contextBudgetReminder.ts create mode 100644 packages/agent-core-v2/src/features/contextBudget/contextBudgetService.ts create mode 100644 packages/agent-core-v2/test/features/contextBudget/contextBudget.test.ts diff --git a/.changeset/compaction-context-budget.md b/.changeset/compaction-context-budget.md new file mode 100644 index 00000000000..4217e6ff5a8 --- /dev/null +++ b/.changeset/compaction-context-budget.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/kimi-code": minor +--- + +Remind the model of its context budget before automatic compaction, and after compaction point it at the session's event log for exact details. diff --git a/packages/agent-core-v2/docs/state-manifest.d.ts b/packages/agent-core-v2/docs/state-manifest.d.ts index 72b14bf3284..8846f7bc5f0 100644 --- a/packages/agent-core-v2/docs/state-manifest.d.ts +++ b/packages/agent-core-v2/docs/state-manifest.d.ts @@ -27,7 +27,7 @@ // references become '(circular)', and class instances collapse to a '(ClassName)' // marker — the wire shape of an entry is the JSON projection of the type here. // -// Index (App: 0 keys · Workspace: 6 keys · Session: 9 keys · Agent: 82 keys) +// Index (App: 0 keys · Workspace: 6 keys · Session: 9 keys · Agent: 83 keys) // App // Workspace // workspaceDirs.ephemeralDirs src/workspace/workspaceDirs/workspaceDirsService.ts @@ -66,6 +66,7 @@ // fullCompaction.consecutiveOverflowCompactions src/agent/fullCompaction/fullCompactionService.ts // fullCompaction.lastCompactedTokenCount src/agent/fullCompaction/fullCompactionService.ts // fullCompaction.observedMaxContextTokensByModel src/agent/fullCompaction/fullCompactionService.ts +// fullCompaction.wireRanges src/agent/fullCompaction/compactionOps.ts // interruptionReminder src/agent/interruptionReminder/interruptionReminderOps.ts // llm.requestTrace src/agent/llmRequester/llmRequestOps.ts // llmRequester.emittedThinkingEffortWarnings src/agent/llmRequester/llmRequesterService.ts @@ -1176,6 +1177,11 @@ export interface AgentStateSnapshot { 'fullCompaction': /* CompactionState — packages/agent-core-v2/src/agent/fullCompaction/compactionOps.ts */ { readonly phase: /* CompactionPhase — packages/agent-core-v2/src/agent/fullCompaction/compactionOps.ts */ 'completed' | 'cancelled' | 'running' | 'idle'; }; + // replayable · durable — folds: ContextApplyCompaction, ContextClear + 'fullCompaction.wireRanges': readonly /* WireLineRange — packages/agent-core-v2/src/wire/record.ts */ { + readonly start: number; + readonly end: number; + }[]; // src/agent/fullCompaction/fullCompactionService.ts 'fullCompaction.activeTurnId': number | undefined; 'fullCompaction.compactionCountInTurn': number; diff --git a/packages/agent-core-v2/src/agent/contextMemory/contextEvents.ts b/packages/agent-core-v2/src/agent/contextMemory/contextEvents.ts index 2021c8bd766..3300d4ce671 100644 --- a/packages/agent-core-v2/src/agent/contextMemory/contextEvents.ts +++ b/packages/agent-core-v2/src/agent/contextMemory/contextEvents.ts @@ -63,6 +63,9 @@ const contextCompactionBaseShape = { keptHeadUserMessageCount: z.number().optional(), droppedCount: z.number().optional(), legacyTail: z.boolean().optional(), + wireLines: z + .object({ start: z.number().int().nonnegative(), end: z.number().int().nonnegative() }) + .optional(), }; const contextApplyCompactionSchema = z.union([ diff --git a/packages/agent-core-v2/src/agent/contextMemory/contextMemory.ts b/packages/agent-core-v2/src/agent/contextMemory/contextMemory.ts index 1e7162b9680..9a490ec9a3e 100644 --- a/packages/agent-core-v2/src/agent/contextMemory/contextMemory.ts +++ b/packages/agent-core-v2/src/agent/contextMemory/contextMemory.ts @@ -1,4 +1,5 @@ import { createDecorator } from "#/_base/di/instantiation"; +import type { WireLineRange } from '#/wire/record'; import type { UndoCut } from './contextOps'; import type { LoopRecordedEvent } from './loopEventFold'; @@ -15,6 +16,7 @@ export interface ContextCompactionInput { readonly keptUserMessageCount?: number; readonly keptHeadUserMessageCount?: number; readonly droppedCount?: number; + readonly wireLines?: WireLineRange; } export interface ContextCompactionResult { diff --git a/packages/agent-core-v2/src/agent/contextMemory/contextMemoryService.ts b/packages/agent-core-v2/src/agent/contextMemory/contextMemoryService.ts index a2ccddc31b2..f29cc89e8fd 100644 --- a/packages/agent-core-v2/src/agent/contextMemory/contextMemoryService.ts +++ b/packages/agent-core-v2/src/agent/contextMemory/contextMemoryService.ts @@ -131,6 +131,7 @@ export class AgentContextMemoryService extends Disposable implements IAgentConte keptUserMessageCount: result.keptUserMessageCount, keptHeadUserMessageCount: result.keptHeadUserMessageCount, droppedCount: result.droppedCount, + wireLines: input.wireLines, }), ); this.tokenCounting.rebase(this.scopeContext.agentContext, { diff --git a/packages/agent-core-v2/src/agent/fullCompaction/compaction-instruction.md b/packages/agent-core-v2/src/agent/fullCompaction/compaction-instruction.md index 4f0b4279c2a..fc30e61a353 100644 --- a/packages/agent-core-v2/src/agent/fullCompaction/compaction-instruction.md +++ b/packages/agent-core-v2/src/agent/fullCompaction/compaction-instruction.md @@ -52,6 +52,8 @@ continue: here is one less thing the next turn must rediscover. Include any required format for the final answer. +This conversation's event log stays on disk and a recovery pointer is appended below your note automatically, so you need not reproduce long outputs verbatim — keep exact identifiers, key values and error lines, and name anything the next turn should look up. + Your TODO list is re-attached automatically below this note from its live source, so do not transcribe it — copying it wastes space and can contradict the live version. What that list cannot hold is the reasoning between tasks — why one diff --git a/packages/agent-core-v2/src/agent/fullCompaction/compactionInstruction.ts b/packages/agent-core-v2/src/agent/fullCompaction/compactionInstruction.ts new file mode 100644 index 00000000000..cd3a10f916f --- /dev/null +++ b/packages/agent-core-v2/src/agent/fullCompaction/compactionInstruction.ts @@ -0,0 +1,15 @@ +import { renderPrompt } from '#/_base/utils/render-prompt'; + +import compactionInstructionTemplate from './compaction-instruction.md?raw'; + +export interface CompactionInstructionInput { + readonly customInstruction?: string; +} + +export function renderCompactionInstruction(input: CompactionInstructionInput): string { + const customInstruction = input.customInstruction?.trim() ?? ''; + return renderPrompt(compactionInstructionTemplate, { + custom_instruction_block: + customInstruction.length > 0 ? `\nOptional user instruction:\n${customInstruction}\n` : '', + }).trimEnd(); +} diff --git a/packages/agent-core-v2/src/agent/fullCompaction/compactionOps.ts b/packages/agent-core-v2/src/agent/fullCompaction/compactionOps.ts index c5816594515..a1b2bb25a48 100644 --- a/packages/agent-core-v2/src/agent/fullCompaction/compactionOps.ts +++ b/packages/agent-core-v2/src/agent/fullCompaction/compactionOps.ts @@ -3,6 +3,12 @@ import { z } from 'zod'; import { AgentEvent2, type AgentDomainTrait } from '#/app/event/event2'; import { defineState } from '#/state/state'; +import { + ContextApplyCompaction, + ContextClear, + type ContextApplyCompactionPayload, +} from '#/agent/contextMemory/contextEvents'; +import type { WireLineRange } from '#/wire/record'; import type { CompactionBeginData, CompactionResult, CompactionSource } from './types'; @@ -123,3 +129,14 @@ export const fullCompactionKey = defineState( s.phase = 'idle'; } }); + +export const fullCompactionWireRangesKey = defineState( + 'fullCompaction.wireRanges', + () => [], +) + .replayable({ schema: z.custom() }) + .on(ContextApplyCompaction, (s, e) => { + const wireLines = (e as unknown as ContextApplyCompactionPayload).wireLines; + return wireLines === undefined ? undefined : [...s, wireLines]; + }) + .on(ContextClear, (s) => (s.length === 0 ? undefined : [])); diff --git a/packages/agent-core-v2/src/agent/fullCompaction/context-recovery-footer.md b/packages/agent-core-v2/src/agent/fullCompaction/context-recovery-footer.md new file mode 100644 index 00000000000..5aba814ea31 --- /dev/null +++ b/packages/agent-core-v2/src/agent/fullCompaction/context-recovery-footer.md @@ -0,0 +1,10 @@ +## Context Recovery +Everything before this note is still on disk in this agent's event log (read-only, append-only): + ${wire_path} +${window_lines} +If you need exact command output, file contents, error text, or the wording of an earlier request, look it up there instead of guessing. How to read it: +- Layout: one file per agent. agents/main/ is the main agent; each subagent has its own agents//wire.jsonl. A parent's log holds only the Agent tool call and the subagent's returned result — the subagent's own steps are in its own file. +- Format: one JSON record per line, append-only; `type` says what it is. The conversation is in `context.append_message` (user prompts) and `context.append_loop_event` (event.type: step.begin | content.part [text|think] | tool.call | tool.result | step.end). Every other type (llm.request, usage.record, token_counting.measured, metadata, profile.bind, …) is bookkeeping — skip it. +- Boundaries: `context.apply_compaction` marks a compaction (older lines stay in the file; grep for it to find exact boundaries). `context.undo` count=N retracts the previous N messages — treat retracted content as never having happened. `context.clear` resets the conversation. +- Externalized content: tool results over 50k chars are stored truncated, with an `output_path` to a tool-results/*.txt file holding the full text. Media parts are blob references, not inline. +- Reading: lines are long JSON (often 10k+ chars). Grep the file for a keyword to get line numbers, then Read exactly that line (line_offset=N, n_lines=1) — Read returns wire.jsonl lines whole up to ~150k chars. To pull one field with real newlines: sed -n 'Np' wire.jsonl | jq -r '.event.result.output'. Never Read large ranges — a handful of records can exceed the per-call byte cap. diff --git a/packages/agent-core-v2/src/agent/fullCompaction/contextRecovery.ts b/packages/agent-core-v2/src/agent/fullCompaction/contextRecovery.ts new file mode 100644 index 00000000000..430f821c46d --- /dev/null +++ b/packages/agent-core-v2/src/agent/fullCompaction/contextRecovery.ts @@ -0,0 +1,28 @@ +import { renderPrompt } from '#/_base/utils/render-prompt'; +import type { WireLineRange } from '#/wire/record'; + +import contextRecoveryTemplate from './context-recovery-footer.md?raw'; + +export const CONTEXT_RECOVERY_HEADING = '## Context Recovery'; + +export interface ContextRecoveryPointer { + readonly journalPath: string; + readonly windows: readonly WireLineRange[]; +} + +export function renderContextRecoveryPointer(pointer: ContextRecoveryPointer): string { + const windows = pointer.windows; + const summarized = windows.length - 1; + const lines = windows.map((range, index) => { + const label = `window ${String(index + 1)}: lines ${String(range.start)}–${String(range.end)}`; + return index === summarized ? `${label} ← the conversation this note summarizes` : label; + }); + const nextStart = windows[summarized]!.end + 1; + lines.push( + `window ${String(windows.length + 1)} (the one you are in now) starts at line ${String(nextStart)} with the \`context.apply_compaction\` record that carries this note — it is already in your context; no need to read it.`, + ); + return renderPrompt(contextRecoveryTemplate, { + wire_path: pointer.journalPath, + window_lines: lines.map((line) => ` ${line}`).join('\n'), + }).trimEnd(); +} diff --git a/packages/agent-core-v2/src/agent/fullCompaction/fullCompaction.ts b/packages/agent-core-v2/src/agent/fullCompaction/fullCompaction.ts index 88c70d19440..758f98e4539 100644 --- a/packages/agent-core-v2/src/agent/fullCompaction/fullCompaction.ts +++ b/packages/agent-core-v2/src/agent/fullCompaction/fullCompaction.ts @@ -2,6 +2,7 @@ import type { CompactionResult, CompactionSource, } from './types'; +import type { CompactionTriggerBudget } from './strategy'; import { createDecorator } from "#/_base/di/instantiation"; import type { Event } from '#/_base/event'; import type { Hooks } from '#/hooks'; @@ -11,6 +12,10 @@ export interface FullCompactionInput { readonly instruction?: string; } +export interface CompactionBudget extends CompactionTriggerBudget { + readonly used: number; +} + export interface FullCompactionTask { readonly abortController: AbortController; readonly promise: Promise; @@ -25,6 +30,7 @@ export interface IAgentFullCompactionService { readonly compacting: FullCompactionTask | null; begin(input: FullCompactionInput): boolean; cancel(): void; + budget(): CompactionBudget; readonly hooks: Hooks<{ onWillCompact: FullCompactionTask; diff --git a/packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts b/packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts index a453fea3b2a..b858f7dad30 100644 --- a/packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts +++ b/packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts @@ -3,7 +3,6 @@ import { Service } from "#/_base/di/service"; import { LifecycleScope } from '#/app/scopes'; import { ScopeActivation, registerScopedService } from '#/_base/di/scope'; import { defineState } from '#/state/state'; -import { renderPrompt } from "#/_base/utils/render-prompt"; import { estimateTokensForMessage } from "#/kosong/contract/tokens"; import { buildCompactionSummaryText, isRealUserInput } from '#/agent/contextMemory/compactionHandoff'; import { IAgentContextMemoryService } from '#/agent/contextMemory/contextMemory'; @@ -27,6 +26,13 @@ import { stripDynamicToolContext } from '#/agent/toolSelect/dynamicTools'; import { IAgentToolSelectService } from '#/agent/toolSelect/toolSelect'; import { IAgentTodoService } from '#/features/todo/todoService'; import { renderTodoList } from '#/features/todo/todoItem'; +import { + isContextBudgetReminder, + summarizeCompactionAheadFollowUp, +} from '#/features/contextBudget/contextBudgetReminder'; +import { onUnexpectedError } from '#/_base/errors/unexpectedError'; +import type { WireLineRange } from '#/wire/record'; +import { IWireService } from '#/wire/wire'; import { APIContextOverflowError, APIEmptyResponseError, @@ -42,9 +48,11 @@ import { ITelemetryService } from '#/app/telemetry/telemetry'; import { ErrorCodes, Error2, isCodedError, isError2, toKimiErrorPayload, unwrapErrorCause } from "#/errors"; import { AgentErrorEvent } from '#/agent/mcp/mcpEvents'; import { IEventDispatcher } from '#/state/eventDispatcher'; -import compactionInstructionTemplate from './compaction-instruction.md?raw'; +import { renderCompactionInstruction } from './compactionInstruction'; +import { renderContextRecoveryPointer } from './contextRecovery'; import { IAgentFullCompactionService, + type CompactionBudget, type FullCompactionInput, type FullCompactionTask, } from './fullCompaction'; @@ -57,6 +65,7 @@ import { CompactionCancelled, CompactionCompleted, fullCompactionKey, + fullCompactionWireRangesKey, FullCompactionBegin, FullCompactionCancel, FullCompactionComplete, @@ -150,9 +159,11 @@ export class AgentFullCompactionService extends Service implements IAgentFullCom @IEventBus private readonly eventBus: IEventBus, @IAgentLoopService private readonly loopService: IAgentLoopService, @IAgentStateService private readonly states: IAgentStateService, + @IWireService private readonly wire: IWireService, ) { super(); this.states.contributeState(fullCompactionKey); + this.states.contributeState(fullCompactionWireRangesKey); this.states.contributeState(fullCompactionCompactionCountInTurnKey); this.states.contributeState(fullCompactionObservedMaxContextTokensByModelKey); this.states.contributeState(fullCompactionLastCompactedTokenCountKey); @@ -237,6 +248,10 @@ export class AgentFullCompactionService extends Service implements IAgentFullCom return this._compacting; } + budget(): CompactionBudget { + return { used: this.tokenCountWithPending(), ...this.strategy.budget() }; + } + cancel(): void { const active = this._compacting; if (active !== null) { @@ -633,15 +648,13 @@ export class AgentFullCompactionService extends Service implements IAgentFullCom : undefined; const compactionMaxOutputSize = resolvedModel.maxOutputSize ?? defaultCompactionCap; - const customInstruction = data.instruction?.trim() ?? ''; - const instruction = renderPrompt(compactionInstructionTemplate, { - custom_instruction_block: - customInstruction.length > 0 ? `\nOptional user instruction:\n${customInstruction}\n` : '', - }).trimEnd(); + const instruction = renderCompactionInstruction({ customInstruction: data.instruction }); const delays = retryBackoffDelays(MAX_COMPACTION_RETRY_ATTEMPTS); let attempt: CompactionAttemptResult | undefined; - let historyForModel: readonly ContextMessage[] = stripDynamicToolContext(originalHistory); + let historyForModel: readonly ContextMessage[] = stripDynamicToolContext(originalHistory).filter( + (message) => !isContextBudgetReminder(message), + ); let droppedCount = 0; let overflowShrinkCount = 0; let emptyOrTruncatedShrinkCount = 0; @@ -688,6 +701,7 @@ export class AgentFullCompactionService extends Service implements IAgentFullCom overflowShrinkCount, (message) => this.tokenCounting.estimateMessage(message), ); + if (historyForModel.length === 0) throw error; droppedCount += before - historyForModel.length; retryCount = 0; continue; @@ -735,14 +749,23 @@ export class AgentFullCompactionService extends Service implements IAgentFullCom } const summary = await this.postProcessSummary(attempt.summary); + const wireLines = await this.captureWireLines(); + const recoveryFooter = this.renderRecoveryFooter(wireLines); + const summaryText = buildCompactionSummaryText(summary); const result = this.context.applyCompaction({ summary, - contextSummary: buildCompactionSummaryText(summary), + contextSummary: + recoveryFooter === undefined ? summaryText : `${summaryText}\n\n${recoveryFooter}`, compactedCount: originalHistory.length, tokensBefore, - summaryOutputTokens: attempt.usage?.output, + summaryOutputTokens: + attempt.usage === null + ? undefined + : attempt.usage.output + + (recoveryFooter === undefined ? 0 : this.tokenCounting.estimateText(recoveryFooter)), requestOverheadTokens: this.requestTokens([]), droppedCount: droppedCount === 0 ? undefined : droppedCount, + wireLines, }); const properties: CompactionFinishedEvent = { @@ -758,6 +781,7 @@ export class AgentFullCompactionService extends Service implements IAgentFullCom thinking_effort: thinkingEffort, trace_id: attempt.traceId, ...usageTelemetry(attempt.usage), + ...aheadReminderTelemetry(originalHistory), }; this.telemetry.track2('compaction_finished', properties); return result; @@ -794,11 +818,56 @@ export class AgentFullCompactionService extends Service implements IAgentFullCom return `${summary.trim()}\n\n${renderTodoList(todos, '## TODO List')}`; } + private async captureWireLines(): Promise { + try { + await this.wire.flush(); + } catch (error) { + onUnexpectedError(error); + return undefined; + } + const end = this.wire.lineCount(); + const previous = this.states.get(fullCompactionWireRangesKey).at(-1); + const start = Math.max(previous?.end ?? 0, this.wire.lastContextClearLine() ?? 0) + 1; + if (end < start) return undefined; + return { start, end }; + } + + private renderRecoveryFooter(wireLines: WireLineRange | undefined): string | undefined { + if (wireLines === undefined) return undefined; + const journalPath = this.wire.journalPath(); + if (journalPath === undefined) return undefined; + const windows = [...this.states.get(fullCompactionWireRangesKey), wireLines]; + return renderContextRecoveryPointer({ journalPath, windows }); + } + private tokenCountWithPending(): number { return this.tokenCounting.get(agentContextOfScope(this.agent)).size; } } +type CompactionAheadTelemetryProperties = Pick< + CompactionFinishedEvent, + | 'ahead_reminder_delivered' + | 'ahead_steps_count' + | 'ahead_write_calls_count' + | 'ahead_bash_calls_count' + | 'ahead_todo_calls_count' +>; + +function aheadReminderTelemetry( + history: readonly ContextMessage[], +): CompactionAheadTelemetryProperties { + const followUp = summarizeCompactionAheadFollowUp(history); + if (followUp === undefined) return { ahead_reminder_delivered: false }; + return { + ahead_reminder_delivered: true, + ahead_steps_count: followUp.stepCount, + ahead_write_calls_count: followUp.writeCallCount, + ahead_bash_calls_count: followUp.bashCallCount, + ahead_todo_calls_count: followUp.todoCallCount, + }; +} + function findAPIStatusError(error: unknown): APIStatusError | undefined { let current: unknown = error; const seen = new Set(); diff --git a/packages/agent-core-v2/src/agent/fullCompaction/strategy.ts b/packages/agent-core-v2/src/agent/fullCompaction/strategy.ts index 2ca7120ed05..fd0ccdfbef1 100644 --- a/packages/agent-core-v2/src/agent/fullCompaction/strategy.ts +++ b/packages/agent-core-v2/src/agent/fullCompaction/strategy.ts @@ -27,9 +27,17 @@ export const DEFAULT_COMPACTION_CONFIG: CompactionConfig = { minOverflowReductionRatio: 0.05, }; +export interface CompactionTriggerBudget { + readonly maxSize: number; + readonly triggerRatio: number; + readonly reservedContextSize: number; + readonly triggerTokens: number; +} + export interface CompactionStrategy { shouldCompact(usedSize: number): boolean; shouldBlock(usedSize: number): boolean; + budget(): CompactionTriggerBudget; computeCompactCount(messages: readonly Message[], source: CompactionSource): number; reduceCompactOnOverflow(messages: readonly Message[]): number; readonly checkAfterStep: boolean; @@ -51,6 +59,10 @@ export class RuntimeCompactionStrategy implements CompactionStrategy { return this.delegate().shouldBlock(usedSize); } + budget(): CompactionTriggerBudget { + return this.delegate().budget(); + } + computeCompactCount(messages: readonly Message[], source: CompactionSource): number { return this.windowDelegate().computeCompactCount(messages, source); } @@ -129,6 +141,24 @@ export class DefaultCompactionStrategy implements CompactionStrategy { ); } + budget(): CompactionTriggerBudget { + const maxSize = this.maxSize; + const reservedContextSize = this.config.reservedContextSize; + const reservedTrigger = + reservedContextSize > 0 && reservedContextSize < maxSize + ? maxSize - reservedContextSize + : Number.POSITIVE_INFINITY; + return { + maxSize, + triggerRatio: this.config.triggerRatio, + reservedContextSize, + triggerTokens: + maxSize <= 0 + ? Number.POSITIVE_INFINITY + : Math.min(Math.ceil(maxSize * this.config.triggerRatio), reservedTrigger), + }; + } + private shouldUseReservedContext(usedSize: number): boolean { const reservedSize = this.config.reservedContextSize; return reservedSize > 0 && reservedSize < this.maxSize && usedSize + reservedSize >= this.maxSize; diff --git a/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncation.ts b/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncation.ts index 2bf2743a01f..6aa87c15543 100644 --- a/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncation.ts +++ b/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncation.ts @@ -17,6 +17,8 @@ export interface IAgentToolResultTruncationService { ): Promise; isSpillFilePath(path: string): boolean; + + isWireJournalPath(path: string): boolean; } export const IAgentToolResultTruncationService: ServiceIdentifier< diff --git a/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncationService.ts b/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncationService.ts index a9b666a664e..fec11d1fd30 100644 --- a/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncationService.ts +++ b/packages/agent-core-v2/src/agent/toolResultTruncation/toolResultTruncationService.ts @@ -8,9 +8,10 @@ import { type ExecutableToolResult, } from '#/tool/toolContract'; import { IBootstrapService } from '#/app/bootstrap/bootstrap'; +import { AGENT_WIRE_RECORD_KEY } from '#/wire/record'; import type { ContentPart } from '#/kosong/contract/message'; import { IFileSystemStorageService } from '#/persistence/interface/storage'; -import { join, normalize } from 'pathe'; +import { basename, join, normalize } from 'pathe'; import { IAgentToolResultTruncationService, type ToolResultTruncationInput, @@ -117,6 +118,12 @@ export class ToolResultTruncationService implements IAgentToolResultTruncationSe return normalized === dir || normalized.startsWith(`${dir}/`); } + isWireJournalPath(path: string): boolean { + const sessionsDir = normalize(join(this.bootstrap.homeDir, this.bootstrap.scope('sessions'))); + const normalized = normalize(path); + return normalized.startsWith(`${sessionsDir}/`) && basename(normalized) === AGENT_WIRE_RECORD_KEY; + } + private async saveToolResult( toolName: string, toolCallId: string, diff --git a/packages/agent-core-v2/src/agent/tools/os/read/read.md b/packages/agent-core-v2/src/agent/tools/os/read/read.md index 504bec75762..6a81d8cec09 100644 --- a/packages/agent-core-v2/src/agent/tools/os/read/read.md +++ b/packages/agent-core-v2/src/agent/tools/os/read/read.md @@ -7,6 +7,7 @@ When you need several files, prefer to read them in parallel: emit multiple `Rea - Relative paths resolve against the working directory; a path outside the working directory must be absolute. - Returns up to ${MAX_LINES} lines or ${MAX_BYTES_KB} KB per call, whichever comes first; lines longer than ${MAX_LINE_LENGTH} chars are truncated mid-line (recover the elided content with Bash, e.g. `cut` or `sed`). - Page larger files with `line_offset` (1-based start line) and `n_lines`. Omit `n_lines` to read up to the ${MAX_LINES}-line cap. +- Kimi Code agent event logs (`wire.jsonl` under the sessions directory) are returned with whole lines (up to ~150k chars per record); read them one record at a time with `n_lines=1` after locating the line with Grep. - Sensitive files (`.env` files, credential stores, SSH private keys, and similar secrets) are refused to protect secrets; do not attempt to read them. Templates and public keys are exempt: `.env.example` / `.env.sample` / `.env.template` and public SSH keys such as `id_rsa.pub` read normally. - UTF-8 text files are read directly. UTF-16 LE/BE text files (with or without a BOM) are detected automatically and transcoded to UTF-8 for display; the status block notes the detected encoding, and Edit/Write on such a file still expect UTF-8 — convert its encoding first (e.g. with `iconv`). Other encodings (e.g. GBK), binary files, and files containing NUL bytes are refused. - Negative line_offset reads from the end of the file (for example, -100 reads the last 100 lines); the absolute value cannot exceed ${MAX_LINES}. diff --git a/packages/agent-core-v2/src/agent/tools/os/read/read.ts b/packages/agent-core-v2/src/agent/tools/os/read/read.ts index 881b2018285..66411c96da2 100644 --- a/packages/agent-core-v2/src/agent/tools/os/read/read.ts +++ b/packages/agent-core-v2/src/agent/tools/os/read/read.ts @@ -6,6 +6,7 @@ import { type AgentTool } from '#/tool/toolContract'; export const MAX_LINES: number = 1000; export const MAX_LINE_LENGTH: number = 2000; export const MAX_BYTES: number = 100 * 1024; +export const EVENT_LOG_MAX_LINE_LENGTH: number = 150_000; export const TRANSCODE_MAX_BYTES: number = 10 * 1024 * 1024; diff --git a/packages/agent-core-v2/src/agent/tools/os/read/readTool.ts b/packages/agent-core-v2/src/agent/tools/os/read/readTool.ts index 85fb3f32a4f..684b4e3d511 100644 --- a/packages/agent-core-v2/src/agent/tools/os/read/readTool.ts +++ b/packages/agent-core-v2/src/agent/tools/os/read/readTool.ts @@ -21,6 +21,7 @@ import { makeCarriageReturnsVisible, splitLinesKeepingTerminator, type LineEndin import { decodeUtfText, detectTextEncoding, type UtfTextEncoding } from '#/_base/text/encoding'; import { renderPrompt } from '#/_base/utils/render-prompt'; import { + EVENT_LOG_MAX_LINE_LENGTH, IReadTool, MAX_BYTES, MAX_LINE_LENGTH, @@ -58,6 +59,11 @@ interface FinishReadResultInput { readonly totalLines: number; readonly requestedLines: number; readonly detectedEncoding?: UtfTextEncoding; + readonly eventLog: boolean; +} + +function lineLengthLimit(eventLog: boolean): number { + return eventLog ? EVENT_LOG_MAX_LINE_LENGTH : MAX_LINE_LENGTH; } function truncateLine(line: string, maxLength: number): string { @@ -93,12 +99,16 @@ function lineEndingStyleFromFlags(flags: LineEndingFlags): LineEndingStyle { return 'lf'; } -function renderLine(entry: ReadLineEntry, lineEndingStyle: LineEndingStyle): RenderedLine { +function renderLine( + entry: ReadLineEntry, + lineEndingStyle: LineEndingStyle, + maxLineLength: number, +): RenderedLine { const modelContent = lineEndingStyle === 'crlf' && entry.rawContent.endsWith('\r') ? entry.rawContent.slice(0, -1) : entry.rawContent; - const truncated = truncateLine(modelContent, MAX_LINE_LENGTH); + const truncated = truncateLine(modelContent, maxLineLength); const renderedContent = lineEndingStyle === 'mixed' ? makeCarriageReturnsVisible(truncated) : truncated; return { @@ -114,6 +124,7 @@ function renderedLineBytes(renderedLine: string, isFirst: boolean): number { function renderEntries( entries: readonly ReadLineEntry[], lineEndingStyle: LineEndingStyle, + maxLineLength: number, ): { renderedLines: string[]; truncatedLineNumbers: number[]; @@ -125,7 +136,7 @@ function renderEntries( let maxBytesReached = false; for (const entry of entries) { - const rendered = renderLine(entry, lineEndingStyle); + const rendered = renderLine(entry, lineEndingStyle, maxLineLength); const lineBytes = renderedLineBytes(rendered.line, renderedLines.length === 0); if (renderedLines.length > 0 && bytes + lineBytes > MAX_BYTES) { maxBytesReached = true; @@ -245,8 +256,9 @@ export class ReadTool implements IReadTool { if (lease.runtime.identity.generation !== inspected.identity.generation) { return { isError: true, output: 'Runtime changed before execution. Retry the tool call.' }; } - const result = await this.execution(lease.runtime.fs!, args, path); - return this.resultTruncation.isSpillFilePath(path) + const eventLog = this.resultTruncation.isWireJournalPath(path); + const result = await this.execution(lease.runtime.fs!, args, path, eventLog); + return eventLog || this.resultTruncation.isSpillFilePath(path) ? { ...result, spillExempt: true as const } : result; } finally { @@ -256,7 +268,12 @@ export class ReadTool implements IReadTool { }; } - private async execution(fs: IHostFileSystem, args: ReadInput, safePath: string): Promise { + private async execution( + fs: IHostFileSystem, + args: ReadInput, + safePath: string, + eventLog: boolean, + ): Promise { try { let stat: Awaited>; try { @@ -316,6 +333,7 @@ export class ReadTool implements IReadTool { lineOffset, effectiveLimit, requestedLines, + eventLog, detectedEncoding, ); } @@ -325,6 +343,7 @@ export class ReadTool implements IReadTool { lineOffset, effectiveLimit, requestedLines, + eventLog, detectedEncoding, ); } catch (error) { @@ -344,6 +363,7 @@ export class ReadTool implements IReadTool { lineOffset: number, effectiveLimit: number, requestedLines: number, + eventLog: boolean, detectedEncoding?: UtfTextEncoding, ): Promise { const selectedEntries: ReadLineEntry[] = []; @@ -382,7 +402,7 @@ export class ReadTool implements IReadTool { } const lineEndingStyle = lineEndingStyleFromFlags(flags); - const rendered = renderEntries(selectedEntries, lineEndingStyle); + const rendered = renderEntries(selectedEntries, lineEndingStyle, lineLengthLimit(eventLog)); return this.finishReadResult({ renderedLines: rendered.renderedLines, @@ -394,6 +414,7 @@ export class ReadTool implements IReadTool { totalLines: currentLineNo, requestedLines, detectedEncoding, + eventLog, }); } @@ -403,6 +424,7 @@ export class ReadTool implements IReadTool { lineOffset: number, effectiveLimit: number, requestedLines: number, + eventLog: boolean, detectedEncoding?: UtfTextEncoding, ): Promise { const tailCount = Math.abs(lineOffset); @@ -431,6 +453,7 @@ export class ReadTool implements IReadTool { effectiveLimit, totalLines: currentLineNo, requestedLines, + eventLog, detectedEncoding, }); } @@ -441,11 +464,13 @@ export class ReadTool implements IReadTool { effectiveLimit: number; totalLines: number; requestedLines: number; + eventLog: boolean; detectedEncoding?: UtfTextEncoding; }): ExecutableToolResult { const lineEndingStyle = lineEndingStyleFromFlags(input.lineEndingFlags); + const maxLineLength = lineLengthLimit(input.eventLog); let renderedCandidates = input.entries.slice(0, input.effectiveLimit).map((entry) => { - return { entry, rendered: renderLine(entry, lineEndingStyle) }; + return { entry, rendered: renderLine(entry, lineEndingStyle, maxLineLength) }; }); let totalBytes = 0; @@ -462,7 +487,7 @@ export class ReadTool implements IReadTool { const candidate = renderedCandidates[i]; if (candidate === undefined) continue; const lineBytes = renderedLineBytes(candidate.rendered.line, kept.length === 0); - if (bytes + lineBytes > MAX_BYTES) break; + if (kept.length > 0 && bytes + lineBytes > MAX_BYTES) break; kept.unshift(candidate); bytes += lineBytes; } @@ -488,6 +513,7 @@ export class ReadTool implements IReadTool { totalLines: input.totalLines, requestedLines: input.requestedLines, detectedEncoding: input.detectedEncoding, + eventLog: input.eventLog, }); } @@ -518,7 +544,12 @@ export class ReadTool implements IReadTool { } if (input.truncatedLineNumbers.length > 0) { parts.push( - `Lines [${input.truncatedLineNumbers.join(', ')}] were truncated to ${String(MAX_LINE_LENGTH)} characters; use Bash (e.g. cut or sed) to read the elided content of those lines.`, + `Lines [${input.truncatedLineNumbers.join(', ')}] were truncated to ${String(lineLengthLimit(input.eventLog))} characters; use Bash (e.g. cut or sed) to read the elided content of those lines.`, + ); + } + if (input.eventLog) { + parts.push( + `Kimi Code agent event log: records are returned whole up to ${String(EVENT_LOG_MAX_LINE_LENGTH)} characters per line; read one record at a time (n_lines=1). For a longer record, extract fields with Bash: sed -n 'Np' | jq. A primer on this format appears in your compaction note once a compaction has run.`, ); } if (input.lineEndingStyle === 'mixed') { diff --git a/packages/agent-core-v2/src/app/telemetry/events.ts b/packages/agent-core-v2/src/app/telemetry/events.ts index 465cce28e37..c0262faf233 100644 --- a/packages/agent-core-v2/src/app/telemetry/events.ts +++ b/packages/agent-core-v2/src/app/telemetry/events.ts @@ -215,6 +215,24 @@ export interface CompactionFinishedEvent { input_cache_read?: number; input_cache_creation?: number; trace_id?: string; + ahead_reminder_delivered: boolean; + ahead_steps_count?: number; + ahead_write_calls_count?: number; + ahead_bash_calls_count?: number; + ahead_todo_calls_count?: number; +} + +export interface ContextBudgetReminderEvent { + bucket: 'half' | 'three_quarters'; + used_tokens: number; + trigger_tokens: number; + max_tokens: number; +} + +export interface CompactionAheadReminderEvent { + used_tokens: number; + trigger_tokens: number; + lead_tokens: number; } export interface CompactionFailedEvent { @@ -784,6 +802,31 @@ export const telemetryEventDefinitions = { input_cache_creation: 'Cache-creation input tokens', trace_id: 'Trace id of the final compaction request round; absent for non-Kimi protocols', + ahead_reminder_delivered: + 'Whether the compaction-ahead reminder had been delivered in the compacted window', + ahead_steps_count: 'Assistant steps taken between the compaction-ahead reminder and compaction', + ahead_write_calls_count: 'Write/Edit tool calls made after the compaction-ahead reminder', + ahead_bash_calls_count: 'Bash tool calls made after the compaction-ahead reminder', + ahead_todo_calls_count: 'Todo tool calls made after the compaction-ahead reminder', + }, + }), + context_budget_reminder: defineAgentTelemetryEvent({ + owner: 'kimi-code', + comment: 'The model is told how much of its context budget is used, once per bucket.', + properties: { + bucket: 'Share of the compaction trigger reached: half or three_quarters', + used_tokens: 'Context tokens in use when the reminder was injected', + trigger_tokens: 'Token count at which automatic compaction triggers', + max_tokens: 'Effective context window size in tokens', + }, + }), + compaction_ahead_reminder: defineAgentTelemetryEvent({ + owner: 'kimi-code', + comment: 'The model is warned once per window that automatic compaction is imminent.', + properties: { + used_tokens: 'Context tokens in use when the reminder was injected', + trigger_tokens: 'Token count at which automatic compaction triggers', + lead_tokens: 'Tokens between the reminder threshold and the compaction trigger', }, }), compaction_failed: defineAgentTelemetryEvent({ diff --git a/packages/agent-core-v2/src/features/contextBudget/compaction-ahead.md b/packages/agent-core-v2/src/features/contextBudget/compaction-ahead.md new file mode 100644 index 00000000000..709aa6c6af8 --- /dev/null +++ b/packages/agent-core-v2/src/features/contextBudget/compaction-ahead.md @@ -0,0 +1,8 @@ + +Context is at ~${used_pct}%; automatic compaction runs at ${trigger_pct}% (about ${remaining_k}k tokens from now). When it runs you will write a handoff note with text only — no tool calls. This is your last chance to act: +- persist unfinished intermediate results to files or the todo list — these survive verbatim and can be read back; +- verify with tools any claim you intend to carry forward (run the test; don't assume) — the note will be written with the result in view; +- bring the current sub-task to a hand-off-able boundary; don't start large new work now; +- if a long user input or constraint may be truncated (kept user messages are capped at ~${kept_k}k tokens), restate its essentials. +Then continue the task; do not stop. + diff --git a/packages/agent-core-v2/src/features/contextBudget/context-budget.md b/packages/agent-core-v2/src/features/contextBudget/context-budget.md new file mode 100644 index 00000000000..897043ad4d1 --- /dev/null +++ b/packages/agent-core-v2/src/features/contextBudget/context-budget.md @@ -0,0 +1,5 @@ + +Context: ~${used_pct}% of the ${max_k}k-token window is used; automatic compaction runs at ${trigger_k}k (${trigger_pct}%). Figures are as of the last check. +At compaction this window is replaced by a handoff note you write yourself (text only, no tools). Kept verbatim: your recent user messages (capped at ~${kept_k}k tokens; a long one keeps only its head) and the todo list. Cleared: assistant messages, tool calls and tool results — but the full record stays on disk and a recovery pointer will follow the note. +Do not wrap up or stop early because of budget. Prefer Grep or paged Read over whole-file reads when the payoff is small. + diff --git a/packages/agent-core-v2/src/features/contextBudget/contextBudgetFeature.ts b/packages/agent-core-v2/src/features/contextBudget/contextBudgetFeature.ts new file mode 100644 index 00000000000..715ec1112ff --- /dev/null +++ b/packages/agent-core-v2/src/features/contextBudget/contextBudgetFeature.ts @@ -0,0 +1,15 @@ +import { Feature } from '#/features/feature'; +import { registerFeature } from '#/features/featureRegistry'; + +import { AgentContextBudgetService, IAgentContextBudgetService } from './contextBudgetService'; + +export class ContextBudgetFeature extends Feature { + static override readonly name = 'contextBudget'; + + constructor() { + super(); + this.contributeAgentService(IAgentContextBudgetService, AgentContextBudgetService); + } +} + +registerFeature(ContextBudgetFeature); diff --git a/packages/agent-core-v2/src/features/contextBudget/contextBudgetReminder.ts b/packages/agent-core-v2/src/features/contextBudget/contextBudgetReminder.ts new file mode 100644 index 00000000000..1a2d5ad368f --- /dev/null +++ b/packages/agent-core-v2/src/features/contextBudget/contextBudgetReminder.ts @@ -0,0 +1,124 @@ +import { renderPrompt } from '#/_base/utils/render-prompt'; +import { COMPACT_USER_MESSAGE_MAX_TOKENS } from '#/agent/contextMemory/compactionHandoff'; +import type { ContextMessage } from '#/agent/contextMemory/types'; +import type { CompactionBudget } from '#/agent/fullCompaction/fullCompaction'; + +import compactionAheadTemplate from './compaction-ahead.md?raw'; +import contextBudgetTemplate from './context-budget.md?raw'; + +export const CONTEXT_BUDGET_REMINDER_VARIANT = 'context_budget'; +export const COMPACTION_AHEAD_REMINDER_VARIANT = 'compaction_ahead'; + +export const COMPACTION_AHEAD_LEAD_RATIO = 0.1; + +export type ContextBudgetBucket = 'half' | 'three_quarters'; + +export interface ContextBudgetDisclosure { + readonly bucket: ContextBudgetBucket; +} + +const BUCKET_THRESHOLDS: readonly (readonly [ContextBudgetBucket, number])[] = [ + ['three_quarters', 0.75], + ['half', 0.5], +]; + +const WRITE_TOOL_NAMES = new Set(['Write', 'Edit']); +const BASH_TOOL_NAMES = new Set(['Bash']); +const TODO_TOOL_NAMES = new Set(['TodoList', 'SetTodoList']); + +export interface CompactionAheadFollowUp { + readonly stepCount: number; + readonly writeCallCount: number; + readonly bashCallCount: number; + readonly todoCallCount: number; +} + +export function contextBudgetBucket(budget: CompactionBudget): ContextBudgetBucket | undefined { + if (!Number.isFinite(budget.triggerTokens) || budget.triggerTokens <= 0) return undefined; + const share = budget.used / budget.triggerTokens; + for (const [bucket, threshold] of BUCKET_THRESHOLDS) { + if (share >= threshold) return bucket; + } + return undefined; +} + +export function compactionAheadLeadTokens(budget: CompactionBudget): number { + return Math.ceil(budget.maxSize * COMPACTION_AHEAD_LEAD_RATIO); +} + +export function shouldRemindCompactionAhead(budget: CompactionBudget): boolean { + if (!Number.isFinite(budget.triggerTokens) || budget.maxSize <= 0) return false; + if (budget.used >= budget.triggerTokens) return false; + return budget.triggerTokens - budget.used <= compactionAheadLeadTokens(budget); +} + +export function renderContextBudgetReminder(budget: CompactionBudget): string { + return renderPrompt(contextBudgetTemplate, { + used_pct: percent(budget.used, budget.maxSize), + max_k: thousands(budget.maxSize), + trigger_k: thousands(budget.triggerTokens), + trigger_pct: percent(budget.triggerTokens, budget.maxSize), + kept_k: thousands(COMPACT_USER_MESSAGE_MAX_TOKENS), + }).trimEnd(); +} + +export function renderCompactionAheadReminder(budget: CompactionBudget): string { + return renderPrompt(compactionAheadTemplate, { + used_pct: percent(budget.used, budget.maxSize), + trigger_pct: percent(budget.triggerTokens, budget.maxSize), + remaining_k: thousands(Math.max(0, budget.triggerTokens - budget.used)), + kept_k: thousands(COMPACT_USER_MESSAGE_MAX_TOKENS), + }).trimEnd(); +} + +export function isContextBudgetReminder(message: ContextMessage): boolean { + return ( + message.origin?.kind === 'injection' && + (message.origin.variant === CONTEXT_BUDGET_REMINDER_VARIANT || + message.origin.variant === COMPACTION_AHEAD_REMINDER_VARIANT) + ); +} + +export function isCompactionAheadReminder(message: ContextMessage): boolean { + return ( + message.origin?.kind === 'injection' && + message.origin.variant === COMPACTION_AHEAD_REMINDER_VARIANT + ); +} + +export function summarizeCompactionAheadFollowUp( + history: readonly ContextMessage[], +): CompactionAheadFollowUp | undefined { + let reminderIndex = -1; + for (let index = history.length - 1; index >= 0; index -= 1) { + if (isCompactionAheadReminder(history[index]!)) { + reminderIndex = index; + break; + } + } + if (reminderIndex < 0) return undefined; + + let stepCount = 0; + let writeCallCount = 0; + let bashCallCount = 0; + let todoCallCount = 0; + for (const message of history.slice(reminderIndex + 1)) { + if (message.role !== 'assistant') continue; + stepCount += 1; + for (const toolCall of message.toolCalls) { + if (WRITE_TOOL_NAMES.has(toolCall.name)) writeCallCount += 1; + else if (BASH_TOOL_NAMES.has(toolCall.name)) bashCallCount += 1; + else if (TODO_TOOL_NAMES.has(toolCall.name)) todoCallCount += 1; + } + } + return { stepCount, writeCallCount, bashCallCount, todoCallCount }; +} + +function percent(part: number, whole: number): number { + if (whole <= 0) return 0; + return Math.round((part / whole) * 100); +} + +function thousands(tokens: number): number { + return Math.round(tokens / 1000); +} diff --git a/packages/agent-core-v2/src/features/contextBudget/contextBudgetService.ts b/packages/agent-core-v2/src/features/contextBudget/contextBudgetService.ts new file mode 100644 index 00000000000..cdaef5d0d0b --- /dev/null +++ b/packages/agent-core-v2/src/features/contextBudget/contextBudgetService.ts @@ -0,0 +1,125 @@ +import { fromCallback, setup } from 'xstate'; + +import { createDecorator, IInstantiationService } from '#/_base/di/instantiation'; +import { + AgentActorService, + type AgentActorContext, + type AgentActorRestoreEvent, +} from '#/agent/actorService/agentActorService'; +import { IAgentFullCompactionService } from '#/agent/fullCompaction/fullCompaction'; +import { IAgentScopeContext } from '#/agent/scopeContext/scopeContext'; +import { ITelemetryService } from '#/app/telemetry/telemetry'; +import { IAgentReminderService } from '#/features/reminder/reminderService'; +import type { ContextInjectionResult } from '#/features/reminder/types'; +import { IEventDispatcher } from '#/state/eventDispatcher'; + +import { + COMPACTION_AHEAD_REMINDER_VARIANT, + CONTEXT_BUDGET_REMINDER_VARIANT, + compactionAheadLeadTokens, + contextBudgetBucket, + renderCompactionAheadReminder, + renderContextBudgetReminder, + shouldRemindCompactionAhead, + type ContextBudgetDisclosure, +} from './contextBudgetReminder'; + +interface ContextBudgetActorContext { + readonly runtime: AgentActorContext; +} + +const contextBudgetReminders = fromCallback(({ + input, +}: { + input: { + readonly runtime: AgentActorContext; + }; +}) => { + const runtime = input.runtime; + const reminder = runtime.get(IAgentReminderService); + const compaction = runtime.get(IAgentFullCompactionService); + const telemetry = runtime.get(ITelemetryService); + + const budgetRegistration = reminder.register( + CONTEXT_BUDGET_REMINDER_VARIANT, + ({ lastDisclosure }): ContextInjectionResult | undefined => { + const budget = compaction.budget(); + const bucket = contextBudgetBucket(budget); + if (bucket === undefined || lastDisclosure?.bucket === bucket) return undefined; + telemetry.track2('context_budget_reminder', { + bucket, + used_tokens: budget.used, + trigger_tokens: budget.triggerTokens, + max_tokens: budget.maxSize, + }); + return { content: renderContextBudgetReminder(budget), disclosure: { bucket } }; + }, + ); + + const aheadRegistration = reminder.register( + COMPACTION_AHEAD_REMINDER_VARIANT, + ({ lastInjection }): string | undefined => { + if (lastInjection !== undefined) return undefined; + const budget = compaction.budget(); + if (!shouldRemindCompactionAhead(budget)) return undefined; + telemetry.track2('compaction_ahead_reminder', { + used_tokens: budget.used, + trigger_tokens: budget.triggerTokens, + lead_tokens: compactionAheadLeadTokens(budget), + }); + return renderCompactionAheadReminder(budget); + }, + ); + + return () => { + budgetRegistration.dispose(); + aheadRegistration.dispose(); + }; +}); + +const contextBudgetActorLogic = setup({ + types: {} as { + context: ContextBudgetActorContext; + input: AgentActorContext; + events: AgentActorRestoreEvent; + }, + actors: { contextBudgetReminders }, +}).createMachine({ + context: ({ input }) => ({ runtime: input }), + initial: 'beforeRestore', + states: { + beforeRestore: { + on: { 'runtime.restore': 'active' }, + }, + active: { + invoke: { + src: 'contextBudgetReminders', + input: ({ context }) => ({ runtime: context.runtime }), + }, + }, + }, +}); + +export interface IAgentContextBudgetService { + readonly _serviceBrand: undefined; +} + +export const IAgentContextBudgetService = createDecorator( + 'agentContextBudgetService', +); + +export class AgentContextBudgetService + extends AgentActorService + implements IAgentContextBudgetService +{ + declare readonly _serviceBrand: undefined; + + constructor( + @IEventDispatcher dispatcher: IEventDispatcher, + @IAgentScopeContext scopeContext: IAgentScopeContext, + @IInstantiationService instantiation: IInstantiationService, + ) { + super(dispatcher, scopeContext, instantiation); + this.attachActor(contextBudgetActorLogic, { id: 'contextBudget' }); + } +} diff --git a/packages/agent-core-v2/src/features/reminder/reminderService.ts b/packages/agent-core-v2/src/features/reminder/reminderService.ts index f19319aeba7..5c3db3390de 100644 --- a/packages/agent-core-v2/src/features/reminder/reminderService.ts +++ b/packages/agent-core-v2/src/features/reminder/reminderService.ts @@ -33,7 +33,11 @@ interface ReminderEntry { readonly variant: string; } -const REMINDER_VARIANT_PRIORITY = new Map([['date_change', -1]]); +const REMINDER_VARIANT_PRIORITY = new Map([ + ['date_change', -1], + ['context_budget', 1], + ['compaction_ahead', 2], +]); interface ReminderActorContext { readonly entries: Set; diff --git a/packages/agent-core-v2/src/index.ts b/packages/agent-core-v2/src/index.ts index 4310c71a8c8..9879bd9103a 100644 --- a/packages/agent-core-v2/src/index.ts +++ b/packages/agent-core-v2/src/index.ts @@ -645,6 +645,11 @@ export * from '#/agent/fullCompaction/fullCompaction'; export * from '#/agent/fullCompaction/fullCompactionService'; export * from '#/agent/fullCompaction/compactionOps'; export * from '#/agent/fullCompaction/types'; +export * from '#/agent/fullCompaction/contextRecovery'; +export * from '#/agent/fullCompaction/compactionInstruction'; +export * from '#/features/contextBudget/contextBudgetReminder'; +export * from '#/features/contextBudget/contextBudgetService'; +import '#/features/contextBudget/contextBudgetFeature'; export * from '#/agent/llmRequester/llmRequester'; export * from '#/agent/llmRequester/llmRequesterService'; export * from '#/agent/llmRequester/llmRequestOps'; diff --git a/packages/agent-core-v2/src/wire/record.ts b/packages/agent-core-v2/src/wire/record.ts index 758f68bb17f..f5fbd16d715 100644 --- a/packages/agent-core-v2/src/wire/record.ts +++ b/packages/agent-core-v2/src/wire/record.ts @@ -9,6 +9,11 @@ export type RecordDehydrator = ( transform: PartsTransformer, ) => WireRecord | Promise; +export interface WireLineRange { + readonly start: number; + readonly end: number; +} + export interface WireRecord { readonly type: string; readonly time?: number; diff --git a/packages/agent-core-v2/src/wire/wire.ts b/packages/agent-core-v2/src/wire/wire.ts index 13d052786a9..215ad8b75d3 100644 --- a/packages/agent-core-v2/src/wire/wire.ts +++ b/packages/agent-core-v2/src/wire/wire.ts @@ -9,6 +9,9 @@ export interface IWireService { appendRecord(record: WireRecord, dehydrate?: RecordDehydrator): void; readJournal(): AsyncIterable; flush(): Promise; + lineCount(): number; + lastContextClearLine(): number | undefined; + journalPath(): string | undefined; } export const IWireService: ServiceIdentifier = diff --git a/packages/agent-core-v2/src/wire/wireService.ts b/packages/agent-core-v2/src/wire/wireService.ts index 063813bcdd3..fc30811360c 100644 --- a/packages/agent-core-v2/src/wire/wireService.ts +++ b/packages/agent-core-v2/src/wire/wireService.ts @@ -38,6 +38,8 @@ export class WireService extends Service implements IWireService { declare readonly _serviceBrand: undefined; private readonly wireScope: string; + private lines = 0; + private lastClearLine: number | undefined; private readonly agentId: string; private persistQueue: Promise | undefined; private pendingRepair: @@ -111,16 +113,20 @@ export class WireService extends Service implements IWireService { let rewrittenRecords: WireRecord[] | undefined; let newerWireVersion = false; let recordIndex = 0; + let lineCount = 0; let hasRecords = false; let legacyPlanRevisionMigrated = false; for await (const candidate of source) { + lineCount++; + this.lines = lineCount; const sourceRecord: unknown = candidate; if (!isWireRecord(sourceRecord)) { this.reportSkippedRecord(undefined, recordIndex, true); recordIndex++; continue; } + if (sourceRecord.type === 'context.clear') this.lastClearLine = lineCount; if (!hasRecords) { hasRecords = true; if (sourceRecord.type !== 'metadata') { @@ -179,9 +185,23 @@ export class WireService extends Service implements IWireService { await this.repairJournal(truncation, rewrittenRecords); } else if (rewrittenRecords !== undefined) { await this.log.rewrite(this.wireScope, AGENT_WIRE_RECORD_KEY, rewrittenRecords); + this.lines = rewrittenRecords.length; + this.lastClearLine = lastContextClearLineOf(rewrittenRecords); } } + lineCount(): number { + return this.lines; + } + + lastContextClearLine(): number | undefined { + return this.lastClearLine; + } + + journalPath(): string | undefined { + return this.storage.pathFor(this.wireScope, AGENT_WIRE_RECORD_KEY); + } + private async repairJournal( truncation: AppendLogTruncation, rewrittenRecords: WireRecord[] | undefined, @@ -210,6 +230,10 @@ export class WireService extends Service implements IWireService { truncation, ); this.pendingRepair = outcome === 'failed' ? { records, truncation } : undefined; + if (outcome !== 'failed') { + this.lines = records.length; + this.lastClearLine = lastContextClearLineOf(records); + } } private async repairPendingJournal(): Promise { @@ -317,7 +341,16 @@ export class WireService extends Service implements IWireService { this.log.append(this.wireScope, AGENT_WIRE_RECORD_KEY, record, { onError: onUnexpectedError, }); + this.lines += 1; + if (record.type === 'context.clear') this.lastClearLine = this.lines; + } +} + +function lastContextClearLineOf(records: readonly WireRecord[]): number | undefined { + for (let index = records.length - 1; index >= 0; index -= 1) { + if (records[index]!.type === 'context.clear') return index + 1; } + return undefined; } function extractLegacyPlanRevisionKey(path: string, agentId: string): string | undefined { diff --git a/packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts b/packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts index 51fd7fc1471..e1587aa304a 100644 --- a/packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts +++ b/packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts @@ -24,7 +24,12 @@ import { MASTER_ENV } from '#/app/flag/flagService'; import { estimateTokensForMessages } from '#/kosong/contract/tokens'; import { recordingTelemetry, type TelemetryRecord } from '../../app/telemetry/stubs'; import type { TestAgentContext, TestAgentOptions, TestAgentServiceOverride } from '../../harness'; -import { agentService, appServices, createCommandRunner, execEnvServices, hostEnvironmentServices, sessionServices, testAgent as createTestAgent } from '../../harness'; +import { agentService, appService, appServices, createCommandRunner, execEnvServices, hostEnvironmentServices, sessionServices, testAgent as createTestAgent } from '../../harness'; +import { IFileSystemStorageService } from '#/persistence/interface/storage'; +import { InMemoryStorageService } from '#/persistence/backends/memory/inMemoryStorageService'; +import { ISessionTokenCountingService } from '#/session/tokenCounting/sessionTokenCounting'; +import { renderCompactionInstruction } from '#/agent/fullCompaction/compactionInstruction'; +import type { ContextMessage } from '#/agent/contextMemory/types'; import { IAgentToolSelectAnnouncementsService } from '#/agent/toolSelect/toolSelectAnnouncements'; import { IAgentFullCompactionService, @@ -39,6 +44,7 @@ import { type ToolExecution, } from '#/index'; import { IAgentLoopService } from '#/agent/loop/loop'; +import { IWireService } from '#/wire/wire'; import { IAgentTodoService } from '#/features/todo/todoService'; import { IAgentGoalService } from '#/features/goal/goalService'; import { HostFileSystem } from '#/os/backends/node-local/hostFsService'; @@ -303,7 +309,7 @@ describe('FullCompaction', () => { compacted_count: 6, retry_count: 0, thinking_effort: 'off', - input_tokens: 1181, + input_tokens: 1247, output_tokens: 8, input_cache_read: 0, input_cache_creation: 0, @@ -657,7 +663,7 @@ describe('FullCompaction', () => { event: 'compaction_finished', properties: expect.objectContaining({ source: 'manual', - tokens_before: 17_895, + tokens_before: 17_950, retry_count: 1, trace_id: 'trace-compact-1', }), @@ -1006,6 +1012,35 @@ describe('FullCompaction', () => { ]); }); + it('fails the compaction instead of compacting an empty history when overflow shrink drops everything', async () => { + let calls = 0; + const generate: GenerateFn = async () => { + calls += 1; + if (calls === 1) { + throw new APIContextOverflowError(400, 'Context length exceeded', 'req-shrink-empty'); + } + return textResult('Groundless summary.'); + }; + const ctx = testAgent({ generate }); + ctx.configure({ + provider: CATALOGUED_PROVIDER, + modelCapabilities: CATALOGUED_MODEL_CAPABILITIES, + }); + ctx.appendExchange(1, 'small user one', 'small assistant one', 20); + ctx.context.append({ + role: 'user', + content: [{ type: 'text', text: 'X'.repeat(400_000) }], + toolCalls: [], + }); + const failed = ctx.once('error'); + + await ctx.rpc.beginCompaction({}); + await failed; + + expect(calls).toBe(1); + expect(ctx.context.get()).toHaveLength(3); + }); + it('waits before retrying compaction generation after a retryable failure', async () => { vi.useFakeTimers(); const firstAttemptFailed = deferred(); @@ -1128,7 +1163,7 @@ describe('FullCompaction', () => { properties: expect.objectContaining({ agent_id: 'main', source: 'manual', - tokens_before: 17_895, + tokens_before: 17_950, duration_ms: expect.any(Number), round: 1, retry_count: 0, @@ -1353,7 +1388,7 @@ describe('FullCompaction', () => { event: 'compaction_failed', properties: expect.objectContaining({ source: 'manual', - tokens_before: 17_895, + tokens_before: 17_950, duration_ms: expect.any(Number), retry_count: 4, error_type: 'APIConnectionError', @@ -3036,6 +3071,269 @@ describe('FullCompaction', () => { }); }); +describe('FullCompaction context recovery pointer', () => { + const JOURNAL_HOME = '/home/user/.kimi-code'; + + interface ApplyCompactionArgs { + readonly summary?: string; + readonly contextSummary?: string; + readonly wireLines?: { readonly start: number; readonly end: number }; + } + + function locatedStorage(base: string): IFileSystemStorageService { + const memory = new InMemoryStorageService(); + return new Proxy(memory, { + get(target, property, receiver) { + if (property === 'pathFor') { + return (scope: string, key: string) => `${base}/${scope}/${key}`; + } + const value = Reflect.get(target, property, receiver) as unknown; + return typeof value === 'function' + ? (value as (...args: unknown[]) => unknown).bind(target) + : value; + }, + }) as unknown as IFileSystemStorageService; + } + + function recoveryAgent( + ...inputs: readonly (TestAgentServiceOverride | TestAgentOptions)[] + ): TestAgentContext { + const ctx = testAgent(...inputs); + ctx.configure({ + provider: CATALOGUED_PROVIDER, + modelCapabilities: CATALOGUED_MODEL_CAPABILITIES, + tools: SNAPSHOT_VISIBLE_TOOLS, + }); + return ctx; + } + + async function compactOnce(ctx: TestAgentContext, summary: string): Promise { + const completed = ctx.once('compaction.completed'); + ctx.mockNextResponse({ type: 'text', text: summary }); + await ctx.rpc.beginCompaction({}); + await completed; + } + + function noteText(ctx: TestAgentContext): string { + const part = ctx.context.get().at(-1)?.content[0]; + return part?.type === 'text' ? part.text : ''; + } + + function applyCompactionRecords(ctx: TestAgentContext): ApplyCompactionArgs[] { + return ctx.newEvents().flatMap((event) => { + if (event === null || typeof event !== 'object') return []; + const candidate = event as { type?: unknown; event?: unknown; args?: unknown }; + if (candidate.type !== '[wire]' || candidate.event !== 'context.apply_compaction') return []; + return [candidate.args as ApplyCompactionArgs]; + }); + } + + function reminderMessage(variant: string, text: string): ContextMessage { + return { + role: 'user', + content: [{ type: 'text', text: `${text}` }], + toolCalls: [], + origin: { kind: 'injection', variant }, + }; + } + + it('appends the journal location and window line ranges to the model-facing note', async () => { + const ctx = recoveryAgent(appService(IFileSystemStorageService, locatedStorage(JOURNAL_HOME))); + ctx.appendExchange(1, 'old user one', 'old assistant one', 20); + ctx.appendExchange(2, 'recent user two', 'recent assistant two', 40); + + await compactOnce(ctx, 'Compacted summary.'); + + const [record] = applyCompactionRecords(ctx); + expect(record?.wireLines).toEqual({ start: 1, end: expect.any(Number) }); + const end = record!.wireLines!.end; + expect(end).toBeGreaterThan(1); + const note = noteText(ctx); + expect(note).toContain('Compacted summary.'); + expect(note).toContain('## Context Recovery'); + expect(note).toContain(`${JOURNAL_HOME}/`); + expect(note).toContain('/wire.jsonl'); + expect(note).toContain(`window 1: lines 1–${String(end)} ← the conversation this note summarizes`); + expect(note).toContain(`window 2 (the one you are in now) starts at line ${String(end + 1)}`); + expect(note).toContain('context.append_loop_event'); + expect(record?.summary).not.toContain('Context Recovery'); + expect(record?.contextSummary).toContain('Context Recovery'); + await ctx.expectResumeMatches(); + }); + + it('lists every earlier window after repeated compactions', async () => { + const ctx = recoveryAgent(appService(IFileSystemStorageService, locatedStorage(JOURNAL_HOME))); + ctx.appendExchange(1, 'old user one', 'old assistant one', 20); + await compactOnce(ctx, 'First summary.'); + ctx.appendExchange(2, 'recent user two', 'recent assistant two', 40); + await compactOnce(ctx, 'Second summary.'); + + const [first, second] = applyCompactionRecords(ctx); + const firstLines = first!.wireLines!; + const secondLines = second!.wireLines!; + expect(secondLines.start).toBe(firstLines.end + 1); + expect(secondLines.end).toBeGreaterThan(secondLines.start); + const note = noteText(ctx); + expect(note).toContain(`window 1: lines 1–${String(firstLines.end)}\n`); + expect(note).not.toContain(`window 1: lines 1–${String(firstLines.end)} ←`); + expect(note).toContain( + `window 2: lines ${String(secondLines.start)}–${String(secondLines.end)} ← the conversation this note summarizes`, + ); + expect(note).toContain(`window 3 (the one you are in now) starts at line ${String(secondLines.end + 1)}`); + await ctx.expectResumeMatches(); + }); + + it('records window line ranges but omits the pointer when the journal has no on-disk path', async () => { + const ctx = recoveryAgent(); + ctx.appendExchange(1, 'old user one', 'old assistant one', 20); + ctx.appendExchange(2, 'recent user two', 'recent assistant two', 40); + + await compactOnce(ctx, 'Compacted summary.'); + + const [record] = applyCompactionRecords(ctx); + expect(record?.wireLines).toEqual({ start: 1, end: expect.any(Number) }); + expect(noteText(ctx)).not.toContain('Context Recovery'); + expect(record?.contextSummary).not.toContain('Context Recovery'); + }); + + it('starts the window after the latest context.clear record', async () => { + const ctx = recoveryAgent(appService(IFileSystemStorageService, locatedStorage(JOURNAL_HOME))); + ctx.appendExchange(1, 'discarded user one', 'discarded assistant one', 20); + ctx.context.clear(); + ctx.appendExchange(2, 'post-clear user two', 'post-clear assistant two', 40); + + await compactOnce(ctx, 'Post-clear summary.'); + + const wire = ctx.get(IWireService); + await wire.flush(); + let line = 0; + let clearLine = 0; + for await (const record of wire.readJournal()) { + line += 1; + if (record.type === 'context.clear') clearLine = line; + } + expect(clearLine).toBeGreaterThan(1); + const [record] = applyCompactionRecords(ctx); + expect(record?.wireLines?.start).toBe(clearLine + 1); + expect(record!.wireLines!.end).toBeGreaterThan(clearLine); + const note = noteText(ctx); + expect(note).toContain(`window 1: lines ${String(clearLine + 1)}–`); + expect(note).not.toContain('window 1: lines 1–'); + }); + + it('counts the appended recovery footer into the compacted token floor', async () => { + const withFooter = recoveryAgent( + appService(IFileSystemStorageService, locatedStorage(JOURNAL_HOME)), + ); + const bare = recoveryAgent(); + for (const ctx of [withFooter, bare]) { + ctx.appendExchange(1, 'old user one', 'old assistant one', 20); + ctx.appendExchange(2, 'recent user two', 'recent assistant two', 40); + await compactOnce(ctx, 'Compacted summary.'); + } + + const [footerRecord] = applyCompactionRecords(withFooter); + const contextSummary = footerRecord!.contextSummary!; + const footer = contextSummary.slice(contextSummary.indexOf('## Context Recovery')); + expect(footer.length).toBeGreaterThan(0); + const withFooterTokens = withFooter.tokenCounting.get().size; + const bareTokens = bare.tokenCounting.get().size; + expect(withFooterTokens - bareTokens).toBe( + withFooter.get(ISessionTokenCountingService).estimateText(footer), + ); + }); + + it('keeps context budget reminders out of the summarizer request', async () => { + const ctx = recoveryAgent(); + ctx.appendExchange(1, 'old user one', 'old assistant one', 20); + ctx.context.append( + reminderMessage('context_budget', 'BUDGET-REMINDER-TEXT'), + reminderMessage('compaction_ahead', 'AHEAD-REMINDER-TEXT'), + ); + ctx.appendExchange(2, 'recent user two', 'recent assistant two', 40); + + await compactOnce(ctx, 'Compacted summary.'); + + const request = JSON.stringify(ctx.lastLlmInput().input.history); + expect(request).toContain('old user one'); + expect(request).toContain('recent assistant two'); + expect(request).not.toContain('BUDGET-REMINDER-TEXT'); + expect(request).not.toContain('AHEAD-REMINDER-TEXT'); + }); + + it('reports what the agent did after the compaction-ahead reminder', async () => { + const records: TelemetryRecord[] = []; + const ctx = recoveryAgent({ telemetry: recordingTelemetry(records) }); + ctx.appendExchange(1, 'old user one', 'old assistant one', 20); + ctx.context.append( + reminderMessage('compaction_ahead', 'AHEAD-REMINDER-TEXT'), + { + role: 'assistant', + content: [{ type: 'text', text: 'persisting state' }], + toolCalls: [ + { type: 'function', id: 'call_write', name: 'Write', arguments: '{}' }, + { type: 'function', id: 'call_bash', name: 'Bash', arguments: '{}' }, + ], + }, + { role: 'tool', content: [{ type: 'text', text: 'ok' }], toolCalls: [], toolCallId: 'call_write' }, + { role: 'tool', content: [{ type: 'text', text: 'ok' }], toolCalls: [], toolCallId: 'call_bash' }, + ); + ctx.appendExchange(2, 'recent user two', 'recent assistant two', 40); + + await compactOnce(ctx, 'Compacted summary.'); + + expect(records).toContainEqual({ + event: 'compaction_finished', + properties: expect.objectContaining({ + ahead_reminder_delivered: true, + ahead_steps_count: 2, + ahead_write_calls_count: 1, + ahead_bash_calls_count: 1, + ahead_todo_calls_count: 0, + }), + }); + }); + + it('reports that no compaction-ahead reminder was delivered when none was', async () => { + const records: TelemetryRecord[] = []; + const ctx = recoveryAgent({ telemetry: recordingTelemetry(records) }); + ctx.appendExchange(1, 'old user one', 'old assistant one', 20); + ctx.appendExchange(2, 'recent user two', 'recent assistant two', 40); + + await compactOnce(ctx, 'Compacted summary.'); + + const finished = records.find((record) => record.event === 'compaction_finished'); + expect(finished?.properties).toMatchObject({ ahead_reminder_delivered: false }); + expect(finished?.properties).not.toHaveProperty('ahead_steps_count'); + }); + + it('exposes the live compaction budget from the numbers that drive auto compaction', () => { + const ctx = recoveryAgent(); + ctx.appendExchange(1, 'old user one', 'old assistant one', 1_000); + + const budget = ctx.get(IAgentFullCompactionService).budget(); + + expect(budget).toEqual({ + used: ctx.get(ISessionTokenCountingService).get(ctx.agentContext).size, + maxSize: 256_000, + triggerRatio: 0.85, + reservedContextSize: 50_000, + triggerTokens: 206_000, + }); + expect(budget.used).toBeGreaterThan(0); + }); + + it('tells the summarizer a recovery pointer follows the note', () => { + const withPointer = renderCompactionInstruction({}); + const withCustom = renderCompactionInstruction({ customInstruction: ' keep the API facts ' }); + + expect(withPointer).toContain('a recovery pointer is appended below your note automatically'); + expect(withPointer).toContain('format for the final answer.\n\nThis conversation'); + expect(withPointer).not.toContain('${'); + expect(withCustom).toContain('Optional user instruction:\nkeep the API facts'); + }); +}); + afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs(); diff --git a/packages/agent-core-v2/test/agent/fullCompaction/strategy.test.ts b/packages/agent-core-v2/test/agent/fullCompaction/strategy.test.ts index ac826910c08..dd37ab68843 100644 --- a/packages/agent-core-v2/test/agent/fullCompaction/strategy.test.ts +++ b/packages/agent-core-v2/test/agent/fullCompaction/strategy.test.ts @@ -176,6 +176,77 @@ describe('DefaultCompactionStrategy', () => { expect(strategy.shouldCompact(28_000)).toBe(true); expect(strategy.shouldBlock(28_000)).toBe(true); }); + + it('describes a trigger budget that agrees with shouldCompact at the ratio threshold', () => { + const strategy = testCompactionStrategy(1_000_000); + + const budget = strategy.budget(); + + expect(budget).toEqual({ + maxSize: 1_000_000, + triggerRatio: 0.85, + reservedContextSize: 0, + triggerTokens: 850_000, + }); + expect(strategy.shouldCompact(budget.triggerTokens)).toBe(true); + expect(strategy.shouldCompact(budget.triggerTokens - 1)).toBe(false); + }); + + it('lets the reserved context lower the trigger budget', () => { + const strategy = new DefaultCompactionStrategy(() => 128_000, { + triggerRatio: 0.85, + blockRatio: 0.85, + reservedContextSize: 50_000, + maxCompactionPerTurn: 3, + maxOverflowCompactionAttempts: 3, + maxRecentMessages: 3, + maxRecentUserMessages: Infinity, + maxRecentSizeRatio: 0.2, + minOverflowReductionRatio: 0.05, + }); + + const budget = strategy.budget(); + + expect(budget.triggerTokens).toBe(78_000); + expect(strategy.shouldCompact(78_000)).toBe(true); + expect(strategy.shouldCompact(77_999)).toBe(false); + }); + + it('rounds a fractional ratio threshold up so the budget never fires early', () => { + const strategy = new DefaultCompactionStrategy(() => 100_001, { + triggerRatio: 0.85, + blockRatio: 0.85, + reservedContextSize: 0, + maxCompactionPerTurn: 3, + maxOverflowCompactionAttempts: 3, + maxRecentMessages: 3, + maxRecentUserMessages: Infinity, + maxRecentSizeRatio: 0.2, + minOverflowReductionRatio: 0.05, + }); + + const budget = strategy.budget(); + + expect(budget.triggerTokens).toBe(85_001); + expect(strategy.shouldCompact(85_001)).toBe(true); + expect(strategy.shouldCompact(85_000)).toBe(false); + }); + + it('ignores a reserve that is not smaller than the window in the trigger budget', () => { + const strategy = new DefaultCompactionStrategy(() => 32_000, { + triggerRatio: 0.85, + blockRatio: 0.85, + reservedContextSize: 50_000, + maxCompactionPerTurn: 3, + maxOverflowCompactionAttempts: 3, + maxRecentMessages: 3, + maxRecentUserMessages: Infinity, + maxRecentSizeRatio: 0.2, + minOverflowReductionRatio: 0.05, + }); + + expect(strategy.budget().triggerTokens).toBe(27_200); + }); }); function testCompactionStrategy(maxSize: number = 1_000): DefaultCompactionStrategy { diff --git a/packages/agent-core-v2/test/agent/loop/loop.test.ts b/packages/agent-core-v2/test/agent/loop/loop.test.ts index afd2147123f..cdd643b906a 100644 --- a/packages/agent-core-v2/test/agent/loop/loop.test.ts +++ b/packages/agent-core-v2/test/agent/loop/loop.test.ts @@ -143,8 +143,8 @@ describe('Agent loop', () => { [emit] turn.step.started { "time": "
-`;continue;case"thead_close":y+=` -`;continue;case"tbody_open":y+=`${w} -`;continue;case"tbody_close":y+=` -`;continue;case"tr_open":y+=`${w} -`;continue;case"tr_close":y+=` -`;continue;case"td_open":y+=`${w} -`;continue;case"th_open":y+=`${w} -`;continue}else if(T.length===1){const S=T[0];if(C==="ordered_list_open"&&S[0]==="start"){y+=`${w}
    -`;continue}if(C==="td_open"&&S[0]==="style"){y+=`${w}
+`;continue;case"thead_close":y+=` +`;continue;case"tbody_open":y+=`${w} +`;continue;case"tbody_close":y+=` +`;continue;case"tr_open":y+=`${w} +`;continue;case"tr_close":y+=` +`;continue;case"td_open":y+=`${w} +`;continue;case"th_open":y+=`${w} +`;continue}else if(E.length===1){const S=E[0];if(C==="ordered_list_open"&&S[0]==="start"){y+=`${w}
    +`;continue}if(C==="td_open"&&S[0]==="style"){y+=`${w}
`;case"th_open":return`${t}`;default:return null}if(n.length===1&&n[0][0]==="style"){if(e.type==="td_open")return`${t}`;if(e.type==="th_open")return`${t}`}return null}function nL(e){const t=e.attrs;return!t||t.length===0?"":t.length===1?``:t.length===2?``:``}function d1e(e){switch(e.type){case"text":case"text_special":case"softbreak":case"hardbreak":case"html_inline":case"code_inline":case"image":return!0;default:return!1}}function iL(e){switch(e.type){case"text":case"text_special":case"softbreak":case"hardbreak":case"html_inline":case"code_inline":return!0;default:return!1}}function $k(e,t){if(e.hidden)return"";const n=e.attrs,i=e.nesting,o=e.tag;if(!n||n.length===0)return i===0?t?`<${o} />`:`<${o}>`:i===-1?``:`<${o}>`;let s=(i===-1?"`}const f1e={langPrefix:"language-",xhtmlOut:!1,breaks:!1},fy=Object.prototype.hasOwnProperty,Mi={code_inline(e,t){return wv(e[t])},code_block(e,t){return JC(e[t])},fence(e,t,n,i,o){const s=e[t],r=s.info?pH(s.info).trim():"",{langName:l,langAttrs:a}=AH(r),u=n.highlight,c=eo(s.content);if(!u)return _0(s,c,r,l,n);const d=u(s.content,l,a);return w4(d)?d.then(h=>_0(s,h||c,r,l,n)):_0(s,d||c,r,l,n)},image(e,t,n,i,o){const s=e[t],r=o.renderInlineAsText(s.children||[],n,i),l=s.attrIndex("alt");return l>=0&&s.attrs?s.attrs[l][1]=r:s.attrs?s.attrs.push(["alt",r]):s.attrs=[["alt",r]],$k(s,n.xhtmlOut===!0)},hardbreak(e,t,n){return n.xhtmlOut?`
-`:`
-`},softbreak(e,t,n){return n.breaks?n.xhtmlOut?`
-`:`
-`:` -`},text(e,t){return eo(e[t].content)},text_special(e,t){return eo(e[t].content)},html_block(e,t){return e[t].content},html_inline(e,t){return e[t].content}};function oL(e,t,n){const i=e.info?pH(e.info).trim():"",{langName:o,langAttrs:s}=AH(i),r=t.highlight,l=eo(e.content);if(!r)return _0(e,l,i,o,t);const a=r(e.content,o,s);if(w4(a))throw new TypeError('Renderer rule "fence" returned a Promise. Use renderAsync() instead.');return _0(e,a||l,i,o,t)}function T8(e,t,n,i){switch(e.type){case"text":return t.text===Mi.text?e.content.length===0?"":eo(e.content):null;case"text_special":return t.text_special===Mi.text_special?e.content.length===0?"":eo(e.content):null;case"softbreak":return t.softbreak===Mi.softbreak?i:null;case"hardbreak":return t.hardbreak===Mi.hardbreak?n:null;case"html_inline":return t.html_inline===Mi.html_inline?e.content:null;case"code_inline":return t.code_inline===Mi.code_inline?wv(e):null;default:return null}}function h1e(e,t,n,i,o){const s=e[0];switch(s.type){case"text":if(o.text===Mi.text)return s.content.length===0?"":eo(s.content);break;case"text_special":if(o.text_special===Mi.text_special)return s.content.length===0?"":eo(s.content);break;case"softbreak":if(o.softbreak===Mi.softbreak)return t.breaks?t.xhtmlOut?`
-`:`
-`:` -`;break;case"hardbreak":if(o.hardbreak===Mi.hardbreak)return t.xhtmlOut?`
-`:`
-`;break;case"html_inline":if(o.html_inline===Mi.html_inline)return s.content;break;case"code_inline":if(o.code_inline===Mi.code_inline)return wv(s);break}const r=o[s.type];if(!r)return $k(s,t.xhtmlOut===!0);const l=r(e,0,t,n,i);return typeof l=="string"?l:v9(l,s.type)}var p1e=class{rules;baseOptions;normalizedBase;constructor(e={}){this.baseOptions={...e},this.normalizedBase=this.buildNormalizedBase(),this.rules={...Mi}}set(e){return this.baseOptions={...this.baseOptions,...e},this.normalizedBase=this.buildNormalizedBase(),this}render(e,t,n){if(!Array.isArray(e))throw new TypeError("render expects token array as first argument");if(e.length===1)return this.renderSingleToken(e,e[0],t,n);const i=this.mergeOptions(t),o=n??{},s=this.rules,r=i.xhtmlOut===!0;let l,a,u,c,d,h,p="",m="",g=!1,y="";for(let b=0;b0&&e[b-1].hidden?` -`:"";if(C==="list_item_open"&&(!v.attrs||v.attrs.length===0)&&b+3${this.renderInlineTokens(S.children||[],i,o)}`,b+=3;continue}}if(b+2 -`,b+=2;continue}}}if(C==="inline"){const T=v.children||[];if(T.length===1){g||(l=s.text,a=s.text_special,u=s.softbreak,c=s.hardbreak,d=s.html_inline,h=s.code_inline,p=i.xhtmlOut?`
-`:`
-`,m=i.breaks?p:` -`,g=!0);const S=T[0];switch(S.type){case"text":if(l===Mi.text){y+=eo(S.content);continue}break;case"text_special":if(a===Mi.text_special){y+=eo(S.content);continue}break;case"softbreak":if(u===Mi.softbreak){y+=m;continue}break;case"hardbreak":if(c===Mi.hardbreak){y+=p;continue}break;case"html_inline":if(d===Mi.html_inline){y+=S.content;continue}break;case"code_inline":if(h===Mi.code_inline){y+=wv(S);continue}break}}y+=this.renderInlineTokens(T,i,o);continue}const M=s[C];if(!M){const T=v.attrs;if(!v.hidden){if(!T||T.length===0)switch(C){case"hr":y+=r?`
-`:`
-`;continue;case"heading_open":y+=`<${v.tag}>`;continue;case"heading_close":y+=` -`;continue;case"paragraph_open":y+=`${w}

`;continue;case"paragraph_close":y+=`

-`;continue;case"list_item_open":{const S=e[b+1];y+=w+(S&&(S.type==="inline"||S.hidden||S.nesting===-1&&S.tag==="li")?"
  • ":`
  • -`);continue}case"list_item_close":y+=`
  • -`;continue;case"bullet_list_open":y+=`${w}
      -`;continue;case"bullet_list_close":y+=`
    -`;continue;case"blockquote_open":y+=w+(e[b+1]&&e[b+1].nesting===-1&&e[b+1].tag==="blockquote"?"
    ":`
    -`);continue;case"blockquote_close":y+=`
    -`;continue;case"ordered_list_open":y+=`${w}
      -`;continue;case"ordered_list_close":y+=`
    -`;continue;case"table_open":y+=`${w} -`;continue;case"table_close":y+=`
    -`;continue;case"thead_open":y+=`${w}
    `;continue;case"td_close":y+=``;continue;case"th_close":y+=``;continue}if(C==="th_open"&&S[0]==="style"){y+=`${w}`;continue}}}y+=this.renderToken(e,b,i);continue}if(C==="code_block"&&M===Mi.code_block){y+=JC(v);continue}if(C==="fence"&&M===Mi.fence){y+=oL(v,i);continue}if(C==="html_block"&&M===Mi.html_block){y+=v.content;continue}const N=M(e,b,i,o,this);typeof N=="string"?y+=N:y+=v9(N,v.type)}return y}async renderAsync(e,t,n){if(!Array.isArray(e))throw new TypeError("render expects token array as first argument");const i=this.mergeOptions(t),o=n??{},s=this.rules;let r="";for(let l=0;l0&&e[t-1].hidden?` -`:"",c=a?`> -`:">";if(!l||l.length===0)return s===0?n.xhtmlOut?`${u}<${r} /${c}`:`${u}<${r}${c}`:s===-1?`${u}(n||(n={...t}),n);if(fy.call(e,"highlight")&&e.highlight!==t.highlight&&(i().highlight=e.highlight),fy.call(e,"langPrefix")){const o=e.langPrefix;o!==t.langPrefix&&(i().langPrefix=o)}if(fy.call(e,"xhtmlOut")){const o=e.xhtmlOut;o!==t.xhtmlOut&&(i().xhtmlOut=o)}if(fy.call(e,"breaks")){const o=e.breaks;o!==t.breaks&&(i().breaks=o)}return n||t}buildNormalizedBase(){return Object.freeze({...f1e,...this.baseOptions})}renderSingleToken(e,t,n,i){const o=this.rules,s=t.type;if(s==="code_block"&&o.code_block===Mi.code_block)return JC(t);if(s==="html_block"&&o.html_block===Mi.html_block)return t.content;const r=this.mergeOptions(n),l=i??{};if(s==="inline")return this.renderInlineTokens(t.children||[],r,l);const a=o[s];if(!a)return t.block?this.renderToken(e,0,r):$k(t,r.xhtmlOut===!0);if(s==="fence"&&a===Mi.fence)return oL(t,r);const u=a(e,0,r,l,this);return typeof u=="string"?u:v9(u,s)}renderInlineTokens(e,t,n){if(!e||e.length===0)return"";const i=this.rules;if(e.length===1)return h1e(e,t,n,this,i);const o=t.xhtmlOut===!0,s=o?`
    -`:`
    -`,r=t.breaks?s:` -`,l=i.text,a=i.text_special,u=i.softbreak,c=i.hardbreak,d=i.html_inline,h=i.code_inline,p=i.link_open,m=i.link_close,g=i.em_open,y=i.em_close,b=i.strong_open,v=i.strong_close;let C="";for(let w=0;w`;if(u===Mi.softbreak&&w+3`,w+=1;continue}if(M.type==="em_open"&&!g&&!y&&w+2${x}`,w+=2;continue}}}if(M.type==="strong_open"&&!b&&!v&&w+2${x}`,w+=2;continue}}}switch(M.type){case"text":if(l===Mi.text){const S=M.content.length===0?"":eo(M.content);if(d===Mi.html_inline&&w+1=4)return!0;continue}if(l===9){if(r+=4-r%4,s++,r>=4)return!0;continue}break}if(s0&&u<=6){if(a=3)return!0;break}default:if(l>=48&&l<=57){let a=s+1;for(;a57)break;a++}if(a=Te,!G&&Ee!==void 0&&(Me=ds(e),G=Me>=Ee)),G){const Z=this.parseFullDocument(e,R,n,Me,!1);return this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",Ls(R,{area:"stream",path:"stream-full",reason:"skip-cache-large-one-shot",unbounded:!!Fc(R)?.unbounded}),Z.tokens}else if(B){const Z=(ke,le,se)=>kese?se:ke;Me===void 0&&(Me=ds(e));const Q=ue&&!ee?eL(e.length,Me,n.options):null,fe=Q?.maxChunkChars??(j?Z(Math.ceil(e.length/$),8e3,64e3):V??1e4),de=Q?.maxChunkLines??(j?Z(Math.ceil(Me/$),150,700):ne??200),pe=Q?.maxChunks??(j?Z(Math.ceil(e.length/64e3),$,32):K),X=e.length>0&&e.charCodeAt(e.length-1)===10,re=O&&e.length>=this.IMPLICIT_STREAM_CHUNK_MIN_CHARS&&Q?.strategy!=="plain";if((F||re)&&(e.length>=fe*2||Me>=de*2)&&X){const ke=Pk(n,e,R,{maxChunkChars:fe,maxChunkLines:de,fenceAware:Q?.fenceAware??ie,maxChunks:pe});return this.cache={src:e,tokens:ke,env:R,lineCount:Me,lastSegment:void 0,globalStateReason:Rl(e)},this.updateCacheLineCount(this.cache,Me),this.recordChunkedParseResult(R,F?"explicit-initial-large-doc":"default-initial-large-doc"),ke}}const oe=this.parseFullDocument(e,R,n,Me);return Me=oe.lineCount,this.cache={src:e,tokens:oe.tokens,env:R,lineCount:Me,lastSegment:void 0,globalStateReason:Rl(e)},this.updateCacheLineCount(this.cache,Me),this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",Ls(R,{area:"stream",path:"stream-full",reason:"initial-parse",unbounded:!!Fc(R)?.unbounded}),oe.tokens}if(e===o.src)return this.stats.total+=1,this.stats.cacheHits+=1,this.stats.lastMode="cache",Ls(o.env,{area:"stream",path:"stream-cache",reason:"same-source"}),o.tokens;const s=e.startsWith(o.src)?e.slice(o.src.length):null;let r=o.globalStateReason;r===void 0&&(r=Rl(o.src),o.globalStateReason=r);const l=r?null:s!==null?this.detectGlobalStateForAppend(o,s):Rl(e),a=r||l;if(a){const R=i??o.env;rd(R);const W=Rl(e),z=this.parseFullDocument(e,R,n),F=z.tokens,O=z.lineCount;return this.cache={src:e,tokens:F,env:R,lineCount:O,lastSegment:void 0,globalStateReason:W},this.updateCacheLineCount(this.cache,O),this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",Ls(R,{area:"stream",path:"stream-full",reason:`global-state:${a}`,unbounded:!!Fc(R)?.unbounded}),F}const u=n.options?.streamOptimizationMinSize??this.MIN_SIZE_FOR_OPTIMIZATION;if(o.src.length5e3?W=8:c.length>1e3?W=6:c.length>200&&(W=4),W=Math.min(W,R);let z=null;const F=n.options?.streamContextParseStrategy??"chars",O=n.options?.streamContextParseMinChars??200,B=n.options?.streamContextParseMinLines??2;let j;const $=()=>(j===void 0&&(j=ds(c)),j),V=this.canDirectlyParseAppend(o),ne=V&&this.shouldUseUnboundedAppend(e,o,c);let K=!1;if(!V)switch(F){case"lines":K=$()>=B;break;case"constructs":if(c.length>=O){K=!0;break}if(v1e(c)){K=!0;break}K=$()>=B;break;case"chars":default:K=c.length>=O}if(W>0&&K){const ie=this.getTailLines(o.src,W)+c;try{const ye=this.core.parse(ie,o.env,n).tokens,Te=ye.findIndex(Ee=>Ee.map&&typeof Ee.map[1]=="number"&&Ee.map[1]>W);if(Te!==-1){const Ee=ye.slice(Te),Me=R-W;Me!==0&&this.shiftTokenLines(Ee,Me),z={tokens:Ee}}}catch{z=null}}else z=null;if(!z){const ie=R;if(ne)z={tokens:x0(n,c,o.env,{mode:"stream"})},ie>0&&this.shiftTokenLines(z.tokens,ie);else{const ye=this.core.parse(c,o.env,n);ie>0&&this.shiftTokenLines(ye.tokens,ie),z=ye}}let ee=0;if(o.tokens.length>0&&z.tokens.length>0){const ie=o.tokens[o.tokens.length-1],ye=z.tokens[0];try{ie.type==="inline"&&ye.type==="inline"&&(ye.children&&ye.children.length>0&&(ie.children||(ie.children=[]),this.appendTokens(ie.children,ye.children)),ie.content=(ie.content||"")+(ye.content||""),ee=1)}catch{ee=0}}const ue=o.tokens.length;if(z.tokens.length>ee){const ie=o.tokens,ye=z.tokens,Te=Math.min(ie.length,ye.length-ee);let Ee=0;for(let Me=Te;Me>0;Me--){let G=!0;for(let oe=0;oe0&&(ee+=Ee),ye.length>ee&&this.appendTokens(o.tokens,ye,ee)}if(o.src=e,o.globalStateReason=null,o.lineCount=R+(j??$()),o.tokens.length>ue){const ie=this.getLastSegment(o.tokens,e,ue,o.tokens.length,e.length-c.length,R);ie?o.lastSegment=ie:o.lastSegment=void 0}else o.lastSegment=void 0;return this.stats.total+=1,this.stats.appendHits+=1,ne&&(this.stats.unboundedAppendHits=(this.stats.unboundedAppendHits||0)+1),this.stats.lastMode="append",Ls(o.env,{area:"stream",path:ne?"stream-unbounded-append":"stream-append",reason:ne?"large-delta":"safe-append",unbounded:ne}),o.tokens}const d=i??o.env,h=this.tryTailSegmentReparse(e,o,d,n);if(h)return this.stats.total+=1,this.stats.tailHits+=1,this.stats.lastMode="tail",Ls(d,{area:"stream",path:"stream-tail",reason:"tail-reparse"}),h;const p=!!n.__explicitStreamChunkFallbackSetting,m=typeof n.__canUseImplicitLargeInputStrategy=="function"?n.__canUseImplicitLargeInputStrategy():!0,g=!!n.options?.streamChunkedFallback,y=!p&&!c&&m,b=g||y,v=n.options?.streamChunkAdaptive!==!1,C=n.options?.streamChunkTargetChunks??8,w=n.options?.streamChunkSizeChars,M=n.options?.streamChunkSizeLines,N=n.options?.streamChunkMaxChunks,T=!!n.__explicitStreamChunkConfig,S=n.options?.autoTuneChunks!==!1,x=n.options?.streamChunkFenceAware??!0;let A=c&&o.lineCount!==void 0?o.lineCount+ds(c):void 0;if(b){A===void 0&&(A=ds(e));const R=($,V,ne)=>$ne?ne:$,W=S&&!T?eL(e.length,A,n.options):null,z=W?.maxChunkChars??(v?R(Math.ceil(e.length/C),8e3,64e3):w??1e4),F=W?.maxChunkLines??(v?R(Math.ceil(A/C),150,700):M??200),O=W?.maxChunks??(v?R(Math.ceil(e.length/64e3),C,32):N),B=e.length>0&&e.charCodeAt(e.length-1)===10,j=y&&e.length>=this.IMPLICIT_STREAM_CHUNK_MIN_CHARS&&W?.strategy!=="plain";if((g||j)&&(e.length>=z*2||A>=F*2)&&B){const $=Pk(n,e,d,{maxChunkChars:z,maxChunkLines:F,fenceAware:W?.fenceAware??x,maxChunks:O});return this.cache={src:e,tokens:$,env:d,lineCount:A,lastSegment:void 0,globalStateReason:Rl(e)},this.updateCacheLineCount(this.cache,A),this.recordChunkedParseResult(d,g?"explicit-fallback-large-doc":"default-fallback-large-doc"),$}}const E=this.parseFullDocument(e,d,n,A),I=E.tokens;return A=E.lineCount,this.cache={src:e,tokens:I,env:d,lineCount:A,lastSegment:void 0,globalStateReason:Rl(e)},this.updateCacheLineCount(this.cache,A),this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",Ls(d,{area:"stream",path:"stream-full",reason:"fallback-full",unbounded:!!Fc(d)?.unbounded}),I}recordChunkedParseResult(e,t){const n=Fc(e)?.chunk,i=n?.fallback?String(n.fallbackReason||"global-state"):null;if(this.stats.total+=1,i){this.stats.fullParses+=1,this.stats.lastMode="full",Ls(e,{area:"stream",path:"stream-full",reason:`global-state:${i}`,unbounded:!!Fc(e)?.unbounded});return}this.stats.chunkedParses=(this.stats.chunkedParses||0)+1,this.stats.lastMode="chunked",Ls(e,{area:"stream",path:"stream-chunked",chunked:!0,reason:t})}parseFullDocument(e,t,n,i,o=!0){const s=Rl(e);e2(t)&&rd(t);const r=typeof n.__canUseImplicitLargeInputStrategy!="function"||n.__canUseImplicitLargeInputStrategy()?bH(n,e.length,i):"no";if(r==="yes"){const a=x0(n,e,t);return Ls(t,{area:"stream",path:"stream-full",reason:"auto-unbounded-char-threshold",unbounded:!0}),{tokens:a,lineCount:i??(o?ds(e):0)}}let l=i;if(r==="need-lines"&&(l=ds(e),kH(n,e.length,l))){const a=x0(n,e,t);return Ls(t,{area:"stream",path:"stream-full",reason:"auto-unbounded-line-threshold",unbounded:!0}),{tokens:a,lineCount:l}}return l===void 0&&(l=o?ds(e):0),{tokens:W1(t,s,()=>this.core.parse(e,t,n).tokens),lineCount:l}}shouldUseUnboundedAppend(e,t,n){return!n||e.length=this.MIN_UNBOUNDED_APPEND_CHARS?!0:ds(n)>=this.MIN_UNBOUNDED_APPEND_LINES}getAppendedSegment(e,t,n){if(n===null||n===void 0&&!t.startsWith(e)||!e.endsWith(` -`))return null;const i=n??t.slice(e.length);if(!i)return null;const o=i.length;if(i.charCodeAt(o-1)!==10)return null;let s=0,r=-1;for(let a=0;a=2));a++);if(s<2)return null;const l=(r===-1?i:i.slice(0,r)).trim();if(l.length===0)return null;if(/^[-=]+$/.test(l)){const a=e.slice(0,-1),u=a.lastIndexOf(` -`);if(a.slice(u+1).trim().length>0)return null}return this.endsInsideOpenFence(e)||this.mayContainReferenceDefinition(i)?null:i}tryTailSegmentReparse(e,t,n,i){const o=this.ensureLastSegment(t);if(!o||o.srcOffset<=0&&o.tokenStart<=0)return null;const s=t.src.slice(0,o.srcOffset);if(!e.startsWith(s))return null;const r=t.src.slice(o.srcOffset),l=e.slice(o.srcOffset);if(l===r)return null;const a=e.startsWith(t.src)?e.slice(t.src.length):null;if(a){const u=this.tryContainerTailAppendMerge(e,t,n,i,o,a);if(u)return u}if(this.mayContainReferenceDefinition(r)||this.mayContainReferenceDefinition(l))return null;try{const u=this.core.parse(l,n,i),c=this.getLastSegment(u.tokens,l);return o.lineStart>0&&this.shiftTokenLines(u.tokens,o.lineStart),t.src=e,t.env=n,t.globalStateReason=null,t.globalStateCarry=void 0,t.tokens.length=o.tokenStart,this.appendTokens(t.tokens,u.tokens),t.lineCount=o.lineStart+ds(l),c?t.lastSegment={tokenStart:o.tokenStart+c.tokenStart,tokenEnd:o.tokenStart+c.tokenEnd,lineStart:o.lineStart+c.lineStart,lineEnd:o.lineStart+c.lineEnd,srcOffset:o.srcOffset+c.srcOffset}:t.lastSegment=null,t.tokens}catch{return null}}getTailLines(e,t){if(t<=0)return"";let n=t;for(let i=e.length-1;i>=0;i--)if(e.charCodeAt(i)===10&&(n--,n===0))return e.slice(i+1);return e}endsInsideOpenFence(e){const n=e.length>4e3?e.length-4e3:0,i=e.slice(n),o=i.length;let s=null,r=0;for(;r<=o;){let l=i.indexOf(` -`,r);l===-1&&(l=o);let a=r;for(;a=3&&(s?s.marker===u&&d>=s.length&&(s=null):s={marker:u,length:d})}}if(l===o)break;r=l+1}return s!==null}peek(){return this.cache?.tokens??g1e}getStats(){return{...this.stats}}appendTokens(e,t,n=0,i=t.length){for(let o=n;oE8?n.slice(n.length-E8):n,i&&(e.globalStateReason=i),i}ensureLastSegment(e){return e.lastSegment!==void 0||(e.lastSegment=this.getLastSegment(e.tokens,e.src)),e.lastSegment}getLastSegment(e,t,n=0,i=e.length,o,s){if(i<=n)return null;let r=Number.POSITIVE_INFINITY,l=-1,a=0;for(let u=i-1;u>=n;u--){const c=e[u];if(c.map&&(c.map[0]l&&(l=c.map[1])),c.nesting<0){a+=-c.nesting;continue}if(c.nesting>0){if(a-=c.nesting,c.level===0&&a<=0){const d=Number.isFinite(r)?r:c.map?.[0]??0,h=l>=d?l:c.map?.[1]??d;return{tokenStart:u,tokenEnd:i,lineStart:d,lineEnd:h,srcOffset:this.getLineStartOffset(t,d,o,s)}}continue}if(c.level===0&&a===0){const d=Number.isFinite(r)?r:c.map?.[0]??0,h=l>=d?l:c.map?.[1]??d;return{tokenStart:u,tokenEnd:i,lineStart:d,lineEnd:h,srcOffset:this.getLineStartOffset(t,d,o,s)}}}return null}getLineStartOffset(e,t,n,i){if(n!==void 0&&i!==void 0&&t>=i)return this.getLineStartOffsetFrom(e,n,t-i);if(t<=0)return 0;let o=t,s=-1;for(;o>0;){if(s=e.indexOf(` -`,s+1),s===-1)return e.length;o--}return s+1}getLineStartOffsetFrom(e,t,n){if(n<=0)return t;let i=n,o=t-1;for(;i>0;){if(o=e.indexOf(` -`,o+1),o===-1)return e.length;i--}return o+1}mayContainReferenceDefinition(e){return e.includes("]:")?/(?:^|\n)[ \t]{0,3}\[[^\]\n]+\]:/.test(e):!1}canDirectlyParseAppend(e){if(!this.endsWithBlankLine(e.src))return!1;const t=this.ensureLastSegment(e);if(!t)return!1;switch(e.tokens[t.tokenStart]?.type){case"paragraph_open":case"heading_open":case"fence":case"code_block":case"html_block":case"hr":case"table_open":return!0;default:return!1}}tryContainerTailAppendMerge(e,t,n,i,o,s){if(!s||this.mayContainReferenceDefinition(s))return null;const r=t.tokens[o.tokenStart];switch(r?.type){case"bullet_list_open":case"ordered_list_open":return this.tryListTailAppendMerge(e,t,n,i,o,s,r);case"table_open":return this.tryTableTailAppendMerge(e,t,n,i,o,s,r);default:return null}}tryListTailAppendMerge(e,t,n,i,o,s,r){if(t.src.length===0||t.src.charCodeAt(t.src.length-1)!==10)return null;const l=o.lineEnd-o.lineStart,a=t.src.length-o.srcOffset;if(l0&&this.shiftTokenLines(d,h);const p=this.getListParagraphMode(t.tokens,o.tokenStart,t.tokens.length,r.level),m=this.getListParagraphMode(c,0,c.length,0);(p==="loose"||m==="loose"||this.endsWithBlankLine(t.src)||(c[0]?.map?.[0]??0)>0)&&(this.setListParagraphVisibility(t.tokens,o.tokenStart,t.tokens.length,r.level,!1),this.setListParagraphVisibility(d,0,d.length,r.level,!1)),t.tokens.splice(t.tokens.length-1,0,...d),t.src=e,t.env=n,t.globalStateReason=null;const g=h+ds(s);t.lineCount=g;const y=this.getDocLineCount(e,g);return r.map&&(r.map[1]=y),t.lastSegment={tokenStart:o.tokenStart,tokenEnd:t.tokens.length,lineStart:o.lineStart,lineEnd:y,srcOffset:o.srcOffset},t.tokens}tryTableTailAppendMerge(e,t,n,i,o,s,r){if(t.src.length===0||t.src.charCodeAt(t.src.length-1)!==10||/(?:^|\n)[ \t]*\n/.test(s))return null;const l=o.lineEnd-o.lineStart,a=t.src.length-o.srcOffset;if(l=0?d.slice(h.tbodyOpenIndex+1,h.tbodyCloseIndex):d.slice(h.tbodyOpenIndex,h.tbodyCloseIndex+1);if(m.length===0)return null;const g=o.lineEnd-2;g!==0&&this.shiftTokenLines(m,g);const y=p.tbodyCloseIndex>=0?p.tbodyCloseIndex:p.tableCloseIndex,b=t.lineCount??ds(t.src);t.tokens.splice(y,0,...m),t.src=e,t.env=n,t.globalStateReason=null;const v=b+ds(s);t.lineCount=v;const C=this.getDocLineCount(e,v);if(r.map&&(r.map[1]=C),p.tbodyOpenIndex>=0){const w=t.tokens[p.tbodyOpenIndex];w?.map&&(w.map[1]=C)}return t.lastSegment={tokenStart:o.tokenStart,tokenEnd:t.tokens.length,lineStart:o.lineStart,lineEnd:C,srcOffset:o.srcOffset},t.tokens}getTableHeaderContext(e){const t=e.indexOf(` -`);if(t<0)return null;const n=e.indexOf(` -`,t+1);return n<0?null:e.slice(0,n+1)}getTableBodySection(e,t,n,i){if(t<0||t>=n||e[t]?.type!=="table_open")return null;let o=-1;for(let l=n-1;l>t;l--){const a=e[l];if(a.type==="table_close"&&a.level===i){o=l;break}}if(o<0)return null;let s=-1,r=-1;for(let l=t+1;l=0){for(let l=o-1;l>s;l--){const a=e[l];if(a.type==="tbody_close"&&a.level===i+1){r=l;break}}if(r<0)return null}return{tableCloseIndex:o,tbodyOpenIndex:s,tbodyCloseIndex:r}}isSingleTopLevelContainer(e,t,n,i){if(e.length<2)return!1;const o=e[0],s=e[e.length-1];if(o.type!==t||s.type!==n||o.level!==0||s.level!==0||i!==void 0&&o.markup!==i)return!1;let r=0;for(let l=0;l0&&l0||a.nesting<0)&&(r+=a.nesting)}return r===0}getListParagraphMode(e,t,n,i){let o=!1,s=!1;const r=i+2;for(let l=t;l=0;){const i=e.charCodeAt(n);if(i===32||i===9){n--;continue}return i===10}return!0}getDocLineCount(e,t=ds(e)){return e.length===0?0:e.charCodeAt(e.length-1)===10?t:t+1}shiftTokenLines(e,t){if(t===0)return;let n=null;for(let i=0;i=0;s--)n.push(o.children[s]);for(;n.length>0;){const s=n.pop();if(s.map&&(s.map[0]+=t,s.map[1]+=t),s.children)for(let r=s.children.length-1;r>=0;r--)n.push(s.children[r])}}}}};const rL={default:a1e,zero:u1e,commonmark:l1e};function w1e(e){return{core:e.core.ruler.version,block:e.block.ruler.version,inline:e.inline.ruler.version,inline2:e.inline.ruler2.version}}function C1e(e,t){return e.core.ruler.version!==t.core||e.block.ruler.version!==t.block||e.inline.ruler.version!==t.inline||e.inline.ruler2.version!==t.inline2}function lL(e){return e.experimental?{...e,...e.experimental}:e}function La(e,t){if(!e)return!1;if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0)return!0;const n=e.experimental;return!!n&&Object.prototype.hasOwnProperty.call(n,t)&&n[t]!==void 0}function aL(e,t,n){for(let i=0;i=4?n.quotes=[S[0],S[1],S[2],S[3]]:n.quotes=["“","”","‘","’"]}let r=aL(s?.options,o,["fullChunkSizeChars","fullChunkSizeLines","fullChunkMaxChunks"]),l=aL(s?.options,o,["streamChunkSizeChars","streamChunkSizeLines","streamChunkMaxChunks"]),a=uL(s?.options,o,"fullChunkedFallback"),u=uL(s?.options,o,"streamChunkedFallback"),c=!1,d=null,h=null;const p=new fpe;let m=null;const g=()=>(m||(m=new m1e(n)),m);let y=null;const b=()=>(y||(y=new b1e(p)),y);let v=null;const C=()=>(v||(v=new Ej({fuzzyLink:!0})),v),w=S=>!c&&!!d&&!C1e(S,d),M=(S,x)=>i==="default"&&!c&&m===null&&h!==null&&S.parse===h&&w(S)&&!S.stream.enabled&&x<(S.options.autoUnboundedThresholdChars??4e6)&&S.options.html===!1&&S.options.xhtmlOut===!1&&S.options.breaks===!1&&S.options.langPrefix==="language-"&&S.options.linkify===!1&&S.options.typographer===!1&&S.options.highlight===null,N=(S,x)=>i==="default"&&!c&&w(S)&&!S.stream.enabled&&!S.options.fullChunkedFallback&&x<(S.options.autoUnboundedThresholdChars??4e6)&&S.options.html===!1&&S.options.linkify===!1&&S.options.typographer===!1,T={core:p,block:p.block,inline:p.inline,get linkify(){const S=C();return Object.defineProperty(this,"linkify",{value:S,writable:!0,configurable:!0}),S},get renderer(){const S=g();return Object.defineProperty(this,"renderer",{value:S,writable:!0,configurable:!0}),S},options:n,__explicitFullChunkConfig:r,__explicitStreamChunkConfig:l,__explicitFullChunkFallbackSetting:a,__explicitStreamChunkFallbackSetting:u,__canUseImplicitLargeInputStrategy(){return w(this)},set(S){const x=lL(S);return this.options={...this.options,...x},(La(S,"fullChunkSizeChars")||La(S,"fullChunkSizeLines")||La(S,"fullChunkMaxChunks"))&&(r=!0,this.__explicitFullChunkConfig=!0),(La(S,"streamChunkSizeChars")||La(S,"streamChunkSizeLines")||La(S,"streamChunkMaxChunks"))&&(l=!0,this.__explicitStreamChunkConfig=!0),La(S,"fullChunkedFallback")&&(a=!0,this.__explicitFullChunkFallbackSetting=!0),La(S,"streamChunkedFallback")&&(u=!0,this.__explicitStreamChunkFallbackSetting=!0),m&&m.set(x),typeof x.stream=="boolean"&&(this.stream.enabled=x.stream,y&&(y.reset(),y.resetStats())),this},configure(S){const x=typeof S=="string"?rL[S]:S;if(!x)throw new Error("Wrong `markdown-it` preset, can't be empty");if(x.options&&this.set(x.options),x.components){const A=x.components;A.core?.rules&&this.core.ruler.enableOnly(A.core.rules),A.block?.rules&&this.block.ruler.enableOnly(A.block.rules),A.inline?.rules&&this.inline.ruler.enableOnly(A.inline.rules),A.inline2?.rules&&this.inline.ruler2.enableOnly(A.inline2.rules)}return this},enable(S,x){const A=Array.isArray(S)?S:[S],E=[this.core?.ruler,this.block?.ruler,this.inline?.ruler,this.inline?.ruler2],I=new Set;for(const R of E){if(!R)continue;const W=R.enable(A,!0);for(let z=0;z!I.has(W));if(R.length)throw new Error(`Rules manager: invalid rule name ${R.join(", ")}`)}return this},disable(S,x){const A=Array.isArray(S)?S:[S],E=[this.core?.ruler,this.block?.ruler,this.inline?.ruler,this.inline?.ruler2],I=new Set;for(const R of E){if(!R)continue;const W=R.disable(A,!0);for(let z=0;z!I.has(W));if(R.length)throw new Error(`Rules manager: invalid rule name ${R.join(", ")}`)}return this},use(S,...x){const A=typeof S=="function"?S:S&&typeof S.default=="function"?S.default:void 0;if(!A)throw new TypeError("MarkdownIt.use: plugin must be a function");const E=[this,...x],I=S;return c=!0,A.apply(I,E),this},render(S,x){let A;if(M(this,S.length)){x!==void 0&&(hl(x),A=y8("render"));const R=A?Zp():0,W=A?YE(S,A):QE(S);if(A&&(A.attemptMs=Zp()-R,W===null&&(A.fallbackReason="unsupported-stock-subset"),Sg(x,A)),W!==null)return x!==void 0&&Ls(x,{area:"render",path:"stock-fast",reason:"stock-subset"}),W}const E=x??{},I=this.parse(S,E);return A&&Sg(E,A),g().render(I,this.options,E)},async renderAsync(S,x){let A;if(M(this,S.length)){x!==void 0&&(hl(x),A=y8("render"));const R=A?Zp():0,W=A?YE(S,A):QE(S);if(A&&(A.attemptMs=Zp()-R,W===null&&(A.fallbackReason="unsupported-stock-subset"),Sg(x,A)),W!==null)return x!==void 0&&Ls(x,{area:"render",path:"stock-fast",reason:"stock-subset"}),W}const E=x??{},I=this.parse(S,E);return A&&Sg(E,A),g().renderAsync(I,this.options,E)},renderIterable(S,x={}){const A=this.parseIterable(S,x);return g().render(A,this.options,x)},async renderAsyncIterable(S,x={}){const A=await this.parseAsyncIterable(S,x);return g().renderAsync(A,this.options,x)},renderInline(S,x={}){const A=this.parseInline(S,x);return g().render(A,this.options,x)},validateLink:rH,normalizeLink:lH,normalizeLinkText:aH,utils:Hde,helpers:{...Efe},parse(S,x){if(typeof S!="string")throw new TypeError("Input data should be a String");if(x!==void 0&&hl(x),N(this,S.length)){const R=x===void 0?void 0:y8("parse"),W=R?Zp():0,z=xpe(S,R);if(R&&(R.attemptMs=Zp()-W,z===null&&(R.fallbackReason="unsupported-stock-subset"),Sg(x,R)),z!==null)return x!==void 0&&Ls(x,{area:"parse",path:"stock-fast",reason:"stock-subset"}),z}const A=x??{};let E;if(!this.stream.enabled&&!this.options.fullChunkedFallback&&w(this)){const R=bH(this,S.length);if(R==="yes"){const W=x0(this,S,A);return Ls(x,{area:"parse",path:"auto-unbounded",unbounded:!0,reason:"char-threshold"}),W}R==="need-lines"&&(E=ds(S))}if(!this.stream.enabled){const R=S.length,W=this.options.autoTuneChunks!==!1,z=r,F=!a&&w(this),O=!!this.options.fullChunkedFallback,B=F&&R>=2e5;let j;(O||B||E!==void 0)&&(j=E??ds(S));const $=(O||B)&&W&&!z?r1e(R,j,this.options):null;if(O||B){const V=j??0;if(O?R>=(this.options.fullChunkThresholdChars??2e4)||V>=(this.options.fullChunkThresholdLines??400):B){if($&&$.strategy!=="plain"){const ne=Pk(this,S,A,{maxChunkChars:$.maxChunkChars,maxChunkLines:$.maxChunkLines,fenceAware:$.fenceAware,maxChunks:$.maxChunks});return x&&cL(x,O?"explicit-full-chunk":"default-large-string"),ne}if(O){const ne=(G,oe,Z)=>GZ?Z:G,K=this.options.fullChunkAdaptive!==!1,ee=this.options.fullChunkTargetChunks??8,ue=ne(Math.ceil(R/ee),8e3,64e3),ie=ne(Math.ceil(V/ee),150,700),ye=K?ue:this.options.fullChunkSizeChars??1e4,Te=K?ie:this.options.fullChunkSizeLines??200,Ee=K?ne(Math.ceil(R/64e3),ee,32):this.options.fullChunkMaxChunks,Me=Pk(this,S,A,{maxChunkChars:ye,maxChunkLines:Te,fenceAware:this.options.fullChunkFenceAware??!0,maxChunks:Ee});return x&&cL(x,"explicit-full-chunk"),Me}}}if(E!==void 0&&w(this)&&kH(this,R,j??E)){const V=x0(this,S,A);return Ls(x,{area:"parse",path:"auto-unbounded",unbounded:!0,reason:"line-threshold"}),V}}const I=Rl(S);return Ls(x,{area:"parse",path:"plain",reason:"default-plain"}),W1(A,I,()=>p.parse(S,A,this).tokens)},parseIterable(S,x={}){return hl(x),n1e(this,S,x)},parseAsyncIterable(S,x={}){return hl(x),i1e(this,S,x)},parseIterableToSink(S,x,A={}){return hl(A),o1e(this,S,x,A)},parseAsyncIterableToSink(S,x,A={}){return hl(A),s1e(this,S,x,A)},parseInline(S,x={}){if(typeof S!="string")throw new TypeError("Input data should be a String");hl(x),e2(x)&&rd(x);const A=p.createState(S,x,this);return A.inlineMode=!0,p.process(A),A.tokens}};if(T.stream={enabled:!!n.stream,parse(S,x){return T.stream.enabled?b().parse(S,x,T):T.parse(S,x??{})},reset(){b().reset()},peek(){return y?y.peek():[]},stats(){return y?y.getStats():{total:0,cacheHits:0,appendHits:0,unboundedAppendHits:0,tailHits:0,fullParses:0,resets:0,chunkedParses:0,lastMode:"idle"}},resetStats(){y&&y.resetStats()}},s?.components){const S=s.components;S.core?.rules&&T.core.ruler.enableOnly(S.core.rules),S.block?.rules&&T.block.ruler.enableOnly(S.block.rules),S.inline?.rules&&T.inline.ruler.enableOnly(S.inline.rules),S.inline2?.rules&&T.inline.ruler2.enableOnly(S.inline2.rules)}return d=w1e(T),h=T.parse,T}var x1e=A1e;const SH=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],S1e=["a","abbr","b","bdi","bdo","button","cite","code","data","del","dfn","em","font","i","ins","kbd","label","mark","q","s","samp","small","span","strong","sub","sup","time","u","var"],_H=["article","aside","blockquote","details","div","figcaption","figure","footer","header","h1","h2","h3","h4","h5","h6","li","main","nav","ol","p","pre","section","summary","table","tbody","td","th","thead","tr","ul"],_1e=["svg","g","path"],I1e=["address","audio","body","canvas","caption","colgroup","datalist","dd","dialog","dl","dt","fieldset","form","head","hgroup","html","iframe","legend","map","menu","meter","noscript","object","optgroup","option","output","picture","progress","rp","rt","ruby","script","select","style","template","textarea","tfoot","title","video"],M1e=["onclick","onerror","onload","onmouseover","onmouseout","onmousedown","onmouseup","onkeydown","onkeyup","onfocus","onblur","onsubmit","onreset","onchange","onselect","ondblclick","ontouchstart","ontouchend","ontouchmove","ontouchcancel","onwheel","onscroll","oncopy","oncut","onpaste","oninput","oninvalid","onsearch","innerhtml","outerhtml","textcontent","innertext","srcdoc","ping"],T1e=["action","data","href","src","srcset","poster","xlink:href","formaction"],E1e=["script"],L1e=["pre","iframe","picture","script","style","table","tbody","td","tfoot","th","thead","textarea","tr","title","video"],mf=new Set(SH),IH=new Set(_H),Cv=new Set([...SH,...S1e,..._H,..._1e]),MH=new Set([...Cv,...I1e]),N1e=new Set(M1e),D1e=new Set(T1e),i2=new Set(E1e),TH=new Set(L1e);function EH(e){let t="";for(const n of e){const i=n.charCodeAt(0);i<=31||i>=127&&i<=159||/\s/u.test(n)||(t+=n)}return t}const F1e={amp:"&",bsol:"\\",colon:":",newline:` -`,sol:"/",tab:" "};function LH(e){return e.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z][a-z0-9]+));?/gi,(t,n,i,o)=>{const s=n??i;if(s){const r=Number.parseInt(s,n?10:16);try{return Number.isFinite(r)?String.fromCodePoint(r):""}catch{return""}}return F1e[String(o??"").toLowerCase()]??t})}const hy=new Set(["http","https","mailto","tel"]),R1e=new Set(["javascript","vbscript","data","file","ftp","blob","filesystem","intent","chrome","chrome-extension","moz-extension","ms-browser-extension","view-source"]),th=new Set(["http","https"]);function NH(e){return e.match(/^([a-z][a-z0-9+.-]*):/i)?.[1]?.toLowerCase()??""}const O1e=/^https?:\/\//i;function P1e(e){if(!O1e.test(e))return!1;for(const t of e){const n=t.charCodeAt(0);if(t==="&"||n<=32||n>=127&&n<=159||n>127&&/\s/u.test(t))return!1}return!0}function $1e(e,t,n){if(!I0(t,n)||!e.startsWith("file:///"))return!1;const i=e.charAt(8);return i!=="/"&&i!=="\\"}function I0(e,t){return e?(e==="a"||e==="area")&&(!t||t==="href"||t==="xlink:href"):!t||t==="href"}function B1e(e,t){return t==="href"||t==="xlink:href"?I0(e,t)?hy:th:t==="src"||t==="srcset"||t==="poster"||t==="action"||t==="formaction"||t==="data"?th:(I0(e,t),hy)}function Wh(e,t={}){if(P1e(e))return!1;const n=EH(LH(e)).toLowerCase(),i=String(t.tagName??"").toLowerCase(),o=String(t.attrName??"").toLowerCase();if(!n)return!1;if(n.startsWith("data:")){const r=/^data:image\/(?:png|gif|jpe?g|webp|avif|bmp);/i.test(n);return i==="img"&&o==="src"?!r:!0}if(/^[\\/]{2}/.test(n))return!0;if(n.startsWith("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("#")||n.startsWith("?"))return!1;const s=NH(n);return s?s==="file"?!$1e(n,i,o):I0(i,o)?R1e.has(s):!B1e(i,o).has(s):!1}function z1e(e){const t=LH(String(e??"")).trim();if(!t||t.startsWith("#")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../")||t.startsWith("?"))return!1;const n=NH(EH(t).toLowerCase());return n==="http"||n==="https"}function j1e(e,t={}){const n=String(e??"").trim();return n?Wh(n,t)?"":n:""}function dL(e){return j1e(e,{tagName:"img",attrName:"src"})}function H1e(e,t,n){function i(h){return h.trim().split(" ",2)[0]===t}function o(h,p,m,g,y){return h[p].nesting===1&&h[p].attrJoin("class",t),y.renderToken(h,p,m,g,y)}n=n||{};const s=3,r=n.marker||":",l=r.charCodeAt(0),a=r.length,u=n.validate||i,c=n.render||o;function d(h,p,m,g){let y,b=!1,v=h.bMarks[p]+h.tShift[p],C=h.eMarks[p];if(l!==h.src.charCodeAt(v))return!1;for(y=v+1;y<=C&&r[(y-v)%a]===h.src[y];y++);const w=Math.floor((y-v)/a);if(w=m||(v=h.bMarks[T]+h.tShift[T],C=h.eMarks[T],v=4)){for(y=v+1;y<=C&&r[(y-v)%a]===h.src[y];y++);if(!(Math.floor((y-v)/a)=2){const r=Number(s[0]),l=Number(s[1]);Number.isFinite(r)&&Number.isFinite(l)&&(o.map=[r+t,Math.min(l+t,n)])}Array.isArray(o.children)&&DH(o.children,t,n)}}function q1e(e){["admonition","info","warning","error","tip","danger","note","caution"].forEach(t=>{e.use(H1e,t,{render(n,i){return n[i].nesting===1?`
    `:`
    -`}})}),e.block.ruler.before("fence","vmr_container_fallback",(t,n,i,o)=>{const s=t,r=s.bMarks[n]+s.tShift[n],l=s.eMarks[n],a=s.src.slice(r,l),u=a.match(/^:::\s*([^\s{]+)/);if(!u)return!1;const c=u[1];if(!c.trim())return!1;const d=a.slice(u[0].length).trim();let h,p;const m=d.indexOf("{"),g=m>=0?d.slice(m).trimStart():void 0;if(m===-1)h=d||void 0;else{if(h=d.slice(0,m).trim()||void 0,g?.startsWith("{")){let N=0,T=-1;for(let S=0;S0&&(p=g.slice(0,T))}p||(h=d||void 0)}if(o)return!0;const y=!!s.env.__markstreamFinal;let b=n+1,v=!1;for(;b<=i;){const N=s.bMarks[b]+s.tShift[b],T=s.eMarks[b];if(s.src.slice(N,T).trim()===":::"){v=!0;break}b++}v||(b=i);const C=s.push("vmr_container_open","div",1);if(C.attrSet("class",`vmr-container vmr-container-${c}`),C.map=[n,v?b:i],C.meta={...C.meta??{},unclosed:!v&&!y},h&&C.attrSet("data-args",h),p)try{const N=JSON.parse(p);for(const[T,S]of Object.entries(N)){const x=S!=null&&typeof S=="object";C.attrSet(`data-${T}`,x?JSON.stringify(S):String(S))}}catch{const N=W1e(p);if(N)for(const[T,S]of Object.entries(N)){const x=S!=null&&typeof S=="object";C.attrSet(`data-${T}`,x?JSON.stringify(S):String(S))}else C.attrSet("data-attrs",p)}const w=[];for(let N=n+1;NN.trim().length>0)){let N=w.join(` -`);N.endsWith(` -`)||(N+=` -`),N.endsWith(` - -`)||(N+=` -`);const T=s.tokens[s.tokens.length-1];T&&(T.raw=N);const S=[];s.md.block.parse(N,s.md,s.env,S),DH(S,n+1,n+1+w.length),s.tokens.push(...S)}const M=s.push("vmr_container_close","div",-1);return v||(M.hidden=!0,M.map=[i,i]),s.line=v?b+1:b,!0},{alt:["paragraph","reference","blockquote","list"]})}function xu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gs(e){let t=!1,n=!1;for(let i=0;i")return i}return-1}function C4(e){const t=[],n=/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;let i;for(;(i=n.exec(e))!==null;){const o=i[1];if(!o)continue;const s=i[2]||i[3]||i[4]||"";t.push([o,s])}return t}const U1e=/^[a-z][a-z0-9_-]*$/;function fL(e){return U1e.test(String(e??"").trim().toLowerCase())}function Ga(e){const t=String(e??"").trim();if(!t)return"";if(!t.startsWith("<"))return fL(t)?t.toLowerCase():"";let n=1;for(;n]/.test(s)?"":fL(o)?o:""}function kp(e){if(!e||e.length===0)return[];const t=new Set,n=[];for(const i of e){const o=Ga(i);!o||t.has(o)||(t.add(o),n.push(o))}return n}function V1e(...e){const t=new Set,n=[];for(const i of e)for(const o of kp(i))t.has(o)||(t.add(o),n.push(o));return n}function K1e(e){const t=kp(e);return{key:t.join(","),tags:t}}function FH(e){return Ga(e)}function Z1e(e,t){const n=String(e??""),i=Ga(t);if(!i)return!1;const o=xu(i),s=n.match(new RegExp(String.raw`^\s*<\s*${o}(?:\s[^>]*)?(\s*\/)?>`,"i"));return s?s[1]?!0:new RegExp(String.raw`<\s*\/\s*${o}\s*>`,"i").test(n):!1}function RH(e,t){const n=Ga(t);return!!n&&!Cv.has(n)&&!Z1e(e,n)}function G1e(e,t){const n=String(e??""),i=Ga(t);if(!i)return n;const o=xu(i),s=new RegExp(String.raw`^\s*<\s*${o}(?:\s[^>]*)?>\s*`,"i"),r=new RegExp(String.raw`\s*<\s*\/\s*${o}\s*>\s*$`,"i");return n.replace(s,"").replace(r,"")}const OH=mf,Q1e=Cv,PH=new Set(IH);PH.delete("details");const Y1e=/<([A-Z][\w-]*)(?=[\s/>]|$)/gi,J1e=/<\/\s*([A-Z][\w-]*)(?=[\s/>]|$)/gi,XC=/^<\s*(?:\/\s*)?([A-Z][\w-]*)/i,X1e=/^<\s*([A-Z][\w:-]*)(?=[\s/>]|$)/i;function Bk(e){return(e.match(XC)?.[1]??"").toLowerCase()}function ex(e){return/^\s*<\s*\//.test(e)}function tx(e,t){return OH.has(t)||/\/\s*>\s*$/.test(e)}function eme(e,t){let n=0;for(let i=0;i0&&n--;continue}tx(o,s)||n++}}return n}function hL(e,t,n=0){const i=new RegExp(String.raw`<\s*(\/?)\s*${xu(t)}(?=[\s>/])[^>]*>`,"gi");i.lastIndex=Math.max(0,n);let o=0,s;for(;(s=i.exec(e))!==null;){const r=s[0]??"",l=!!s[1],a=!l&&/\/\s*>$/.test(r);if(l){if(o===0)return{start:s.index,end:s.index+r.length};o--;continue}a||o++}return null}function nme(e,t){const n=new RegExp(String.raw`<\s*(\/?)\s*${xu(t)}(?=[\s>/])[^>]*>`,"gi");let i=0,o;for(;(o=n.exec(e))!==null;){const s=o[0]??"",r=!!o[1],l=!r&&/\/\s*>$/.test(s);if(r){i>0&&i--;continue}l||i++}return i}function zk(e){const t=e;return String(t.raw??t.content??t.markup??"")}function ime(e){const t=e;return t.meta||(t.meta={}),t.meta}function L8(e,t,n){const i=ime(e);i.markstreamCustomHtmlRaw=t,i.markstreamCustomHtmlInner=n}function ome(e,t){if(!t.size)return;const n=Array.from(t,p=>new RegExp(String.raw`<\s*${xu(p)}(?=[\s>/])`,"i")),i=[];let o=!1;const s=p=>p?n.some(m=>m.test(p)):!1,r=p=>{if(!(!p||!i.length))for(const m of i)m.raw+=p,m.inner+=p},l=()=>{!i.length||!o||(r(` -`),o=!1)},a=p=>{r(p)},u=p=>{for(let g=0;g{const m=i[i.length-1]?.tag;if(!m)return null;const g=new RegExp(String.raw`^\s*<\s*\/\s*${xu(m)}\s*>`,"i");return p.match(g)?.[0]??null},d=p=>!!c(p),h=(p,m,g)=>{const y=g??(p.type==="html_inline"?Bk(m):"");if(!(y&&t.has(y))){r(m);return}const b=ex(m),v=!b&&tx(m,y);if(b){if(!i.length||i[i.length-1].tag!==y){r(m);return}u(m);return}if(r(m),v){L8(p,m,"");return}i.push({tag:y,token:p,raw:m,inner:""})};for(const p of e){if(p.type==="inline"&&Array.isArray(p.children)){const m=String(p.content??"");if(d(m)?o=!1:l(),!i.length&&!s(m)){o=!1;continue}let g=0,y=!0;for(const b of p.children){const v=zk(b),C=b.type==="html_inline"?Bk(v):"",w=C&&t.has(C);let M=v;if(y&&m&&v&&(i.length||w)){const N=m.indexOf(v,g);if(N!==-1)a(m.slice(g,N)),M=m.slice(N,N+v.length),g=N+v.length;else{if(i.length&&!w)continue;y=!1}}h(b,M,C)}y&&m&&g0;continue}if(i.length&&typeof p.content=="string"){const m=zk(p),g=p.type==="html_block"?c(m):null;if(g){u(`${o?` -`:""}${g}`),o=i.length>0;continue}if(!p.content)continue;l(),r(p.content),o=!0}}for(const p of i)L8(p.token,p.raw,p.inner)}function sme(e){return/^\s*<\s*[!?]/.test(e)}function rme(e){const t=new Set(Q1e);if(e&&Array.isArray(e))for(const n of e){const i=String(n??"").trim();if(!i)continue;const o=i.match(/^[<\s/]*([A-Z][\w-]*)/i);o&&t.add(o[1].toLowerCase())}return t}function pL(e,t){if(t.has(e))return!0;for(const n of t)if(n.startsWith(e))return!0;return!1}function lme(e,t){let n=null;for(const s of e.matchAll(Y1e)){const r=s.index??-1;if(r<0)continue;const l=(s[1]??"").toLowerCase();pL(l,t)&&gs(e.slice(r))===-1&&(!n||r")&&(!n||s")&&(!n||s{const p=h,m=new Set(n),g=Array.isArray(p.env?.__markstreamCustomHtmlTags)?p.env.__markstreamCustomHtmlTags:[];for(const C of g){const w=Ga(String(C??""));w&&m.add(w)}const y=rme(Array.from(m)),b=new Set(cme);for(const C of m)b.add(C);return{autoCloseInlineTagSet:b,commonHtmlTags:y,customTagSet:m,shouldMergeHtmlBlockTag:C=>m.has(C)||!y.has(C)||PH.has(C)}},o=h=>{if(h.type==="html_block")return String(h.content??"");if(h.type!=="inline"||!Array.isArray(h.children)||h.children.length!==1)return"";const p=h.children[0];return p?.type!=="html_block"?"":String(h.content??p.content??"")},s=(h,p)=>{h.type="html_block",h.content=p,h.raw=p,h.children=[]},r=h=>h.replace(/^(?:\r?\n)+/,""),l=h=>/^(?: {4}|\t)/.test(h),a=h=>h.replace(/^(?: {4}|\t)/gm,""),u=(h,p)=>{const m=r(h);if(!/\S/.test(m))return[];if(l(m))return[{type:"code_block",content:a(m),raw:m}];const g=m.replace(/^[\t ]+/,"");if(!g)return[];if(g.startsWith("<"))return[{type:"html_block",content:g}];const y={type:"inline",tag:"",nesting:0,content:g,children:[{type:"text",content:g,raw:g}]};return p==="paragraph"?[{type:"paragraph_open",tag:"p",nesting:1},y,{type:"paragraph_close",tag:"p",nesting:-1}]:p==="text"?[{type:"text",content:g,raw:g}]:[y]},c=(h,p,m)=>h[p-1]?.type==="paragraph_open"&&h[p+1]?.type==="paragraph_close"?"inline":m,d=(h,p)=>{const m=r(p);return!/\S/.test(m)||h.type!=="inline"||!Array.isArray(h.children)?!1:(h.content=`${String(h.content??"")}${m}`,h.children.push({type:"text",content:m,raw:m}),!0)};e.core.ruler.after("inline","fix_html_inline_streaming",h=>{const p=h.tokens??[],{commonHtmlTags:m,customTagSet:g}=i(h);for(const y of p){const b=y;if(b.type!=="inline"||!Array.isArray(b.children))continue;const v=String(b.content??""),C=b.children.length?b.children:v.includes("<")?[{type:"text",content:v,raw:v}]:null;if(C)try{const w=ume(C,m);if(b.children=w.children,w.pendingBuffer){const M=v.lastIndexOf(w.pendingBuffer);if(M!==-1){const N=v.slice(0,M);b.content=N,typeof b.raw=="string"&&(b.raw=N)}}}catch(w){console.error("[applyFixHtmlInlineTokens] failed to fix streaming html inline",w)}}ome(p,g)}),e.core.ruler.push("fix_html_inline_tokens",h=>{const p=h.tokens??[],{autoCloseInlineTagSet:m,customTagSet:g,shouldMergeHtmlBlockTag:y}=i(h),b=[];for(let v=0;v0){const[M,N]=b[b.length-1];if(v!==N){if(C.type==="paragraph_open"||C.type==="paragraph_close"){p.splice(v,1),v--;continue}const T=String(C.content??C.raw??"");if(T){const S=p[N],x=`${String(S.content||"")} -${T}`,A=gs(x),E=A===-1?null:hL(x,M,A+1);if(E){const I=x.slice(0,E.end),R=x.slice(E.end);S.content=I,S.loading=!1,p.splice(v,1),b.pop();const W=d(S,R)?[]:u(R,c(p,v,"paragraph"));W.length&&p.splice(v,0,...W),v--;continue}S.content=x,S.loading!==!1&&(S.loading=!0)}p.splice(v,1),v--;continue}}const w=o(C);if(w){if(sme(w))continue;const M=(w.match(/<\s*(?:\/\s*)?([^\s>/]+)/)?.[1]??"").toLowerCase(),N=/^\s*<\s*\//.test(w);if(!M||!y(M))continue;if(s(C,w),!N)M&&!new RegExp(`^\\s*<\\s*${M}\\b[^>]*\\/\\s*>`,"i").test(w)&&nme(w,M)>0&&b.push([M,v]);else if(b.length>0&&M&&b[b.length-1][0]===M){const[,T]=b[b.length-1],S=p[T];S.content=`${String(S.content||"")} -${w}`,S.loading=!1,b.pop(),p.splice(v,1),v--}continue}else if(b.length>0){if(C.type==="paragraph_open"||C.type==="paragraph_close"){p.splice(v,1),v--;continue}const M=C.content||"",N=new RegExp(`<\\s*\\/\\s*${b[b.length-1][0]}\\s*>`,"i").test(M);if(M){const[,T]=b[b.length-1],S=p[T];S.content=`${S.content||""} -${M}`,S.loading!==!1&&(S.loading=!N)}N&&b.pop(),p.splice(v,1),v--}else continue}if(g.size>0){const v=new Map,C=new Map,w=T=>{let S=v.get(T);return S||(S=new RegExp(`<\\s*${T}\\b`,"i"),v.set(T,S)),S},M=T=>{let S=C.get(T);return S||(S=new RegExp(`<\\s*\\/\\s*${T}\\s*>`,"i"),C.set(T,S)),S},N=[];for(let T=0;T0){const E=N[N.length-1],I=p[E.index],R=S.type==="html_block"?M(E.tag).exec(x):null;if(R){const F=R.index+R[0].length,O=x.slice(0,F),B=x.slice(F);I.content=`${String(I.content??"")} -${O}`,Array.isArray(I.children)&&I.children.push({type:"html_inline",content:``,raw:``}),N.pop();const j=d(I,B)?[]:u(B,c(p,T,"paragraph"));j.length?p.splice(T,1,...j):(p.splice(T,1),T--);continue}if(S.type!=="inline")continue;const W=Array.isArray(S.children)?S.children:[],z=eme(W,E.tag);if(z!==-1){const F=W.slice(0,z+1),O=W.slice(z+1),B=F.map(j=>String(j?.content??j?.raw??"")).join("");if(I.content=`${String(I.content??"")} -${B}`,Array.isArray(I.children)&&I.children.push(...F),O.length){const j=O.map($=>String($.content??$.raw??"")).join("");if(j.trim()){const $=j.replace(/^\s+/,"");if(d(I,j))p.splice(T,1),T--;else if($.startsWith("<"))p.splice(T,1,{type:"html_block",content:$});else{const V=u(j,c(p,T,"paragraph"));p.splice(T,1,...V)}}else p.splice(T,1),T--}else p.splice(T,1),T--;N.pop();continue}I.content=`${String(I.content??"")} -${x}`,Array.isArray(I.children)&&I.children.push(...W),p.splice(T,1),T--;continue}if(S.type!=="inline")continue;const A=Array.isArray(S.children)?S.children:[];for(const E of g)if((A.length?tme(A,E):w(E).test(x)&&!M(E).test(x)?1:0)>0){N.push({tag:E,index:T});break}}}{let v=0;for(let C=0;C0?v--:(p.splice(C,1),C--))}}for(let v=0;v/]+)/)?.[1]??"").toLowerCase();if(S.startsWith("!")||S.startsWith("?")){C.loading=!1;continue}if(g.has(S)){const z=String(C.content??""),F=gs(z),O=F===-1?null:hL(z,S,F+1);C.loading=O?!1:C.loading!==void 0?C.loading:!0;const B=O?.start??-1,j=O?O.end-O.start:0;if(B!==-1){const $=z.slice(0,B+j);let V="";F!==-1&&F]+)))?/g;let A;for(;(A=x.exec(C.content||""))!==null;)A[1],A[2]||A[3]||A[4];const E=String(C.content??""),I=new RegExp(`<\\/\\s*${S}\\s*>`,"i").exec(E),R=I?I.index:-1,W=I?I[0].length:0;if(R!==-1){const z=E.slice(0,R+W),F=(E.slice(R+W)||"").replace(/^\s+/,"");C.children=[{type:"html_block",content:z,tag:S,loading:!1}],C.content=z,C.raw=z,F&&p.splice(v+1,0,F.startsWith("<")?{type:"html_block",content:F}:{type:"text",content:F,raw:F})}else C.children=[{type:"html_block",content:C.content,tag:S,loading:!0}];continue}if(!C||C.type!=="inline")continue;if(C.children.length===2&&C.children[0].type==="html_inline"){const S=(C.children[0].content?.match(/<([^\s>/]+)/)?.[1]??"").toLowerCase(),x=C.children[1],A=String(x?.content??"").match(/^<\s*\/\s*([^\s>]+)/)?.[1]?.toLowerCase()??"";if(x?.type==="html_inline"&&A===S)continue;m.has(S)?(C.children[0].loading=!0,C.children[0].tag=S,C.children.push({type:"html_inline",tag:S,loading:!0,content:``})):C.children=[{type:"html_block",loading:!0,tag:S,content:String(C.children[0]?.content??"")+String(C.children[1]?.content??"")}];continue}else if(C.children.length===3&&C.children[0].type==="html_inline"&&C.children[2].type==="html_inline"){const S=(C.children[0].content?.match(/<([^\s>/]+)/)?.[1]??"").toLowerCase();if(m.has(S))continue;C.children=[{type:"html_block",loading:!1,tag:S,content:C.children.map(x=>x.content).join("")}];continue}if(!C.content?.startsWith("<")||C.children?.length!==1)continue;const w=String(C.content),M=C,N=M.children[0];if(N?.type!=="html_inline"){/^<\s*(?:\/\s*)?[A-Z][\w:-]*\s*$/i.test(w)&&(M.children.length=0);continue}const T=String(N.content??w).match(X1e)?.[1]?.toLowerCase()??"";if(T){if(/\/\s*>\s*$/.test(w)||OH.has(T)){M.children=[{type:"html_inline",content:w}];continue}M.children.length=0}}})}function fme(e){const t=e.trim();return!t||/^&[a-z0-9#]+;/i.test(t)?!1:!!(/^(?:const|let|var|function|class|import|export|if|for|while|return|await|async|yield|try|catch|throw|new|typeof|instanceof|switch|case|break|continue|def|ruby|perl|print|echo|true|false|null|undefined|NaN|Infinity|this)\b/.test(t)||/[a-z_$][\w$]*(?:\.[a-z_$][\w$]*|\['[^']*'\]|\["[^"]*"\]|\[\d+\])*\s*\(/i.test(t)||/[a-z_$][\w$]*(?:\.[a-z_$][\w$]*|\['[^']*'\]|\["[^"]*"\]|\[[\d+\]])+/i.test(t)||/\w+\s*(?:===?|!==?|<=?|>=?|\+\+|--|&&|\|\||\?\.)/.test(t)||/^(?:!!|\+\+|--)\s*\w/.test(t)||/[\w$]+\s*(?:\+=|-=|\*=|\/=|%=|\*\*=|=)/.test(t)||/^(?:https?:\/\/|ftp:\/\/|file:\/\/|\/\/|www\.)/i.test(t)||/`[^`]*\$\{[^}]*\}[^`]*`/.test(t)||/<\/?[A-Z][a-zA-Z0-9]*/.test(t)||/<[a-z][a-z0-9]*\s[^>]+>/.test(t)||/^(["'`]).*\1\s*[;,]?$/.test(t)||/^\[[\s\S]*\]$/.test(t)||/^\{[\s\S]*\}$/.test(t)||/^\(\s*\)$/.test(t)||/[\w$]+(?:\s*[+\-*/%<>=!&|^~:]+\s*[\w$]+|\s*\.\s*[\w$]+)/.test(t)||/=>|->|::/.test(t)||/^@[\w.$]+$/.test(t)||/^(?:0x[0-9a-fA-F]+|0b[01]+|0o[0-7]+|\d+(?:\.\d*)?(?:px|em|rem|%|vh|vw|deg|s|ms)?)$/.test(t)||/^\$[\w$]+\s*[=:]/.test(t)||/\|\s*\w+|\w+\s*\|/.test(t)||/^(?:git|npm|yarn|pnpm|bun|pip|cargo|go|rust|python|node|java|mvn|gradle|docker|kubectl)\s+/.test(t)||/(?:console|window|document|Math|JSON|Date|Array|Object|String|Number|Boolean)\.[a-zA-Z]/.test(t)||/^(?:\/\/|#|\/\*|\*\/|)/.test(t)||/^(?:<<<|<<\s*['"]?\w+['"]?)/.test(t))}function hme(e,t={}){t.enabled!==!1&&e.core.ruler.after("inline","fix_indented_code_block",n=>{const i=n.tokens??[];for(let o=0;oa.trim().length>0);if(l.length===1&&!fme(l[0]??"")){const a=l[0]??"",u=s.level??0;i.splice(o,1,{type:"paragraph_open",tag:"p",nesting:1,level:u},{type:"inline",tag:"",nesting:0,level:u,content:a,children:[{type:"text",content:a,level:u+1,raw:a}],block:!0},{type:"paragraph_close",tag:"p",nesting:-1,level:u}),o+=2}}})}const $H=/\.([a-z0-9]{1,15})$/i,pme=/[_()[\]{}<>]/u,mme=/^(?:https?:\/\/|ftp:\/\/|mailto:|www\.)/i,gme=/[?#@]/u,vme=/[\\/]/u,yme=/^[\p{L}\p{N}./\\-]+$/u,kme=/^[A-Za-z0-9-]{1,63}$/u,bme=/^xn--[a-z0-9-]{2,59}$/i,wme=/^(?:[A-Z]{1,6}|\d{1,8})$/u,Cme=/^(?=.{1,12}$)[A-Z0-9]+(?:[-.][A-Z0-9]+)*$/iu,Ame=/文件名\s*[::]?|附件\s*[::]?|路径\s*[::]?|路徑\s*[::]?|文件列表\s*[::]?|文档列表\s*[::]?|文檔列表\s*[::]?|\bfile\s*names?\b\s*[::]?|\battachments?\b\s*[::]?|\bpaths?\b\s*[::]?|\bfile\s+lists?\b\s*[::]?|\bdocument\s+lists?\b\s*[::]?/iu,xme=/文件名\s*[::]?|文件\s*[::]?|附件\s*[::]?|档案\s*[::]?|檔案\s*[::]?|文档\s*[::]?|文檔\s*[::]?|资料\s*[::]?|資料\s*[::]?|路径\s*[::]?|路徑\s*[::]?|\bfile\s*name\b\s*[::]?|\battachments?\b\s*[::]?|\bfiles?\b\s*[::]?|\bdocuments?\b\s*[::]?|\bdocs?\b\s*[::]?|\bpaths?\b\s*[::]?/iu,Sme=/股票代码|股票代碼|证券代码|證券代碼|(?:代码|代碼|交易所|后缀|後綴|市场|市場)(?=$|[\s::/|,,、()()])|\btickers?\b|\bsymbols?\b|\bexchanges?\b/iu,_me=2e3,Ime=512,Mme={},Tme=new Set(["ai","md","py","rs","sh","zip"]),BH=new Set(["as","bj","de","hk","l","ln","ny","pa","sh","ss","sz","t","us"]),Eme=new Set([...BH,"at","ax","cn","co","it","jp","ks","mc","mx","nz","pl","sa","si","to","tw"]),Lme=new Set(["com","dev","io","page","site"]),Nme=new Set(["app","apk","dmg","exe","ipa","lock","log","markdown","webmanifest"]),Dme=new Set(["7z","ai","astro","avi","bash","bz2","c","cjs","cpp","cs","csv","doc","docx","fish","flac","gif","go","gz","h","hpp","html","java","jpeg","jpg","js","json","jsx","kt","md","mdx","mjs","mov","mp3","mp4","pdf","php","png","ppt","pptx","ps1","py","rar","rb","rs","sh","sql","svg","swift","svelte","tar","tgz","toml","ts","tsx","txt","vue","wav","webp","xls","xlsx","xml","yaml","yml","zip","zsh"]),Mh=new Map;function mL(e,t){if(!e||e.length>Ime)return t;for(Mh.set(e,t);Mh.size>_me;){const n=Mh.keys().next().value;if(!n)break;Mh.delete(n)}return t}function Av(e){return e?.filename===!0||e?.explicitFilename===!0||e?.marketTicker===!0}function N8(e,t){const n={filename:e?.filename||t?.filename,explicitFilename:e?.explicitFilename||t?.explicitFilename,marketTicker:e?.marketTicker||t?.marketTicker};return Av(n)?n:void 0}function gL(e,t){if(!Av(t))return e;const n=e?.__linkifyDemotionContext;return{...e,__linkifyDemotionContext:{filename:n?.filename||t?.filename,explicitFilename:n?.explicitFilename||t?.explicitFilename,marketTicker:n?.marketTicker||t?.marketTicker}}}function vL(e){const t=o2(e);return Av(t)?t:void 0}function Fme(e){return e.replace(/^[\s>*_`[\]((【《"'“‘]+/u,"").replace(/[\s<*_`\]))】》"'.。;;,,、::!?!?]+$/u,"")}function yL(e,t){if(!Av(t))return;const n=String(e??"").trim().split(/\s+/u).map(Fme).filter(Boolean);if(n.length===0)return;const i={};return t?.filename&&n.every(o=>jk(o,{filename:!0,explicitFilename:t.explicitFilename}))&&(i.filename=!0),t?.explicitFilename&&i.filename&&(i.explicitFilename=!0),t?.marketTicker&&n.every(o=>jk(o,{marketTicker:!0}))&&(i.marketTicker=!0),Av(i)?i:void 0}function Ff(e,t=!1){let n;return{options(i){return t||i==null?gL(e,n):gL(e,N8(vL(i),yL(i,n)))},remember(i){const o=vL(i);n=t?N8(n,o):N8(o,yL(i,n))},reset(){n=void 0}}}function kL(e){return kme.test(e)&&!e.startsWith("-")&&!e.endsWith("-")}function Rme(e){const t=e.split(".");if(t.length<2)return!1;const n=t[t.length-1]?.toLowerCase()??"";return kL(n)||bme.test(n)?t.every(kL):!1}function zH(e){return Array.from(e).some(t=>t.charCodeAt(0)>127)}function Ome(e){return e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split(/[/?#]/,1)[0]??""}function Pme(e){return e.split(".").some(t=>t.toLowerCase().startsWith("xn--"))}function jH(e,t,n){const i=Ome(t);return zH(e)&&Pme(i)&&String(n??"").toLowerCase().includes(i.toLowerCase())}function $me(e){if(!e)return!1;if(e.includes("文件")||e.includes("附件")||e.includes("路径")||e.includes("路徑")||e.includes("文档")||e.includes("文檔")||e.includes("档案")||e.includes("檔案")||e.includes("资料")||e.includes("資料")||e.includes("股票")||e.includes("证券")||e.includes("證券")||e.includes("代码")||e.includes("代碼")||e.includes("交易所")||e.includes("后缀")||e.includes("後綴")||e.includes("市场")||e.includes("市場"))return!0;const t=e.toLowerCase();return t.includes("file")||t.includes("attachment")||t.includes("document")||t.includes("doc")||t.includes("path")||t.includes("ticker")||t.includes("symbol")||t.includes("exchange")}function o2(e){const t=String(e??""),n=Mh.get(t);return n?(Mh.delete(t),Mh.set(t,n),n):$me(t)?mL(t,{explicitFilename:Ame.test(t),filename:xme.test(t),marketTicker:Sme.test(t)}):mL(t,Mme)}function Bme(e){return Rme(e.split(/[\\/]/)[0]??"")}function zme(e){const t=e.replace(/[^a-z]/gi,"");return t.length>=2&&t===t.toUpperCase()}function jme(e){if(pme.test(e)||!yme.test(e))return!0;if(vme.test(e))return!Bme(e);const t=e.replace($H,"");return zH(t)?!0:t.split(".").filter(Boolean).some(zme)}function Hme(e,t,n){if(!(n?Eme:BH).has(t))return!1;const i=e.slice(0,-(t.length+1));return i===""?e.startsWith("."):(n?Cme:wme).test(i)}function jk(e,t={}){if(!e||mme.test(e)||gme.test(e))return!1;const n=e.match($H);if(!n)return!1;const i=String(n[1]??"").toLowerCase();return Hme(e,i,t.marketTicker===!0)?!0:Dme.has(i)?!Tme.has(i)||t.filename?!0:jme(e):!!(t.explicitFilename&&Lme.has(i)||t.filename&&Nme.has(i))}const HH=new WeakMap,WH=new WeakSet;function eA(e,t){return HH.set(e,t),e}function Wme(e){return HH.get(e)}function qme(e){WH.add(e)}function Ume(e){return e===void 0||WH.has(e)}const bL=["!"];function wL(e){return e==="linkify"||e==="autolink"?e:"recovery"}function Nl(e){return{type:"text",content:e,raw:e}}function nh(e,t){t===1?e.push({type:"em_open",tag:"em",nesting:1}):t===2?e.push({type:"strong_open",tag:"strong",nesting:1}):t===3&&(e.push({type:"strong_open",tag:"strong",nesting:1}),e.push({type:"em_open",tag:"em",nesting:1}))}function ih(e,t){t===1?e.push({type:"em_close",tag:"em",nesting:-1}):t===2?e.push({type:"strong_close",tag:"strong",nesting:-1}):t===3&&(e.push({type:"em_close",tag:"em",nesting:-1}),e.push({type:"strong_close",tag:"strong",nesting:-1}))}function wd(e,t,n,i="recovery"){let o="";if(t.includes('"')){const s=t.split('"');t=s[0].trim(),o=s[1].trim()}return eA({type:"link",loading:n,href:t,title:o,text:e,children:[{type:"text",content:e,raw:e}],raw:`[${e}](${t})`},i)}function Vme(e,t){if(!(!e||!t)&&(e.href=String(e.href??"")+t,e.text=String(e.text??"")+t,e.raw=`[${e.text}](${e.href})`,Array.isArray(e.children)&&e.children.length)){const n=e.children[e.children.length-1];n?.type==="text"?(n.content=String(n.content??"")+t,n.raw=String(n.raw??"")+t):e.children.push(Nl(t))}}function CL(e,t){let n=-1;for(const i of t){const o=e.indexOf(i);o!==-1&&(n===-1||on?.[0]==="href")?.[1];return typeof t=="string"?t:""}function Zme(e,t){if(!e)return;e.attrs=Array.isArray(e.attrs)?e.attrs:[];const n=e.attrs.findIndex(i=>i?.[0]==="href");n>=0?e.attrs[n][1]=t:e.attrs.push(["href",t])}function AL(e,t,n){let i="";for(let o=t+1;o{const n=t.tokens??[];for(let i=0;ir.type==="code_inline"),i=new Map;let o=0;for(let r=0;r0&&u?xL(u):-1;if(c!==-1&&u)for(const d of u.slice(c))d==="("?o++:d===")"&&o>0&&o--}a!==-1&&(r=a);continue}if(!(l.type!=="text"||typeof l.content!="string"))for(const a of l.content)a==="("?o++:a===")"&&o>0&&o--}const s=o2(t);for(let r=0;r<=e.length-1;r++){r<0&&(r=0);const l=e[r];if(!l)break;if(l.type==="link_open"&&(l.markup==="linkify"||l.markup==="autolink")){let a=-1;for(let u=r+1;u0){const m=xL(u);m!==-1&&(d===-1||m=g.content.length){p-=g.content.length;continue}if(p<0)break;const y=g.content[p],b=g.content.slice(0,p);let v=g.content.slice(p);for(let M=m+1;M0&&(e.splice(m+1,C),a=m+1);let w=c;if(y==="!"&&h!==-1)w=c.slice(0,h);else if(v){const M=encodeURI(v);if(M&&c.endsWith(M))w=c.slice(0,c.length-M.length);else{const N=y?encodeURI(y):"",T=N?c.indexOf(N):-1;T!==-1&&(w=c.slice(0,T))}}w!==c&&Zme(l,w),v&&e.splice(a+1,0,Nl(v));break}}}if(!n){if(l?.type==="em_open"&&e[r-1]?.type==="text"&&e[r-1].content?.endsWith("*")){const a=e[r-1].content?.replace(/(\*+)$/,"")||"";e[r-1].content=a,l.type="strong_open",l.tag="strong",l.markup="**";for(let u=r+1;ud[0]==="href")?.[1]||"";if(e[r+3]?.type==="text"){const d=(e[r+3]?.content??"").indexOf(")"),h=d===-1;d===-1&&(c+=e[r+3]?.content?.slice(0,d)||"",e[r+3].content=""),a.push(wd(u,c,h,"linkify"));const p=e[r+3].content?.replace(/^\)\**/,"");p&&a.push(Nl(p)),e.splice(r-4,8,...a)}else a.push(eA({type:"link",loading:!0,href:c,title:"",text:u,children:[{type:"text",content:c,raw:c}],raw:`[${u}](${c})`},"linkify")),e.splice(r-4,7,...a);continue}else if(e[r-1].content==="]("&&e[r-3]?.type==="text"&&e[r-3].content?.endsWith(")"))if(e[r-2]?.type==="strong_open"){const[a,u]=e[r-3].content?.split("[**")||[];e[r+1].content=u||"",e[r-3].content=a||"",e[r-1].content=""}else if(e[r-2]?.type==="em_open"){const[a,u]=e[r-3].content?.split("[*")||[];e[r+1].content=u||"",e[r-3].content=a||"",e[r-1].content=""}else{const[a,u]=e[r-3].content?.split("[")||[];e[r+1].content=u||"",e[r-3].content=a||"",e[r-1].content=""}}if(l.type==="link_close"&&l.nesting===-1&&e[r-2]?.type==="link_open"&&e[r+1]?.type==="text"&&e[r-1]?.type==="text"){const a=e[r-1].content||"",u=e[r-2].attrs||[],c=u.find(b=>b[0]==="href")?.[1]||"",d=u.find(b=>b[0]==="title")?.[1]||"";let h=3,p=2;const m=(e[r-3]?.content||"").match(/^(\*+)$/),g=[];if(m){p+=1;const b=m[1].length;nh(g,b)}if(l.markup!=="linkify"&&e[r+1].type==="text"&&e[r+1]?.content?.startsWith("](")){h+=1;for(let b=r+1;by[0]==="href")?.[1];e[r+5]?.type==="text"&&e[r+5].content==="."?(h=(g||h)+e[r+5].content,e[r+5].content=""):h=g||h,p+=3}let m=!0;if(l.nesting===-1&&(d=d.replace(/\*+$/,"")),e[r+2]?.type==="text"){const g=(e[r+2]?.content??"").indexOf(")");m=g===-1,g===-1&&(h+=e[r+2]?.content?.slice(0,g)||"",e[r+2].content="")}a.push(wd(d,h,m)),ih(a,2),e.splice(r-2,p,...a)}if(l.type==="text"&&/\*+\[[^\]]*$/.test(l.content||"")&&e[r+1]?.type==="strong_open"&&e[r+2]?.type==="text"&&e[r+2].content==="]("&&e[r+3]?.type==="link_open"&&e[r+5]?.type==="link_close"&&e[r+6]?.type==="text"&&e[r+6].content===")"&&e[r+7]?.type==="strong_close"){const a=(l.content||"").match(/^(\*+)\[(.*)$/);if(a){const u=(a[2]||"")+a[1];let c=e[r+3]?.attrs?.find(h=>h[0]==="href")?.[1]||"";!c&&e[r+4]?.type==="text"&&(c=e[r+4].content||"");const d=[];nh(d,2),d.push(wd(u,c,!1)),ih(d,2),e.splice(r,9,...d),r-=d.length-1;continue}}}}if(n)return e;for(let r=0;r{const n=t.tokens??[];for(let i=0;i{const n=t.tokens??[];for(let i=0;i=0&&e[m].type==="text"&&e[m].content==="";)m--;const g=e[m];let y=c+1;for(;y=0&&e[m].type==="text"&&e[m].content==="";)m--;const g=e[m];let y=c+1;for(;y{const n=t;try{const i=uge(n.tokens??[],!!n.env?.__markstreamFinal,n.src??"");Array.isArray(i)&&(n.tokens=i)}catch(i){console.error("[applyFixTableTokens] failed to fix table tokens",i)}})}function SL(){return[{type:"table_open",tag:"table",attrs:null,map:null,children:null,content:"",markup:"",info:"",level:0,loading:!0,meta:null},{type:"thead_open",tag:"thead",attrs:null,block:!0,level:1,children:null},{type:"tr_open",tag:"tr",attrs:null,block:!0,level:2,children:null}]}function _L(){return[{type:"tr_close",tag:"tr",attrs:null,block:!0,level:2,children:null},{type:"thead_close",tag:"thead",attrs:null,block:!0,level:1,children:null},{type:"table_close",tag:"table",attrs:null,map:null,children:null,content:"",markup:"",info:"",level:0,meta:null}]}function IL(e){return[{type:"th_open",tag:"th",attrs:null,block:!0,level:3,children:null},{type:"inline",tag:"",children:null,content:e,level:4,attrs:null,block:!0},{type:"th_close",tag:"th",attrs:null,block:!0,level:3,children:null}]}function qH(e,t){if(!e.startsWith("|")||e.includes(` -`)||!e.endsWith("|"))return null;const n=e.slice(1).split("|");return n.at(-1)===""&&n.pop(),n.length>0&&n.every(i=>i.trim().length>0)?n:null}function D8(e){return qH(e)!==null}function UH(e){return/^:?-+:?$/.test(e.trim())}function oge(e){if(!e.startsWith("|"))return!1;const t=e.slice(1).split("|");return t.at(-1)===""&&t.pop(),t.length>0&&t.every(UH)}function sge(e){return/^(?:[::]-*|:?-+:?)?$/.test(e.trim())}function rge(e){if(e==="")return!0;if(!e.startsWith("|"))return!1;const t=e.slice(1).split("|"),n=t.at(-1)??"";return t.slice(0,-1).every(UH)&&sge(n)}function lge(e){return e==="|"||e==="|:"}function age(e){const t=qH(e);return t!==null&&t.every(n=>!n.includes(":"))}function uge(e,t=!1,n=""){const i=[...e];if(e.length<3)return i;const o=e.length-2,s=e[o];if(s.type==="inline"){const r=String(s.content??""),l=r.split(` -`)[0]??"",[a="",u="",...c]=r.split(` -`),d=!t&&!r.includes(` -`)&&/\r?\n$/.test(n)&&D8(r);if(!t&&(r.includes(` -`)&&c.length===0&&D8(a)&&rge(u)||d)){const h=l.slice(1,-1).split("|").map(m=>m.trim()).flatMap(m=>IL(m)),p=[...SL(),...h,..._L()];i.splice(o-1,3,...p)}else if(r.includes(` -`)&&c.length===0&&D8(a)&&oge(u)){const h=l.slice(1,-1).split("|").map(m=>m.trim()).flatMap(m=>IL(m)),p=[...SL(),...h,..._L()];i.splice(o-1,3,...p)}else r.includes(` -`)&&c.length===0&&age(a)&&lge(u)&&(s.content=r.slice(0,-2),s.children.splice(2,1))}return i}function cge(e,t,n,i){const o=e.length;if(n==="$$"&&i==="$$"){let u=t;for(;u=0&&e[c]==="\\";)d++,c--;if(d%2===0)return u}u++}return-1}const s=n[n.length-1],r=i;let l=0,a=t;for(;a=0&&e[c]==="\\";)d++,c--;if(d%2===0){if(l===0)return a;l--,a+=r.length;continue}}const u=e[a];if(u==="\\"){a+=2;continue}u===s?l++:u===r[r.length-1]&&l>0&&l--,a++}return-1}var dge=cge;const fge=["boldsymbol","mathbb","mathcal","mathfrak","mathrm","mathit","mathsf","vec","hat","bar","tilde","overline","underline","mathscr","mathnormal","operatorname","mathbf*"],Hk=fge.map(e=>e.replace(/[.*+?^${}()|[\\]"\]/g,"\\$&")).join("|"),hge=/\\[a-z]+/i,VH="(?:\\\\|\\u0008)",pge=new RegExp(String.raw`${VH}(?:${Hk})\s*\{[^}]+\}`,"i"),mge=new RegExp(String.raw`(?:${VH})?(?:${Hk})\s*\{`,"i"),gge=/\\(?:text|frac|left|right|times)/,vge=/(?:^|[^+])\+(?!\+)|[=\-*/^<>]|\\times|\\pm|\\cdot|\\le|\\ge|\\neq/,yge=/\b[A-Z]{2,}-[A-Z]{2,}\b/i,kge=/[A-Z]+\s*\([^)]+\)/i,bge=/^\(\s*[a-z](?:\s*,\s*[a-z])+\s*\)$/i,wge=/\b(?:sin|cos|tan|log|ln|exp|sqrt|frac|sum|lim|int|prod)\b/,Cge=/\b\d{4}\/\d{1,2}\/\d{1,2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?\b/,Age={"\b":"\\b","\v":"\\v","\f":"\\f"};function xge(e){let t="";for(const n of e)t+=Age[n]??n;return t}function zd(e){if(!e)return!1;const t=xge(e),n=t.trim();if(Cge.test(n)||n.includes("**"))return!1;if(n.length>2e3)return!0;const i=hge.test(t),o=pge.test(t),s=mge.test(t),r=gge.test(t),l=/(?:^|[^\w\\])(?:[A-Z]|\\[A-Z]+)_(?:\{[^}]+\}|[A-Z0-9\\])/i.test(t)||/(?:^|[^\w\\])(?:[A-Z]|\\[A-Z]+)\^(?:\{[^}]+\}|[A-Z0-9\\])/i.test(t),a=vge.test(t)&&!yge.test(t),u=kge.test(t),c=bge.test(n),d=wge.test(t),h=/^\([a-z]\)$/i.test(n)||/^(?:[a-z]|pi)$/i.test(n),p=/^(?:[A-Z][a-z]?(?:_\{?\d+\}?|\^\{?\d+\}?)?)+$/.test(n);return i||o||s||r||l||a||u||c||d||h||p}const KH="__markstreamMathPluginApplied",tA=80,ZH=2e4,ML=ZH+4096;function nx(e){return!!e[KH]}function Sge(e){e[KH]=!0}const GH=["ldots","cdots","quad","in","displaystyle","int_","lim","lim_","ce","pu","end","infty","perp","mid","operatorname","to","rightarrow","leftarrow","math","mathrm","mathit","mathbb","mathcal","mathfrak","implies","alpha","beta","gamma","delta","epsilon","lambda","sum","sum_","prod","sqrt","fbox","boxed","color","rule","edef","fcolorbox","hline","hdashline","cdot","times","pm","le","ge","neq","sin","cos","tan","log","ln","exp","frac","text","left","right"],_ge=["cdot","mathbf{","partial","mu_{"],QH=GH.slice().sort((e,t)=>t.length-e.length).map(e=>e.replace(/[.*+?^${}()|[\\]\\\]/g,"\\$&")).join("|"),YH="[ \r\b\f\v]",Ige=new RegExp(`([^\\\\])(${_ge.map(e=>e).join("|")})+`,"g"),Mge=/span\{([^}]+)\}/,Tge=/\\operatorname\{span\}\{((?:[^{}]|\{[^}]*\})+)\}/,Ege=/(^|[^\\])\\\r?\n/g,Lge=/(^|[^\\])\\$/g,Nge=/[\p{L}\p{M}\p{N}\p{Pe}\p{Pf}'′″‴|‖]/u,Dge=new RegExp(`(${YH})|(${QH})\\b`,"g"),TL=new Map,EL=new Map;function Fge(e){if(!e)return Dge;const t=[...e];t.sort((r,l)=>l.length-r.length);const n=t.join(""),i=TL.get(n);if(i)return i;const o=`(?:${t.map(r=>r.replace(/[.*+?^${}()|[\\]\\"\]/g,"\\$&")).join("|")})`,s=new RegExp(`(${YH})|(${o})\\b`,"g");return TL.set(n,s),s}function Rge(e,t){const n=e?[]:[...t??[]];e||n.sort((l,a)=>a.length-l.length);const i=e?"__default__":n.join(""),o=EL.get(i);if(o)return o;const s=e?[Hk,QH].filter(Boolean).join("|"):[n.map(l=>l.replace(/[.*+?^${}()|[\\]\\\]/g,"\\$&")).join("|"),Hk].filter(Boolean).join("|"),r=new RegExp(`(^|[^\\\\\\w])(${s})\\s*\\{`,"g");return EL.set(i,r),r}const LL={" ":"t","\r":"r","\b":"b","\f":"f","\v":"v"};function NL(e){const t=/(^|[^\\])(__|\*\*)/g;let n=0;for(;t.exec(e)!==null;)n++;return n}function Oge(e){return e.replace(/(^|[^\\])!+/gu,(t,n)=>{if(n&&Nge.test(n))return t;const i=n?t.slice(n.length):t;return`${n}${"\\!".repeat(i.length)}`})}function DL(e){const t=/(^|[^\\])(__|\*\*)/g;let n,i=null;for(;(n=t.exec(e))!==null;)i={marker:n[2],index:n.index+(n[1]?.length??0)};return i}function Cd(e,t){const n=t?.commands??GH,i=t?.escapeExclamation??!0,o=t?.commands==null,s=Fge(o?void 0:n);let r=e.replace(s,(u,c,d,h,p)=>{if(c!==void 0&&LL[c]!==void 0)return`\\${LL[c]}`;if(d&&n.includes(d)){const m=p&&typeof h=="number"?p[h-1]:void 0;return m==="\\"||m&&/\w/.test(m)?u:`\\${d}`}return u});i&&(r=Oge(r));let l=r;const a=Rge(o,o?void 0:n);return l=l.replace(a,(u,c,d)=>`${c}\\${d}{`),l=l.replace(Mge,"span\\{$1\\}").replace(Tge,"\\operatorname{span}\\{$1\\}"),l=l.replace(Ege,`$1\\\\ -`),l=l.replace(Lge,"$1\\\\"),l=l.replace(Ige,"$1\\$2"),l}function FL(e){const t=e.trim();return!(!zd(t)||/"[^"\n]{1,80}"\s*:\s*/.test(t)||!(/\\[a-z]+/i.test(t)||/[=+*/^<>]|\\times|\\pm|\\cdot|\\le|\\ge|\\neq/.test(t)||/[_^]/.test(t))&&/\s-\s/.test(t))}function JH(e){const t=[];let n=0;for(;n=n[0]&&t0;){if(e[s]==="\\"&&s+10;){if(e[l]==="\\"&&l+1=0&&e[n]==="\\";)i++,n--;return i%2===1}function nA(e,t){let n=t;for(;n0&&e[i-1]==="$"||i+1=l)break;const u=Wk(o,a);if(u){r=Math.max(a+Math.max(1,t.length),u[1]);continue}s2(e,a)||s++,r=a+Math.max(1,t.length)}return s}function ix(e,t,n){const i=Sv(String(e??""));if(!i.endsWith(t))return-1;const o=i.length-t.length;if(o<=0||!Sv(i.slice(0,o)).trim()||s2(i,o))return-1;const s=JH(i);if(Wk(s,o))return-1;const r=RL(i,t,0,o,s);if(t==="$$"){if(r%2===1)return-1}else if(r>RL(i,n,0,o,s))return-1;return o}function xv(e){return e===" "||e===" "}function Sv(e){let t=e.length;for(;t>0&&xv(e[t-1]);)t--;return e.slice(0,t)}function OL(e){let t=0;for(let n=0;n=48&&t<=57}function $ge(e){if(e.length<3)return!1;const t=e[0];if(t!=="-"&&t!=="*"&&t!=="_"&&t!=="=")return!1;let n=0;for(let i=0;i=3}function Bge(e){const t=e.trim();if(!t)return!1;let n=0;t[n]===":"&&n++;let i=0;for(;t[n]==="-";)i++,n++;return i<3?!1:(t[n]===":"&&n++,n===t.length)}function zge(e){if(!e.includes("|"))return!1;const t=e[0]==="|"?e.slice(1):e;return(t.endsWith("|")?t.slice(0,-1):t).split("|").every(Bge)}function jge(e){let t=0;if(!PL(e[t]))return!1;for(;PL(e[t]);)t++;return e[t]!=="."&&e[t]!==")"?!1:xv(e[t+1])}function XH(e){const t=e.trimStart();if(!t||t.startsWith("```")||t.startsWith("~~~")||t.startsWith(":::")||t[0]===">"||t[0]==="<")return!0;if(t[0]==="#"){let n=0;for(;t[n]==="#";)n++;if(n>=1&&n<=6&&xv(t[n]))return!0}return!!((t[0]==="-"||t[0]==="+"||t[0]==="*")&&xv(t[1])||jge(t)||$ge(t)||zge(t))}function $L(e,t){return e?t?`${e} -${t}`:e:t}function iA(e){const t=String(e??"").trim();return t?zd(t):!1}function BL(e){let t=0;for(let n=0;ntA){p=!0;break}const g=o[m],y=d1(g,c);if(y!==-1){const b=$L(h,g.slice(0,y));if(!iA(b)){p=!0;break}const v=g.slice(y+c.length),C=v.trim()?`suffix:${BL(v)}`:"nosuffix";return["closed",u,i+l,d,i+m,y,BL(b),C].join(":")}if(XH(g)){p=!0;break}if(h=$L(h,g),h.length>ZH){p=!0;break}}if(!p&&iA(h))return["pending",u,i+l,d].join(":")}}return null}function R8(e,t){const n=String(e??"").trim();return!n||!/^\d[\d,.]*\s*[~~-]\s*$/.test(n)?!1:/\d/.test(String(t??""))}function Wge(e){const t=String(e??"").trimStart(),n=t.match(/^\d+(?:,\d{3})*(?:\.\d+)?/);if(!n)return!1;const i=t.slice(n[0].length);return/^\s*(?:[+\-*/^_=<>]|\\[a-z]+)/i.test(i)?!1:i===""||/^[)\s,.!?;:]/.test(i)}function O8(e){const t=String(e??"").trim();return t?/^(?:\.{3,}|…+)$/.test(t):!1}function qge(e,t){Sge(e);const n=(r,l,a)=>{const u=String(l??"").replace(/^[\t ]+/,"").replace(/[\t ]+$/,"");if(!u)return;const c=r.push("paragraph_open","p",1);c.map=[a,a+1];const d=r.push("inline","",0);d.content=u,d.map=[a,a+1],d.children=[],r.push("paragraph_close","p",-1)},i=(r,l)=>{const a=r,u=!!t?.strictDelimiters,c=!a?.env?.__markstreamFinal,d=(v,C)=>{let w=C;for(;w=3&&(!w||/\s/.test(w))){const M=a.push("text","",0);return M.content=a.src.slice(a.pos,v),a.pos=v,!0}}const h=[["$$","$$"],["$","$"],["\\(","\\)"]],p=String(a.pending??""),m=Math.max(0,a.pos-p.length);let g=m,y=m;const b=m;for(const[v,C]of h){const w=a.src,M=JH(w),N=Pge(w,c);let T=!1;v==="$$"&&g!==b&&(g=b);let S=-1,x=-1,A=0;const E=I=>{if((I==="undefined"||I==null)&&(I=""),I==="\\"){a.pos=a.pos+I.length,g=a.pos;return}if(I==="\\)"||I==="\\("){const z=a.push("text_special","",0);z.content=I==="\\)"?")":"(",z.markup=I,a.pos=a.pos+I.length,g=a.pos;return}if(!I)return;if(v==="$$"&&I.includes("$")){let z=0;for(;z0&&I[F-1]==="$"||F+10){const O=I.slice(0,R),B=a.push("text","",0);B.content=O,a.pos=a.pos+O.length,g=a.pos}const z=I.slice(R).match(/^!\[([^\]]*)\]\(([^)]+)\)/);if(z){const[,O,B]=z,j=B.match(/^(\S+)(?:\s+"([^"]+)")?\s*$/),$=j?j[1]:B,V=j&&j[2]?j[2]:null,ne=a.push("image","img",0);ne.attrs=[["src",$],["alt",O]],V&&ne.attrs.push(["title",V]),ne.content=O,ne.children=[{type:"text",content:O,tag:""}],a.pos=a.pos+z[0].length,g=a.pos;const K=I.slice(R+z[0].length);K&&E(K);return}const F=a.push("text","",0);F.content=I,a.pos=a.pos+I.length,g=a.pos;return}const W=a.push("text","",0);W.content=I,a.pos=a.pos+I.length,g=a.pos};for(;!(g>=w.length);){const I=w.indexOf(v,g);if(I===-1)break;if(s2(w,I)){g=I+Math.max(1,v.length);continue}const R=Wk(M,I);if(R){g=R[1];continue}const W=Wk(N,I);if(W){g=W[1];continue}if(I===S&&g===x){if(A++,A>2){g=I+Math.max(1,v.length);continue}}else A=0,S=I,x=g;if(v==="("&&I>0){let K=I-1;for(;K>=0&&w[K]===" ";)K--;if(K>=0&&w[K]==="]"){g=I+v.length;continue}}if(v==="$"&&I>0&&w[I-1]==="$"){g=I+1;continue}if(v==="$"&&I=w.length);){const R=nA(w,I);if(R===-1)break;if(R+10&&w[R-1]==="$"){I=R+1;continue}const W=F8(w,R+1);if(W===-1)break;const z=w.slice(R+1,W),F=z.includes("`"),O=!z||!z.trim(),B=w[W+1],j=R8(z,B),$=O8(z);if(!F&&!O&&!j&&!$){const V=w.slice(g,R);V&&E(V);const ne=a.push("math_inline","math",0);ne.content=Cd(z,t),ne.markup="$",ne.raw=`$${z}$`,ne.loading=!1,g=W+1,I=W+1}else E("$"),I=R+1}I{const c=r,d=!c?.env?.__markstreamFinal,h=t?.strictDelimiters,p=h?[["\\[","\\]"],["$$","$$"]]:[["\\[","\\]"],["[","]"],["$$","$$"]],m=c.bMarks[l]+c.tShift[l];let g=c.src.slice(m,c.eMarks[l]).trim(),y=!1,b="",v="",C=!1,w="",M=!1;for(const[V,ne]of p)if(g.startsWith(V))if(V.includes("[")){const K=V==="\\["?g.slice(V.length):"";if(V==="\\["&&d1(K,ne)===-1&&!/^\s*!\[/.test(K)&&!K.includes("`")&&zd(K)){y=!0,b=V,v=ne;break}if(t?.strictDelimiters){if(g.replace("\\","")==="["){if(l+1=0?"\\]":v,A=S>=0?S:d1(g,v,T);if(!C&&A>b.length){const V=g.slice(N+b.length,A),ne=c.push("math_block","math",0);ne.content=Cd(V),ne.markup=b==="$$"?"$$":b==="["?"[]":"\\[\\]",ne.map=[l,l+1],ne.raw=`${b}${V}${x}`,ne.block=!0,ne.loading=!1,c.line=l+1;const K=g.slice(A+x.length);return K.trim()&&n(c,K,l),!0}let E=l,I="",R=!1,W="",z=l;const F=C?g:g===b?"":g.slice(b.length),O=!h&&b==="\\["?"]":"",B=d1(F,v);if(B!==-1){const V=B;I=F.slice(0,V),W=F.slice(V+v.length),z=C?l+1:l,R=!0,E=z}else for(F&&!C&&(I=F),E=l+1;E{const c=r,d=c.bMarks[l]+c.tShift[l],h=c.src.slice(d,c.eMarks[l]).trim();return!h.startsWith("$$")&&!h.startsWith("\\[")?!1:o(r,l,a,u)};e.inline.ruler.before("escape","math",i),e.block.ruler.before("lheading","explicit_math_block",s,{alt:["paragraph","reference","blockquote","list"]}),e.block.ruler.before("paragraph","math_block",o,{alt:["paragraph","reference","blockquote","list"]})}function Uge(e){const t=e.renderer.rules.image||function(n,i,o,s,r){const l=n,a=r;return a.renderToken?a.renderToken(l,i,o):""};e.renderer.rules.image=(n,i,o,s,r)=>{const l=n;return l[i].attrSet?.("loading","lazy"),t(l,i,o,s,r)},e.renderer.rules.fence=e.renderer.rules.fence||((n,i)=>{const o=n[i],s=String(o.info??"").trim();return`
    ${e.utils.escapeHtml(String(o.content??""))}
    `})}const Vge=/^\s]/i,Kge=/^<\/a\s*>/i;function Zge(e,t){if(e?.type!=="inline")return!1;const n=e.children;if(!Array.isArray(n)||n.length===0)return t.test(String(e.content??""));let i=0;for(let o=n.length-1;o>=0;o--){const s=n[o];if(s?.type==="link_close"){for(o--;o>=0&&n[o]?.level!==s.level&&n[o]?.type!=="link_open";)o--;continue}if(s?.type==="html_inline"){const r=String(s.content??"");Vge.test(r)&&i>0&&i--,Kge.test(r)&&i++}if(!(i>0)&&s?.type==="text"&&t.test(String(s.content??"")))return!0}return!1}function Gge(e){const t=e.core?.ruler,n=t.getNamedRules?.().find(i=>i.name==="linkify")?.fn;typeof n=="function"&&t.at("linkify",i=>{if(!i.md?.options?.linkify)return;const o=Array.isArray(i.tokens)?i.tokens:[],s=i.md.linkify;if(!s)return;const r=o.filter(l=>Zge(l,s));if(r.length)return n(Object.assign(Object.create(Object.getPrototypeOf(i)),i,{tokens:r}))})}function Qge(e){const t=e.inline.ruler,n=t.getNamedRules?.(),i=n?.find(l=>l.name==="link")?.fn,o=n?.find(l=>l.name==="image")?.fn;if(typeof i!="function"||typeof o!="function")return;const s=e.validateLink,r=e;r.__markstreamOriginalValidateLink=s,t.at("link",(...l)=>{const a=l[0].md,u=a?.validateLink===s?a.options?.validateLink:a?.validateLink;if(!a||typeof u!="function")return i(...l);const c=a.validateLink;a.validateLink=u;try{return i(...l)}finally{a.validateLink=c}}),t.at("image",(...l)=>{const a=l[0].md;if(!a)return o(...l);const u=a.validateLink;a.validateLink=s;try{return o(...l)}finally{a.validateLink=u}})}function Yge(e={}){const t=e.markdownItOptions??{},n=typeof t.experimental=="object"&&t.experimental!==null?t.experimental:{},i=Object.prototype.hasOwnProperty.call(t,"stream")?!!t.stream:!0,o=Object.prototype.hasOwnProperty.call(t,"validateLink"),s=new x1e({html:!0,linkify:!0,typographer:!0,...t,experimental:{stream:i,...n}});if(!o){const r=l=>!Wh(l,{tagName:"a",attrName:"href"});qme(r),s.set({validateLink:r})}return Qge(s),Gge(s),(e.enableMath??!0)&&qge(s,{...e.mathOptions??{}}),(e.enableContainers??!0)&&q1e(s),e.enableFixIndentedCodeBlock!==!1&&hme(s),Gme(s),Xme(s),Yme(s),ige(s),Uge(s),dme(s,{customHtmlTags:e.customHtmlTags}),s}function qh(e){const t=Object.assign(Object.create(Object.getPrototypeOf(e)),e);return Array.isArray(e.attrs)&&(t.attrs=e.attrs.map(n=>[...n])),Array.isArray(e.map)&&(t.map=[...e.map]),Array.isArray(e.children)&&(t.children=e.children.map(n=>qh(n))),t}function Jge(e){const t=e.meta??{};return{type:"checkbox",checked:t.checked===!0,raw:t.checked?"[x]":"[ ]"}}function Xge(e){const t=e,n=t.attrGet?t.attrGet("checked"):void 0,i=n===""||n==="true";return{type:"checkbox_input",checked:i,raw:i?"[x]":"[ ]"}}function e0e(e){const t=String(e.content??"");return{type:"emoji",name:t,markup:String(e.markup??""),raw:`:${t}:`}}function py(e,t,n){const i=[];let o="",s=t+1;const r=[];for(;sn.startsWith(t)||t.startsWith(n)):!1}function zL(e,t,n,i){n.length>0&&e.push(...n),i.length>0&&t.push(...i),n.length=0,i.length=0}function jL(e,t){return!t&&e.startsWith(" ")&&!e.startsWith(" ")?` ${e}`:e}function o0e(e,t){const n=[],i=[],o=[],s=[],r=e.split(n0e),l=/\r?\n$/.test(e),a=r.some(p=>p.startsWith("diff ")||p.startsWith("--- ")||p.startsWith("+++ ")||p.startsWith("@@ ")),u=p=>{const m=p;if(!nW.some(g=>m.startsWith(g)))if(m.startsWith("-")){const g=m.slice(1);o.push(jL(g,a))}else if(m.startsWith("+")){const g=m.slice(1);s.push(jL(g,a))}else{zL(n,i,o,s);const g=a&&m.startsWith(" ")?m.slice(1):m;n.push(g),i.push(g)}},c=l?Math.max(0,r.length-1):r.length;for(let p=0;p0||s.length>0)&&zL(n,i,o,s);const d=n.join(` -`),h=i.join(` -`);return{original:t&&l&&d?`${d} -`:d,updated:t&&l&&h?`${h} -`:h}}function ox(e){const t=Array.isArray(e.map)&&e.map.length===2,n=e.meta??{},i=typeof n.closed=="boolean"?n.closed:void 0,o=i===!0||i!==!1&&t,s=String(e.info??""),r=s.startsWith("diff"),l=r?(()=>{const u=s,c=u.indexOf(" ");return c===-1?"":String(u.slice(c+1)??"")})():s;let a=String(e.content??"");if(!o&&e.markup){const u=e.markup[0],c=e.markup.length,d=t0e(u,c);d.test(a)&&(a=a.replace(d,""))}if(r){const{original:u,updated:c}=o0e(a,o===!0);return{type:"code_block",language:l,code:String(c??""),raw:String(a??""),diff:r,loading:i===!0?!1:i===!1?!0:!t,originalCode:u,updatedCode:c}}return{type:"code_block",language:l,code:String(a??""),raw:String(a??""),diff:r,loading:i===!0?!1:i===!1?!0:!t}}function s0e(e){const t=e.meta??{};return{type:"footnote_reference",id:String(t.label??""),raw:`[^${String(t.label??"")}]`}}function r0e(){return{type:"hardbreak",raw:`\\ -`}}function l0e(e,t,n){const i=[];let o="",s=t+1;const r=[];for(;s\s*$/.test(t)||mf.has(e)}function a0e(e){if(!e||e.length===0)return HL();const t=$8.get(e);if(t)return t;const n=e.map(Ga).filter(Boolean);if(!n.length){const o=HL();return $8.set(e,o),o}const i={customTagSet:new Set(n),allowedTagSet:_4({customHtmlTags:e})};return $8.set(e,i),i}function rW(e){const t=e,n=t.raw??t.content??t.markup??"";return String(n??"")}function u0e(e){const t=e.meta,n=t?.markstreamCustomHtmlRaw,i=t?.markstreamCustomHtmlInner;return typeof n=="string"&&typeof i=="string"?{raw:n,inner:i}:null}function qk(e,t){const n=t.toLowerCase();for(let i=e.length-1;i>=0;i--){const[o,s]=e[i];if(String(o).toLowerCase()===n)return s}}function c0e(e,t,n){const i=e.slice();return qk(i,"href")||i.push(["href",t]),n!=null&&!qk(i,"title")&&i.push(["title",n]),i}function oA(e){return e.map(rW).join("")}function y9(e){const t=[],n=i=>{const o=String(i??"");if(!o)return;const s=t[t.length-1];if(s?.type==="text"){s.content=`${s.content}${o}`,s.raw=`${s.raw}${o}`;return}t.push({type:"text",content:o,raw:o})};for(const i of e)if(i){if(i.type==="reference"||i.type==="footnote_reference"){n(String(i.raw??""));continue}if("children"in i&&Array.isArray(i.children)){t.push({...i,children:y9(i.children)});continue}t.push(i)}return t}function d0e(e,t,n){let i=0;for(let o=t;o`;g.toLowerCase().includes(M.toLowerCase())||(g+=M),b=!0,y=!0}const v=[],C=/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;let w;for(;(w=C.exec(l))!==null;){const M=w[1],N=w[2]||w[3]||w[4]||"";v.push([M,N])}if(u?.has(a)){const M=u0e(e);return[{type:a,tag:a,attrs:v,content:M?M.inner:p.innerTokens.length?oA(p.innerTokens):"",children:p.innerTokens.length?i(p.innerTokens,o,s,r):[],raw:M?.raw??g,loading:e.loading||y,autoClosed:b},p.nextIndex]}return[{type:"html_inline",tag:a,attrs:v,content:g,children:m,raw:g,loading:y,autoClosed:b},p.nextIndex]}function lW(e){if(e.type==="math_inline"){if(e.raw)return String(e.raw);const t=e.markup==="$$"?"$$":"$";return`${t}${String(e.content??"")}${t}`}return Array.isArray(e.children)&&e.children.length>0?e.children.map(t=>lW(t)).join(""):String(e.content??"")}function h0e(e){return!e||!Array.isArray(e.children)||e.children.length===0?"":e.children.map(t=>lW(t)).join("")}function WL(e,t=!1){let n=e.attrs??[],i=null;if((!n||n.length===0)&&Array.isArray(e.children))for(const d of e.children){const h=d.attrs;if(Array.isArray(h)&&h.length>0){n=h,i=d;break}}const o=String(n.find(d=>d[0]==="src")?.[1]??""),s=n.find(d=>d[0]==="alt")?.[1],r=h0e(i??e);let l="";r?l=r:s!=null&&String(s).length>0?l=String(s):i?.content!=null&&String(i.content).length>0?l=String(i.content):Array.isArray(i?.children)&&i.children[0]?.content?l=String(i.children[0].content):Array.isArray(e.children)&&e.children[0]?.content?l=String(e.children[0].content):e.content!=null&&String(e.content).length>0&&(l=String(e.content));const a=n.find(d=>d[0]==="title")?.[1]??null,u=a===null?null:String(a),c=String(e.content??"");return{type:"image",src:o,alt:l,title:u,raw:c,loading:t}}function p0e(e){const t=String(e.content??"");return{type:"inline_code",code:t,raw:t}}function m0e(e,t,n){const i=[];let o="",s=t+1;const r=[];for(;s=0;i--){const[o,s]=e[i];if(String(o).toLowerCase()===n)return s}}function v0e(e,t,n){const i=e.slice();return Uk(i,"href")||i.push(["href",t]),n!=null&&!Uk(i,"title")&&i.push(["title",n]),i}function my(e,t,n){const i=e[t],o=g0e(i.attrs),s=String(Uk(o,"href")??""),r=Uk(o,"title"),l=r==null?null:String(r),a=v0e(o,s,l);let u=t+1;const c=[];let d=!0;for(;uy.type==="strong_open")){const y=String(p.content??""),b=String(p.raw??y),v=qh(p);v.content=y.slice(0,-2),v.raw=b.replace(/\*\*$/,""),h=c.slice(),h[h.length-1]=v}const m=is(h,void 0,void 0,n),g=m.map(y=>{const b=y;return"content"in y?String(b.content??""):String(b.raw??"")}).join("");return{node:{type:"link",href:s,title:l,text:g,children:m,raw:`[${g}](${s}${l?` "${l}"`:""})`,loading:d,attrs:a},nextIndex:u0?i:[{type:"text",content:a,raw:a}],raw:`~${a}~`},nextIndex:s0?i:[{type:"text",content:o||String(e[t].content??""),raw:o||String(e[t].content??"")}],raw:`^${o||String(e[t].content??"")}^`},nextIndex:s?@[\\\]^_`{|}~]/,E0e=/\p{P}/u,L0e=/^[\x22\x27《「『【〔〖〘〚〈([{“‘﹁﹃﹙﹛﹝]$/u,N0e=/^[\x22\x27》」』】〕〗〙〛〉)]}”’﹂﹄﹚﹜﹞]$/u,D0e=/^(?:https?:\/\/|mailto:|ftp:\/\/)/i,F0e=/:\/\//,sA=1,aW=2,R0e=4,O0e=8,uW=16,Td=32,k9=64,Yg=128,cW=256,P0e=512,Jg=1024,$0e=1982;function gy(e){let t=0;for(let n=0;n=t){n++,i++;continue}n++,i++;continue}if(o==="*"&&n>=t)return n;n++}return-1}function gf(e){return!!e&&M0e.test(e)}function vf(e){return!!e&&(T0e.test(e)||E0e.test(e))}function fW(e,t){return!!e&&!!t&&/^\p{Script=Han}$/u.test(t)&&L0e.test(e)}function hW(e,t){return!!e&&!!t&&/^[\p{L}\p{N}]$/u.test(t)&&N0e.test(e)}function z0e(e,t){const n=t>0?e[t-1]:void 0,i=e[t+1];return!i||gf(i)?!1:!(vf(i)&&!fW(i,n)&&n&&!gf(n)&&!vf(n))}function j0e(e,t){const n=t>0?e[t-1]:void 0,i=e[t+1];return!n||gf(n)?!1:!(vf(n)&&!hW(n,i)&&i&&!gf(i)&&!vf(i))}function H0e(e,t,n=0){let i=n,o=!1;for(;i0?e[t-1]:void 0,i=e[t+2];return!i||gf(i)?!1:!(vf(i)&&!fW(i,n)&&n&&!gf(n)&&!vf(n))}function q0e(e,t){const n=t>0?e[t-1]:void 0,i=e[t+2];return!n||gf(n)?!1:!(vf(n)&&!hW(n,i)&&i&&!gf(i)&&!vf(i))}function U0e(e,t=0){let n=t,i=!1;for(;n=0&&e[s]==="\\";s--)o++;return o%2===1}const G0e=/[\p{L}\p{N}]/u,Q0e=/^[\p{L}\p{N}]+$/u;function rA(e){return e?G0e.test(e):!1}function pW(e){return e?Q0e.test(e):!1}function M0(e,t){let n=t;for(;n0?e[t-1]:void 0,o=n=2&&i.intraword&&t.push({start:n,end:o}),n=o}for(let n=0;n=3)return i;n=i+o.len}return-1}function eve(e){return e?D0e.test(e)||F0e.test(e):!1}function tve(e,t){if(!e||!t)return null;const n=e.match(/\[([^\]\n]+)\]\(([^)]*)$/);return n&&n[2]===t?n[1]:null}function is(e,t,n,i){if(!e||e.length===0)return[];const o=i?.__linkifyDemotionContext,s=o2(t),r={filename:o?.filename||s.filename,explicitFilename:o?.explicitFilename||s.explicitFilename,marketTicker:o?.marketTicker||s.marketTicker};(r.filename||r.explicitFilename||r.marketTicker)&&(i={...i,__linkifyDemotionContext:r});const l=i,a=[];let u=null,c=0;const d=i?.requireClosingStrong,h=e;function p(){return e===h&&(e=e.slice()),e}function m(){u=null}function g(G,oe){const Z=e.length===1?t:String(oe.content??""),Q=[],fe=Y0e(G);if(fe!==-1){M(G.slice(0,fe),G.slice(0,fe));const pe=G.slice(fe);return pe&&(E({type:"text",content:pe,raw:pe}),c--),c++,!0}if(x0e.test(G)){const pe=G.indexOf("~~");pe!==-1&&Q.push({type:"strikethrough",index:pe})}if(S0e.test(G)){const pe=G.indexOf("**");pe!==-1&&Q.push({type:"strong",index:pe})}if(/[^*]*\*[^*]+/.test(G)){const pe=Z?dW(Z,0):G.indexOf("*");if(Z&&pe===-1)return!1;pe!==-1&&Q.push({type:"emphasis",index:pe})}Q.sort((pe,X)=>pe.index!==X.index?pe.index-X.index:pe.type===X.type?0:pe.type==="strong"?-1:X.type==="strong"?1:0);const de=Q[0];if(!de)return!1;if(de.type==="strikethrough"){const pe=de.index,X=pe>-1?G.slice(0,pe):"";if(X&&M(X,X),pe===-1)return c++,!0;const re=G.indexOf("~~",pe+2),ke=re===-1?G.slice(pe+2):G.slice(pe+2,re),le=re===-1?"":G.slice(re+2),{node:se}=UL([{type:"s_open",tag:"s",content:"",markup:"~~",info:"",meta:null},{type:"text",tag:"",content:ke,markup:"",info:"",meta:null},{type:"s_close",tag:"s",content:"",markup:"~~",info:"",meta:null}],0,i);return m(),w(se),le&&(E({type:"text",content:le,raw:le}),c--),c++,!0}if(de.type==="strong"){const pe=de.index,X=pe>-1?G.slice(0,pe):"";if(X&&M(X,X),pe===-1)return c++,!0;if(t&&pe===0){let ge=!1,Le=0;for(;Le=2)return M(G,G),c++,!0}}if(t&&(G.match(/\*/g)||[]).length>B0e(t))return M(G.slice(X.length),G.slice(X.length)),c++,!0;const re=M0(G,pe);if(re.len>=3){const ge=X0e(G,pe+re.len);if(ge!==-1){const Le=G.slice(pe+re.len,ge);if(J0e(Le)){const{node:be}=_g([{type:"strong_open",tag:"strong",content:"",markup:"**",info:"",meta:null},{type:"em_open",tag:"em",content:"",markup:"*",info:"",meta:null},{type:"text",tag:"",content:Le,markup:"",info:"",meta:null},{type:"em_close",tag:"em",content:"",markup:"*",info:"",meta:null},{type:"strong_close",tag:"strong",content:"",markup:"**",info:"",meta:null}],0,t,i);m(),w(be);const xe=G.slice(ge+3);return xe&&(E({type:"text",content:xe,raw:xe}),c--),c++,!0}}}if(!W0e(G,pe)){const ge=G.slice(pe,pe+re.len);M(ge,ge);const Le=G.slice(pe+re.len);return Le&&(E({type:"text",content:Le,raw:Le}),c--),c++,!0}const ke=U0e(G,pe+2);let le="",se="";if(ke.index!==-1){le=G.slice(pe+2,ke.index),se=G.slice(ke.index+2);const ge=ke.index,Le=M0(G,ge);if(re.intraword&&Le.intraword&&!pW(le)||!le&&re.len>=4&&re.intraword)return M(G.slice(X.length),G.slice(X.length)),c++,!0}else{if(d||ke.sawInvalidClose||re.intraword)return M(G.slice(X.length),G.slice(X.length)),c++,!0;le=G.slice(pe+2),se=""}if(!le&&/^\*+$/.test(se))return M(G,G),c++,!0;const{node:_e}=_g([{type:"strong_open",tag:"strong",content:"",markup:"**",info:"",meta:null},{type:"text",tag:"",content:le,markup:"",info:"",meta:null},{type:"strong_close",tag:"strong",content:"",markup:"**",info:"",meta:null}],0,t,i);return m(),w(_e),se&&(E({type:"text",content:se,raw:se}),c--),c++,!0}if(de.type==="emphasis"){let pe=de.index;pe===-1&&(pe=0);const X=G.slice(0,pe);if(X&&M(X,X),!z0e(G,pe)){M(G[pe],G[pe]);const ge=G.slice(pe+1);return ge&&(E({type:"text",content:ge,raw:ge}),c--),c++,!0}const re=M0(G,pe),ke=H0e(Z,G,pe+1),le=ke.index,se=e[c+1];if(i?.final&&se?.type==="em_open"&&le!==-1&&G.slice(pe+1,le).trim()!==G.slice(pe+1,le)||le===-1&&(ke.sawInvalidClose||i?.final||re.intraword||!rA(G[pe+1])))return M(G.slice(pe),G.slice(pe)),c++,!0;const{node:_e}=py([{type:"em_open",tag:"em",content:"",markup:"*",info:"",meta:null},{type:"text",tag:"",content:le>-1?G.slice(pe+1,le):G.slice(pe+1),markup:"",info:"",meta:null},{type:"em_close",tag:"em",content:"",markup:"*",info:"",meta:null}],0,i);if(m(),w(_e),le!==-1&&le{for(let _e=0;_e=0&&se[Le]==="\\";Le--)ge++;if(ge%2===0)return _e}return-1})(G);if(Q===-1)return!1;let fe=1;for(let se=Q+1;sede?.type==="math_inline")||!_0e.test(G))return null;const Z=oe.parseInline(G,{__markstreamFinal:!!i?.final});if(!Array.isArray(Z)||Z.length===0)return null;const Q=(Z.find(de=>de?.type==="inline")?.children??[]).filter(de=>!(de?.type==="text"&&String(de.content??"")===""));if(!Q.length||!Q.some(de=>de?.type!=="text")||Q.length===1&&Q[0]?.type==="text"&&String(Q[0].content??"")===G)return null;const fe=is(Q,G,n,i);return fe.length?fe:null}function v(G){m(),a.push(G)}function C(G){m();const oe=qh(G);a.push(oe)}function w(G){v(G)}function M(G,oe){u?(u.content+=G,u.raw+=oe??G):(u={type:"text",content:String(G??""),raw:String(oe??G??"")},a.push(u))}function N(G,oe){if(!G)return;const Z=is([{...oe,type:"text",content:G,raw:G}],G,n,i);if(Z.length===1&&Z[0]?.type==="text"){const Q=Z[0];M(String(Q.content??""),String(Q.raw??Q.content??""));return}for(const Q of Z)w(Q)}function T(G,oe){return String(G.markup??"").startsWith(oe)}function S(G){if(!u||G.loading!==!0||G.markup!=="\\(\\)")return;const oe=e[c-1];!oe||oe.type!=="text"||!T(oe,"\\(")||u.content.endsWith("(")&&(u.content=u.content.slice(0,-1),u.raw.endsWith("(")&&(u.raw=u.raw.slice(0,-1)),!u.content&&a[a.length-1]===u&&(a.pop(),u=null))}function x(G){return G.endsWith("](")?e[c+1]?.type==="link_open"&&e[c+1]?.markup==="linkify"&&e[c+2]?.type==="text"&&e[c+3]?.type==="link_close"&&e[c+4]?.type==="text"&&String(e[c+4]?.content??"").startsWith(")"):!1}function A(G,oe,Z=gy(G)){let Q=G;const fe=String(oe.content??"");return(Z&sA)!==0&&Q.endsWith("\\")&&!T(oe,"\\\\")&&!fe.endsWith("\\\\")&&(Q=Q.slice(0,-1)),(Z&Jg)!==0&&Q.endsWith("(")&&!T(oe,"\\(")&&!fe.endsWith("\\(")&&(Q=Q.slice(0,-1)),(Z&aW)!==0&&/\*+$/.test(Q)&&!T(oe,"\\*")&&!fe.endsWith("\\*")&&(Q=Q.replace(/\*+$/,"")),Q}for(;c=0;ge--){const Le=a[ge];if(Le.type!=="text")break;re=ge,ke=String(Le.content??"")+ke}rere==="href")?.[1],X=String(pe??"");if(t&&X){const re=t.indexOf("](");if(re!==-1){const ke=t.indexOf(")",re+2);ke===-1?Z.loading=!0:Z.loading&&t.slice(re+2,ke).includes(X)&&(Z.loading=!1)}}/^file:\/\/\/[a-z]:\//i.test(Z.href)&&$(Z,oe-1)||O(Z)||v(Z)}function z(G){if(G.markup!=="linkify")return!1;const{node:oe,nextIndex:Z}=my(e,c,i);return j(oe,Z)?(c=Z,!0):!1}function F(G){m(),w(y0e(G)),c++}function O(G){if(G.type!=="link")return!1;const oe=a[a.length-1];if(!oe||oe.type!=="text")return!1;const Z=String(oe.content??"").match(/^([^[]*)\[([^\]\n]+)\]\($/);if(!Z)return!1;const Q=G,fe=String(Q.href??""),de=String(Q.text??""),pe=String(Z[2]??""),X=fe.replace(/^(?:https?:\/\/|mailto:|ftp:\/\/)/i,"");if(!fe||!(de===fe||de===X||eve(de)))return!1;const re=String(Z[1]??"");return re?(oe.content=re,oe.raw=re):a.pop(),v({...G,text:pe,children:[{type:"text",content:pe,raw:pe}],raw:`[${pe}](${fe}${Q.title?` "${Q.title}"`:""})`}),!0}function B(G){if(G.type!=="link")return!1;const oe=G,Z=String(oe.href??"");return Z?j({href:Z,title:oe.title==null||oe.title===""?null:String(oe.title),loading:!!oe.loading},c+1):!1}function j(G,oe){const Z=a[a.length-1];if(Z?.type!=="image"||Z.src||!Z.loading||!String(Z.raw??"").endsWith("]("))return!1;const Q=e[oe],fe=String(Q?.content??"");if(Q?.type!=="text"||!fe.startsWith(")"))return!1;a.pop(),u=null;const de=String(Z.alt??"");v({type:"image",src:G.href,alt:de,title:G.title,raw:`![${de}](${G.href}${G.title?` "${G.title}"`:""})`,loading:!!G.loading});const pe=fe.slice(1),X=qh(Q);return X.content=pe,X.raw=pe,p()[oe]=X,!0}function $(G,oe=c-1){if(G.type!=="link")return!1;const Z=a[a.length-1],Q=e[oe];if(!Z||Z.type!=="text"||Q?.type!=="text")return!1;const fe=String(Z.content??""),de=String(Q.content??"");if(!fe.endsWith("!")||!de.endsWith("!")||T(Q,"\\!"))return!1;const pe=fe.slice(0,-1);pe?(Z.content=pe,Z.raw=pe,u=Z):(a.pop(),u=null);const X=G,re=String(X.text??X.children?.map(se=>String(se?.content??se?.raw??"")).join("")??""),ke=String(X.href??""),le=X.title==null||X.title===""?null:String(X.title);return v({type:"image",src:ke,alt:re,title:le,raw:`![${re}](${ke}${le?` "${le}"`:""})`,loading:!!X.loading}),!0}function V(G,oe="",Z=null){const Q=String(G.alt??G.raw??"");return{type:"link",href:oe,title:Z,text:Q,children:[G],raw:`[${Q}](${oe}${Z?` "${Z}"`:""})`,loading:!0}}function ne(G){const oe=G.startsWith("![")?G:`![${G}`,Z=oe.slice(2),Q=Z.indexOf("](");return{type:"image",src:"",alt:Q===-1?Z.replace(/\]$/,""):Z.slice(0,Q),title:null,raw:oe,loading:!0}}function K(G){const oe=G.indexOf("[![");if(oe===-1||typeof t=="string"&&e.length===1&&Z0e(t,oe,"["))return!1;const Z=G.slice(0,oe);return Z&&M(Z,Z),v(V(ne(G.slice(oe+1)))),c++,!0}function ee(G){if(i?.final)return!1;const oe=e[c-1];if(oe?.type!=="text"||!String(oe.content??"").endsWith("[")||T(oe,"\\["))return!1;const Z=a[a.length-1];if(Z?.type==="text"&&Z.content.endsWith("[")){const Q=Z.content.slice(0,-1);Q?(Z.content=Q,Z.raw=Q,u=Z):(a.pop(),u=null)}return v(V(WL(G))),c++,!0}function ue(G){if(G.type!=="link")return!1;const oe=G,Z=String(oe.raw??""),Q=String(oe.text??"");if(!Z.startsWith("[![")&&!Q.startsWith("!["))return!1;const fe=oe.title==null||oe.title===""?null:String(oe.title);return v(V({type:"image",src:String(oe.href??""),alt:Q.replace(/^!\[/,"").replace(/\]$/,""),title:fe,raw:Z.startsWith("[![")?Z.slice(1):Z,loading:!0})),!0}function ie(G){if(!G.startsWith("]("))return!1;const oe=e[c-2];if(oe?.type==="text"&&String(oe.content??"").endsWith("[")&&T(oe,"\\["))return!1;const Z=a[a.length-1];if(Z?.type!=="image"&&Z?.type!=="link")return!1;const Q=Z,fe=Z?.type==="link"&&Array.isArray(Q.children)&&Q.children.length===1&&Q.children[0]?.type==="image"?a.pop():null,de=fe?fe.children[0]:a.pop();if(!de||de.type!=="image")return!1;const pe=e[c+1];let X=String(fe?.href??""),re=fe?.title==null?null:String(fe.title),ke=!0;if(pe?.type==="link_open"){const{node:se,nextIndex:_e}=my(e,c+1,i);X=se.href,re=se.title,ke=!0,c=_e}else{if(X=G.slice(2),X.includes('"')){const se=X.split('"');X=String(se[0]??"").trim(),re=se[1]==null?null:String(se[1]).trim()}c++}const le=V(de,X,re);return le.loading=ke,v(le),!0}function ye(){const G=e[c-3];return e[c-2]?.type==="image"&&e[c-1]?.type==="text"&&String(e[c-1].content??"")==="]("&&G?.type==="text"&&String(G.content??"").endsWith("[")&&T(G,"\\[")}function Te(G,oe){const Z=G.indexOf("[");if(Z===-1)return!1;let Q=G.slice(0,Z);const fe=G.indexOf("](",Z);if(fe!==-1){const de=e[c+2];let pe=G.slice(Z+1,fe);if(pe.includes("[")){const ge=pe.indexOf("[");Q+=G.slice(0,Z+ge+1);const Le=Z+ge+1;pe=G.slice(Le+1,fe)}const X=e[c+1];if(G.endsWith("](")&&X?.type==="link_open"&&de){const ge=e[c+4];let Le=4,be=!0;if(ge?.type==="text"){const Oe=String(ge.content??"");if(Oe.startsWith(")")){be=!1;const Ze=Oe.slice(1);if(Ze){const ct=qh(ge);ct.content=Ze,ct.raw=Ze,p()[c+4]=ct}else Le++}else Oe==="."&&Le++}N(Q,oe);const xe=String(de.content??"");return i?.validateLink&&!i.validateLink(xe)?M(pe,pe):v({type:"link",href:xe,title:null,text:pe,children:[{type:"text",content:pe,raw:pe}],loading:be}),c+=Le,!0}const re=G.indexOf(")",fe),ke=re!==-1?G.slice(fe+2,re):"",le=re===-1;let se=Q.match(/\*+$/);if(se&&(Q=Q.replace(/\*+$/,"")),N(Q,oe),se||(se=pe.match(/^\*+/)),!d&&se){const ge=se[0].length;pe=pe.replace(/^\*+/,"").replace(/\*+$/,"");const Le=[];if(ge===1?Le.push({type:"em_open",tag:"em",nesting:1}):ge===2?Le.push({type:"strong_open",tag:"strong",nesting:1}):ge===3&&(Le.push({type:"strong_open",tag:"strong",nesting:1}),Le.push({type:"em_open",tag:"em",nesting:1})),Le.push({type:"link",href:ke,title:null,text:pe,children:[{type:"text",content:pe,raw:pe}],loading:le}),ge===1){Le.push({type:"em_close",tag:"em",nesting:-1});const{node:be}=py(Le,0,i);w(be)}else if(ge===2){Le.push({type:"strong_close",tag:"strong",nesting:-1});const{node:be}=_g(Le,0,void 0,i);w(be)}else if(ge===3){Le.push({type:"em_close",tag:"em",nesting:-1}),Le.push({type:"strong_close",tag:"strong",nesting:-1});const{node:be}=_g(Le,0,void 0,i);w(be)}else{const{node:be}=py(Le,0,i);w(be)}}else i?.validateLink&&!i.validateLink(ke)?M(pe,pe):v({type:"link",href:ke,title:null,text:pe,children:[{type:"text",content:pe,raw:pe}],loading:le});const _e=re!==-1?G.slice(re+1):"";return _e&&(E({type:"text",content:_e,raw:_e}),c--),c++,!0}return!1}function Ee(G){const oe=G.indexOf("![");if(oe===-1)return!1;const Z=G.slice(0,oe);return Z&&!u?u={type:"text",content:Z,raw:Z}:Z&&u&&(u.content+=Z),u&&(a.push(u),u=null),v(ne(G.slice(oe))),c++,!0}function Me(G){if(!(G?.startsWith("[")&&n?.type==="list_item_open"))return!1;const oe=G.slice(1).match(/[^\s\]]/);if(oe===null)return c++,!0;if(oe&&/x/i.test(oe[0])){const Z=oe[0]==="x"||oe[0]==="X";return v({type:"checkbox_input",checked:Z,raw:Z?"[x]":"[ ]"}),c++,!0}return!1}return a}function rx(e,t,n){const i=n?.__sourceLineMapper;if(!i)return{startLine:e,endLine:t};const o=i(e),s=t>e?i(t-1).endLine:i(t).startLine;return{startLine:o.startLine,endLine:Math.max(o.startLine,s)}}function VL(e,t){const n=Math.max(0,Math.min(e.length,Math.trunc(t)));let i=0;for(let o=0;oi&&e[o-1]!==` -`&&r++,{startLine:s,endLine:r}}function _v(e,t,n,i){const o=nve(e,t,n);return rx(o.startLine,o.endLine,i)}function ive(e,t){const n=e?.map;if(!Array.isArray(n)||n.length<2)return null;const i=Number(n[0]),o=Number(n[1]);return!Number.isFinite(i)||!Number.isFinite(o)?null:rx(i,o,t)}function Ei(e,t,n){if(!n?.includeSourceMap)return e;const i=ive(t,n);if(!i)return e;if(e.sourceMap=i,e.type==="code_block"){const o=e;o.startLine=i.startLine,o.endLine=i.endLine}return e}function ove(e,t,n,i){if(!i?.includeSourceMap)return e;const o=t?.map;if(!Array.isArray(o)||o.length<2)return e;const s=Number(o[0]),r=Number(o[1]),l=Number(n);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(l)||(e.sourceMap=rx(s,Math.max(r,l),i)),e}function sve(e){const t=String(e.content??""),n=t.replace(/[ \t\r\n]+$/g,"");if(n===t)return;e.content=n;const i=e.children;if(!(!Array.isArray(i)||i.length===0))for(;i.length;){const o=i[i.length-1];if(!o){i.pop();continue}if(o.type==="softbreak"||o.type==="hardbreak"){i.pop();continue}if(o.type==="text"){const s=String(o.content??""),r=s.replace(/[ \t\r\n]+$/g,"");if(r===s)break;if(r){o.content=r;break}i.pop();continue}break}}function rve(e){const t=String(e.content??""),n=t.match(/\r?\n\s*\d+[.)]?\s*$/);if(!n||typeof n.index!="number")return;e.content=t.slice(0,n.index);const i=e.children;if(!(!Array.isArray(i)||i.length===0))for(;i.length;){const o=i[i.length-1];if(!o){i.pop();continue}if(o.type==="softbreak"||o.type==="hardbreak"){i.pop();continue}if(o.type==="text"){const s=String(o.content??"");if(/^[ \t\r\n\d.)]*$/.test(s)){i.pop();continue}const r=s.replace(/[ \t\r\n\d.)]+$/g,"");r!==s&&(r?o.content=r:i.pop())}break}}function lve(e){const t=String(e.content??"");return/[ \t\r\n]+$/.test(t)||/\r?\n\s*\d+[.)]?\s*$/.test(t)}function Pm(e,t,n){const i=e[t],o=[],s=Ff(n,!0);let r=t+1;for(;rd.raw).join("")};n?.includeSourceMap&&Ei(c,e[r],n),o.push(c),r=u+1}else r+=1;const l={type:"list",ordered:i.type==="ordered_list_open",start:(()=>{if(i.attrs&&i.attrs.length){const a=i.attrs.find(u=>u[0]==="start");if(a){const u=Number(a[1]);return Number.isFinite(u)&&u!==0?u:1}}})(),items:o,raw:o.map(a=>a.raw).join(` -`)};return n?.includeSourceMap&&Ei(l,i,n),[l,r+1]}function ave(e,t,n,i){const o=String(n[1]??"note"),s=String(n[2]??o.charAt(0).toUpperCase()+o.slice(1)),r=[],l=Ff(i,!0);let a=t+1;for(;au.raw).join(` -`)} -:::`},a+1]}const uve=new Set(["warning","info","note","tip","danger","caution"]);function cve(e){let t=0;for(;t=0;g--){const y=h[g];if(y.type==="text"&&/:+/.test(y.content)){p=g;break}}const m={type:"paragraph",children:is((p!==-1?h.slice(0,p):h)||[],void 0,void 0,a.options()),raw:String(d.content??"").replace(/\n:+$/,"").replace(/\n\s*:::\s*$/,"")};n?.includeSourceMap&&Ei(m,e[u],n),l.push(m),a.remember(m.raw)}u+=3}else if(e[u].type==="bullet_list_open"||e[u].type==="ordered_list_open"){const[d,h]=Pm(e,u,a.options());n?.includeSourceMap&&Ei(d,e[u],n),l.push(d),a.remember(d.raw),u=h}else if(e[u].type==="blockquote_open"){const[d,h]=$m(e,u,a.options());n?.includeSourceMap&&Ei(d,e[u],n),l.push(d),a.remember(d.raw),u=h}else{const d=A4(e,u,a.options());d?(l.push(d[0]),a.remember(d[0].raw),u=d[1]):u++}return[{type:"admonition",kind:o,title:s,children:l,raw:`:::${o} ${s} -${l.map(d=>d.raw).join(` -`)} -:::`},u+1]}const fve=/^::: ?(warning|info|note|tip|danger|caution|error) ?(.*)$/;function hve(e,t,n){const i=e[t];if(i.type!=="container_open")return null;const o=fve.exec(String(i.info??""));return o?ave(e,t,o,n):null}const lx={parseContainer:(e,t,n)=>dve(e,t,n),matchAdmonition:hve};function $m(e,t,n){const i=[],o=Ff(n,!0);let s=t+1;for(;sl.raw).join(` -`)};return n?.includeSourceMap&&Ei(r,e[t],n),[r,s+1]}function pve(e){if(e.info?.startsWith("diff"))return ox(e);const t=String(e.content??""),n=t.match(/ type="application\/vnd\.ant\.([^"]+)"/);let i=t;n?.[1]&&(i=t.replace(/]*>/g,"").replace(/<\/antArtifact>/g,""));const o=Array.isArray(e.map)&&e.map.length===2;return{type:"code_block",language:n?n[1]:String(e.info??""),code:i,raw:i,loading:!o}}function mve(e,t,n){const i=[];let o=t+1,s=[],r=[];const l=Ff(n,!0);for(;ou.raw).join("")),o+=3}else if(e[o].type==="dd_open"){let a=o+1;for(r=[];a0&&(i.push({type:"definition_item",term:s,definition:r,raw:`${s.map(u=>u.raw).join("")}: ${r.map(u=>u.raw).join(` -`)}`}),s=[]),o=a+1}else o++;return[{type:"definition_list",items:i,raw:i.map(a=>a.raw).join(` -`)},o+1]}function gve(e,t,n){const i=e[t].meta??{},o=String(i?.label??"0"),s=[],r=Ff(n,!0);let l=t+1;for(;la.raw).join(` -`)}`},l+1]}function vve(e,t,n){const i=e[t],o=i.attrs,s=Array.isArray(o)&&o.length?Object.fromEntries(o.filter(c=>Array.isArray(c)&&c.length>=1&&c[0]).map(([c,d])=>[String(c),d==null||d===""?!0:String(d)])):void 0,r=String(i.tag?.substring(1)??"1"),l=Number.parseInt(r,10),a=e[t+1],u=String(a.content??"");return{type:"heading",level:l,text:u,...s?{attrs:s}:{},children:is(a.children||[],u,void 0,n),raw:u}}function yve(e,t,n){const i=t.toLowerCase(),o=new RegExp(String.raw`^<\s*${i}(?=\s|>|/)`,"i"),s=new RegExp(String.raw`^<\s*\/\s*${i}(?=\s|>)`,"i");let r=0,l=Math.max(0,n);for(;l$/.test(d)||r++,l=a+c+1;continue}l=a+1}return-1}function mW(e){const t=String(e.content??"");if(/^\s*");else if(a)a=!y.includes(">");else if(u)u=!y.includes("?>");else if(y.startsWith("");else if(y.startsWith("");else if(y.startsWith("");else{const b=o(y);if(b)if(b.closing){for(let v=r.length-1;v>=0;v--)if(r[v]===b.tag){r.length=v;break}}else b.selfClosing||s(b.after,b.tag)||r.push(b.tag)}}if(d===-1||d>=t)break;c=d+1}return l||a||u||r.length>0}function i2e(e,t,n){if(!n?.length)return!1;const i=new Set(kp(n));if(!i.size)return!1;const o=c=>{const d=c.charCodeAt(0);return d>=65&&d<=90||d>=97&&d<=122||d>=48&&d<=57||c==="_"||c==="-"||c===":"},s=c=>c===" "||c===" ",r=c=>{if(c[0]!=="<")return null;let d=1;for(;d"&&g!=="/")return null;const y=c.indexOf(">",d);if(y===-1)return null;let b=y-1;for(;b>=0&&s(c[b]);)b--;return{closing:h,tag:m,selfClosing:!h&&c[b]==="/",after:c.slice(y+1)}},l=(c,d)=>{const h=c.toLowerCase();let p=0;for(;p")return!0}}return!1},a=[];let u=0;for(;u=t?t:c,h=e.slice(u,d),p=h.endsWith("\r")?h.slice(0,-1):h,m=Bm(p);if(m){const g=r(p.slice(m.index));if(g)if(g.closing){for(let y=a.length-1;y>=0;y--)if(a[y]===g.tag){a.length=y;break}}else g.selfClosing||l(g.after,g.tag)||a.push(g.tag)}if(c===-1||c>=t)break;u=c+1}return a.length>0}function o2e(e,t){const n=Fve.exec(e);if(!n)return null;const i=n[1]??"",o=n.index+i.length,s=e.indexOf(` -`,o),r=e.slice(o,s===-1?e.length:s);return!Bm(r.endsWith("\r")?r.slice(0,-1):r)||SW(e,o)||n2e(e,o)||i2e(e,o,t)?null:`${e.slice(0,n.index)}${i}`}function px(e,t,n){let i=t;for(;ii&&(r=!0),t.inMath=!1,t.mathOpenOffset=null,s+=2;continue}s++;continue}if(t.inDollarMath){if(e.startsWith("$$",s)&&!Zu(e,l)){i!=null&&o&&n+s+2>i&&(r=!0),t.inDollarMath=!1,t.dollarMathOpenOffset=null,s+=2;continue}s++;continue}if(e[s]==="`"&&!Zu(e,l)){const a=px(e,s,"`"),u=_W(e,s+a,a);if(u===-1)break;s=u+a;continue}if(e.startsWith("\\[",s)&&!Zu(e,l)){t.inMath=!0,t.mathOpenOffset=n+s,s+=2;continue}if(e.startsWith("$$",s)&&!Zu(e,l)){t.inDollarMath=!0,t.dollarMathOpenOffset=n+s,s+=2;continue}s++}return r}function s2e(e,t){if(!nx(t))return e;const n=t,i=YL.get(n),o=i?.source===e?i.state:i&&e.startsWith(i.source)?IW(i.state,e.slice(i.source.length),i.source.length-i.state.lineBuffer.length).state:S4(e).state;YL.set(n,{source:e,state:o});const{context:s}=o,r=s.inMath?s.mathOpenOffset:s.inDollarMath?s.dollarMathOpenOffset:null;if(r==null)return e;const l=e.slice(r+2),a=e.lastIndexOf(` -`,r-1)+1;if(e.slice(a,r).trim()!==""&&!/^\r?\n/.test(l)||/^\s*!\[/.test(l))return e;const u=l.trim(),c=/^(?:[a-z]|pi)$/i.test(u);return zd(l)&&!c?e:e.slice(0,r)}function r2e(e,t,n,i,o){const s=cx(e),r=dx(e);if(t.inFence&&t.fenceInBlockquote&&e.trim()&&fx(e)==null&&q8(t),t.inFence&&t.fenceInList&&e.trim()&&s.column=t.fenceLen&&/^\s*$/.test(l.rest)&&q8(t):(t.inFence=!0,t.fenceChar=l.markerChar,t.fenceLen=l.markerLen,t.fenceInBlockquote=l.inBlockquote,t.fenceInList=l.inList||t.listContentIndent!=null&&!l.inBlockquote&&s.column>=t.listContentIndent,t.fenceListIndent=l.listIndent||t.listContentIndent||0);else if(!t.inFence)return tN(e,t,n,i,o)}else return tN(e,t,n,i,o);return!1}function S4(e,t=Yve(),n=null,i=!1,o=0){const s=E0(t);let r=E0(t),l="",a=!1,u=0;for(;uu&&e[c-1]==="\r"?c-1:d?c:e.length,p=e.slice(u,h);r2e(p,s,o+u,n,i)&&(a=!0),d?(r=E0(s),l=""):l=p,u=d?c+1:e.length}return{closedOpenMath:a,state:{committedContext:r,context:s,lineBuffer:l}}}function IW(e,t,n=0){return t&&!e.context.inMath&&!e.context.inDollarMath&&!e.context.inFence&&!e.committedContext.inFence&&!/[\\$`~\r\n]/.test(t)&&!(e.lineBuffer.endsWith("\\")&&(t[0]==="["||t[0]==="]"))?{closedOpenMath:!1,state:{committedContext:E0(e.committedContext),context:E0(e.context),lineBuffer:e.lineBuffer+t}}:S4(e.lineBuffer+t,e.committedContext,n+e.lineBuffer.length,e.context.inMath||e.context.inDollarMath,n)}function l2e(e,t){if(!nx(e))return;const n=e.stream;if(typeof n?.reset!="function")return;const i=e,o=x4.get(i);if(o?.source===t)return;const s=o?t.startsWith(o.source):!1,r=s&&o?t.slice(o.source.length):"",l=s&&o?IW(o.explicitBracketMath,r,o.source.length-o.explicitBracketMath.lineBuffer.length):S4(t),a=l.state,u=s&&o?l.closedOpenMath:!1;if(o&&s&&o.key===null&&o.pendingCandidate===!1&&!u&&!t2e(o.source,r)&&!Xve(t)){o.source=t,o.explicitBracketMath=a;return}const c=Hge(t);(o&&(o&&!s||o.key!==c||u)||!o&&c)&&n.reset(),Jve(e,t,c,a)}function a2e(e){return typeof e.preTransformTokens=="function"||typeof e.postTransformTokens=="function"}function MW(e,t){const n=e?.map,i=t?.map;return n===i?!0:!Array.isArray(n)||!Array.isArray(i)?!1:n.length===i.length&&n.every((o,s)=>o===i[s])}function u2e(e,t){const n=e?.attrs,i=t?.attrs;if(n===i)return!0;if(!Array.isArray(n)||!Array.isArray(i)||n.length!==i.length)return!1;for(let o=0;o":""}function sN(e){return{type:"paragraph",children:e,raw:e.map(h2e).join("")}}function rN(e,t){if(t.sourceMap)for(const n of e)n.sourceMap||(n.sourceMap=t.sourceMap)}function lN(e,t){if(e.type!=="paragraph")return null;const n=e.children,i=Array.isArray(n)?n:[];if(i.length===0)return null;const o=Vve(t);if(!o?.size)return null;let s=-1;for(let c=0;cp?.type==="hardbreak")){s=c;break}}if(s===-1)return null;const r=i.slice(0,s),l=i[s];if(!l)return null;const a=[];r.length&&a.push(sN(r)),a.push(l);const u=i.slice(s+1);return u.length&&a.push(sN(u)),a}function p2e(e){const t=e.trim();if(!t)return null;const n=/^(?:]*>\s*)?]*)?>/i.test(t),i=/<\/html>\s*$/i.test(t);return!n||!i?null:[{type:"html_block",tag:"html",raw:e,content:e,loading:!1}]}function L0(e){const t=e.raw;if(typeof t=="string")return t;const n=e.content;return typeof n=="string"?n:""}function m2e(e,t){if(e.type!=="html_block"||!t)return!1;const n=String(e.raw??e.content??"");return new RegExp(String.raw`^\s*<\s*\/\s*${xu(t)}\s*>\s*$`,"i").test(n)}const V8=new Set(["iframe","script","style","textarea","title"]);function r2(e,t,n){if(!e||!t)return null;const i=t.toLowerCase(),o=h=>{if(e.startsWith("",h+4);return{closing:!1,end:C===-1?e.length:C+3,selfClosing:!1,tag:""}}if(e.startsWith("",h+9);return{closing:!1,end:C===-1?e.length:C+3,selfClosing:!1,tag:""}}const p=gs(e.slice(h));if(p===-1)return null;const m=h+p+1,g=e.slice(h,m);if(/^<\s*[!?]/.test(g))return{closing:!1,end:m,selfClosing:!1,tag:""};let y=g.slice(1).trimStart();const b=y.startsWith("/");b&&(y=y.slice(1).trimStart());const v=y.match(/^([A-Z][\w:-]*)/i);return v?.[1]?{closing:b,end:m,selfClosing:/\/\s*>$/.test(g),tag:v[1].toLowerCase()}:{closing:!1,end:h+1,selfClosing:!1,tag:""}},s=(h,p)=>{const m=new RegExp(String.raw`<\s*\/\s*${xu(h)}(?=\s|>)`,"gi");m.lastIndex=p;const g=m.exec(e);if(!g||g.index==null)return null;const y=o(g.index);return y?{start:g.index,end:y.end}:null};let r=-1,l=-1,a=Math.max(0,n);for(;a$/.test(u))return{raw:u,start:r,end:l+1,closed:!0};if(V8.has(i)){const h=s(i,l+1);return h?{raw:e.slice(r,h.end),start:r,end:h.end,closeStart:h.start,closed:!0}:{raw:e.slice(r),start:r,end:e.length,closed:!1}}let c=1,d=l+1;for(;d]*$/,"")} -`}function aN(e){return e.replace(/\r\n/g,` -`).replace(/(^|\n)[ \t]{1,4}/g,"$1")}function y2e(e,t,n){return n?e.includes(n,t)?!0:aN(e.slice(Math.max(0,t))).includes(aN(n)):!1}function k2e(e,t){let n=Math.max(0,t);for(;n)`,"gi");let i=-1,o;for(;(o=n.exec(e))!==null;)i=o.index;return i}function EW(e,t){return{final:t,__disableStreamParse:!0,requireClosingStrong:e.requireClosingStrong,customHtmlTags:e.customHtmlTags,validateLink:e.validateLink}}const w2e=new Set(["admonition","blockquote","code_block","definition_list","footnote","heading","list","math_block","table","thematic_break"]),C2e=/(?:^|\n)\s{0,3}(?:#{1,6}\s+\S|[-+*]\s+\S|\d+[.)]\s+\S|>\s*\S|`{3,}|~{3,}|(?:\*{3,}|-{3,}|_{3,})(?:\s|$)|\|.*\|)/m;function A2e(e){return/\n\s*\n/.test(e)||C2e.test(e)}function x2e(e,t){if(!e.trim()||t.length===0)return!1;if(t.some(i=>w2e.has(String(i?.type??"").toLowerCase()))||t.some(i=>{if(i?.type!=="html_block")return!1;const o=i;return Array.isArray(o.children)&&o.children.length>0}))return!0;if(!A2e(e))return!1;if(t.length>1)return!0;const[n]=t;return!!(n&&n.type==="paragraph")}function S2e(e){const t=[];let n=0;for(;n=e.length)break;const i=e.slice(n).match(/^<([A-Z][\w:-]*)/i);if(!i?.[1])return null;const o=r2(e,i[1],n);if(!o||o.start!==n)return null;t.push(o.raw),n=o.end}return t.length>1?t:null}function _2e(e,t,n,i){const o=n.customHtmlTags?.join("\0")??"",s=t,r=QL.get(s),l=r&&r.final===i&&r.customHtmlTags===o&&r.requireClosingStrong===n.requireClosingStrong&&r.validateLink===n.validateLink,a=e.map((u,c)=>l&&r.blocks[c]===u?r.children[c]:V1(u,t,n));return QL.set(s,{blocks:e,children:a,customHtmlTags:o,final:i,requireClosingStrong:n.requireClosingStrong,validateLink:n.validateLink}),a.flat()}function I2e(e,t,n,i){return e.map(o=>{if(o?.type!=="html_block")return o;const s=o,r=String(s.tag??"").toLowerCase();if(!r||r==="details"||TH.has(r)||Array.isArray(s.children))return o;const l=String(o.raw??s.content??"");if(!l)return o;const a=gs(l);if(a===-1)return o;const u=r2(l,r,0),c=u?.closeStart??-1,d=u?.closed===!0&&c>=a+1,h=d?l.slice(a+1,c):l.slice(a+1);if(!h.trim())return o;const p=EW(n,i),m=d?null:S2e(h),g=m?_2e(m,t,p,i):V1(h,t,p);return x2e(h,g)?{...o,children:g}:o})}function M2e(e){for(const t of e)if(t?.type==="html_block")return!0;return!1}function V1(e,t,n){return e.trim()?NW(e,t,{...n,__disableStreamParse:!0,__disableStructuredReuse:!0}):[]}function T2e(e,t,n){const i=V1(e,t,n),o=i[0];return i.length===1&&o?.type==="paragraph"&&Array.isArray(o.children)?o.children:i}function E2e(e,t,n){const i=mW({content:e}),o=gs(e),s=TW(e,"summary");if(o!==-1&&s!==-1&&s>=o+1){const r=T2e(e.slice(o+1,s),t,n);r.length>0&&(i.children=r)}return i.raw=e,i}function L2e(e,t,n){const i=gs(e);if(i===-1)return[];const o=e.slice(i+1);if(!o.trim())return[];const s=r2(o,"summary",0);if(!s)return V1(o,t,n);const r=o.slice(0,s.start),l=o.slice(s.end);return[...V1(r,t,n),E2e(s.raw,t,n),...V1(l,t,n)]}function LW(e,t,n,i,o,s=0){const r=[];let l=s;for(let a=0;a{const $=TW(h,"details");return $!==-1?h.slice(0,$):h})():h,[C]=LW(b?[]:g===-1?e.slice(a+1):e.slice(a+1,g),t,n,i,o,p+h.length),w=L2e(v,n,EW(i,o)),M=g===-1?"":String(e[g].raw??L0(e[g])??""),N=b||g!==-1&&y?.closed===!0,T=M.replace(/[\t\r\n ]+$/,""),S=N?(()=>{const $=(y?.raw??"").lastIndexOf(T);return $===-1?t.length:p+$})():t.length,x=gs(h),A=b&&x!==-1?p+x+1:p+h.length,E=t.slice(A,S===-1?t.length:S),I=n.parse(E,{__markstreamFinal:o}),R=n.renderer.render(I,n.options,{__markstreamFinal:o}),W=S+T.length,z=N?Math.max(S+M.length,k2e(t,W)):t.length,F=N?t.slice(S,z):M,O=N?t.slice(p,z):t.slice(p),B=b&&x!==-1?h.slice(0,x+1):h,j={...u,tag:"details",attrs:C4(h.slice(0,x+1)),raw:O,content:`${B}${R}${F}`,children:[...w,...C],loading:!o&&!N};if(i.includeSourceMap&&(j.sourceMap=_v(t,p,N?z:t.length,i)),r.push(j),l=N?z:t.length,g===-1&&!b)break;g!==-1&&(a=g)}return[r,l]}function N2e(e,t,n,i){if(!n)return e;const o=e.slice();let s=0;for(let r=0;r=d.start&&x.end<=d.end){o.splice(N,1);continue}break}M=S+T.length,o.splice(N,1)}}return o}function D2e(e){const t=l=>l===" "||l===" "||l===` -`||l==="\r",n=l=>{if(!l||l[0]!=="<"||l.includes(">"))return!1;let a=1;if(a{const y=g.charCodeAt(0);return y>=65&&y<=90||y>=97&&y<=122},c=g=>{const y=g.charCodeAt(0);return y>=48&&y<=57},d=g=>g==="!"||u(g),h=g=>u(g)||c(g)||g===":"||g==="-",p=g=>u(g)||c(g)||g==="_"||g==="."||g===":"||g==="-",m=p;if(a>=l.length||!d(l[a]))return!1;for(a++;a=l.length)return!0;if(l[a]==="/"){for(a++;a=l.length}if(!p(l[a]))return!1;for(a++;a=l.length)return!0;const g=l[a];if(g==='"'||g==="'"){for(a++;a=l.length)return!0;a++}else{for(;a"||y==='"'||y==="'"||y==="`")break;a++}if(a>=l.length)return!0}}}return!0},i=(l,a)=>SW(l,a),o=String(e??""),s=o.lastIndexOf("<");if(s===-1||i(o,s))return o;if(s>0){const l=o[s-1],a=l===" "||l===" "||l===` -`||l==="\r",u=o[s-2];if(!a&&!((l==="n"||l==="r")&&u==="\\"))return o}const r=o.slice(s);return r.includes(">")||r.length>1&&(r[1]===" "||r[1]===" "||r[1]===` -`||r[1]==="\r")||!n(r)?o:o.slice(0,s)}function cN(e,t){if(e===t)return;const n=e.split(/\r?\n/),i=t.split(/\r?\n/),o=[];let s=0;for(let r=0;r{const l=Number.isFinite(r)?Math.max(0,Math.trunc(r)):0;if(lString(m??"").toLowerCase()).filter(Boolean));if(!n.size)return e;const i=m=>m===" "||m===" ",o=m=>{const g=m.charCodeAt(0);return g>=65&&g<=90||g>=97&&g<=122||g>=48&&g<=57||m==="_"||m==="-"||m===":"},s=m=>{if(!m)return!1;if(m[0]===" ")return!0;let g=0;for(let y=0;y=4)return!0;continue}if(b===" ")return!0;break}return!1},r=m=>{let g=!1,y=!1;for(let b=0;b")return b}return-1},l=m=>{let g=0;for(;g{if(s(m))return-1;const y=m.replace(/^[ \t]+/,"");if(!y||y.startsWith(">")||y.startsWith("|")||/^(?:[*+-]|\d+[.)])[\t ]+/.test(y))return-1;let b=!1,v=0;for(;v=M.length){b=!0,v++;continue}const T=M[N];if(T==="!"||T==="?"){b=!0,v+=w+1;continue}if(T==="/"){b=!0,v+=w+1;continue}const S=N;for(;N"&&A!=="/"){b=!0,v++;continue}const E=new RegExp(String.raw`<\s*\/\s*${x}\s*>`,"i"),I=/\/\s*>$/.test(M),R=E.test(m.slice(v+w+1)),W=E.test(e.slice(g+v+w+1)),z=/[\r\n]/.test(e.slice(g+v+w+1));if(b&&n.has(x)&&!I&&!R&&(W||z))return v;b=!0,v+=w+1}return-1};let u=!1,c="",d=0,h="",p=0;for(;pp&&e[m-1]==="\r",b=g?y?m-1:m:e.length,v=e.slice(p,b),C=g?y?`\r -`:` -`:"",w=l(v);let M=v;if(!u&&!w){const N=a(v,p);if(N!==-1){const T=C||` -`;M=`${v.slice(0,N).replace(/[ \t]+$/,"")}${T}${T}${v.slice(N).replace(/^[ \t]+/,"")}`}}h+=M,h+=C,w&&(u?w.markerChar===c&&w.markerLen>=d&&/^\s*$/.test(w.rest)&&(u=!1,c="",d=0):(u=!0,c=w.markerChar,d=w.markerLen)),p=g?m+1:e.length}return h}function R2e(e,t){if(!e||!t.length)return e;const n=new Set(t.map(d=>String(d??"").toLowerCase()));if(!n.size)return e;const i=d=>d===" "||d===" ",o=d=>{const h=d.charCodeAt(0);return h>=65&&h<=90||h>=97&&h<=122||h>=48&&h<=57||d==="_"||d==="-"},s=d=>{let h=0;for(;h{let h=!1,p=!1;for(let m=0;m")return m}return-1},l=(d,h,p)=>{const m=p.toLowerCase();let g=d.indexOf("<",h);for(;g!==-1;){let y=g+1;for(;y=d.length||d[y]!=="/"){g=d.indexOf("<",g+1);continue}for(y++;yd.length){g=d.indexOf("<",g+1);continue}let b=!0;for(let C=0;C="A"&&w<="Z"?String.fromCharCode(w.charCodeAt(0)+32):w)!==m[C]){b=!1;break}}if(!b){g=d.indexOf("<",g+1);continue}let v=y+m.length;if(v")return!0;g=d.indexOf("<",g+1)}return!1},a=d=>{let h=0;for(;h=d.length||d[h]!=="<")return d;for(h++;h=d.length||d[h]==="/")return d;const p=h;for(;hc&&e[d-1]==="\r",p=h?d-1:d,m=e.slice(c,p);u+=a(m),u+=h?`\r -`:` -`,c=d+1}return u}function O2e(e,t){if(!e||!t.length)return e;const n=new Set(t.map(h=>String(h??"").toLowerCase()));if(!n.size)return e;const i=h=>h===" "||h===" ",o=h=>{let p=0,m=!1,g=0;for(;p=h.length||h[p]!==">")break;for(m=!0,p++;p{let p=0;for(;pnew RegExp(String.raw`(<\s*\/\s*${h}\s*>)${"(?=[\\t ]*(?:#{1,6}[\\t ]+|>|(?:[*+-]|\\d+[.)])[\\t ]+|(?:`{3,}|~{3,})|\\||\\$\\$|:{3,}|\\[\\^[^\\]]+\\]:|(?:-{3,}|\\*{3,}|_{3,})))"}`,"gi"));let l=!1,a="",u=0,c="",d=0;for(;dd&&e[h-1]==="\r",g=p?m?h-1:h:e.length,y=e.slice(d,g),b=p?m?`\r -`:` -`:"",v=o(y),C=v?.prefix??"",w=v?.content??y,M=s(w);M&&(l?M.markerChar===a&&M.markerLen>=u&&/^\s*$/.test(M.rest)&&(l=!1,a="",u=0):(l=!0,a=M.markerChar,u=M.markerLen));let N=w;if(!l&&N.includes("{if(E.replace(/^[\t ]+/,"").startsWith("|"))return S;const I=E.slice(0,A).replace(/^[\t ]+/,"");if(I.length>0){const R=x.match(/^<\s*\/\s*([A-Z][\w:-]*)/i)?.[1]?.toLowerCase()??"",W=I.match(/^<\s*([A-Z][\w:-]*)/i)?.[1]?.toLowerCase()??"";if(!R||!W||R!==W)return S}return`${x} - -`});if(C){const T=C+N.split(` -`).join(` -${C}`);c+=T}else c+=N;c+=b,d=p?h+1:e.length}return c}function P2e(e,t){if(!e||!t.length)return e;const n=new Set(t.map(I=>String(I??"").toLowerCase()));if(!n.size)return e;const i=I=>I===" "||I===" ",o=I=>{if(!I)return!1;if(I[0]===" ")return!0;let R=0;for(let W=0;W=4)return!0;continue}if(z===" ")return!0;break}return!1},s=I=>{const R=I.charCodeAt(0);return R>=65&&R<=90||R>=97&&R<=122||R>=48&&R<=57||I==="_"||I==="-"||I===":"},r=I=>{let R=0;for(;R{let R=0,W=!1,z=0;for(;R=I.length||I[R]!==">")break;for(W=!0,R++;Rr(I).startsWith("<"),u=I=>{for(let R=0;R{if(o(I))return"";const R=r(I);if(!R.startsWith("<"))return"";let W=1;for(;W=R.length||R[W]==="/"||R[W]==="!"||R[W]==="?")return"";const z=W;for(;W"&&O!=="/"?"":F},d=I=>{if(o(I))return null;const R=r(I);if(!R.startsWith("<"))return null;let W=1;for(;W=R.length)return null;const z=R[W]==="/";if(z)for(W++;W"&&j!=="/")return null;if(z)return{type:"close",name:B};if(/\/\s*>\s*$/.test(R))return{type:"open",name:B,complete:!0};const $=R.indexOf(">",W);if($!==-1){const V=R.slice($+1);if(new RegExp(`<\\s*\\/\\s*${B}\\s*>`,"i").test(V))return{type:"open",name:B,complete:!0}}return{type:"open",name:B,complete:!1}},h=I=>{if(o(I))return null;const R=r(I).replace(/[ \t]+$/,"");if(!R.startsWith("<")||/^<\s*(?:!--|!doctype\b|\?)/i.test(R))return null;const W=R.match(/^<\s*([A-Z][\w:-]*)\b[^>]*\/\s*>\s*$/i);if(W?.[1])return W[1].toLowerCase();const z=R.match(/^<\s*([A-Z][\w:-]*)\b[^>]*>[\s\S]*<\s*\/\s*([A-Z][\w:-]*)\s*>\s*$/i);if(!z?.[1]||!z[2])return null;const F=z[1].toLowerCase();return F===z[2].toLowerCase()?F:null};let p=!1,m="",g=0;const y=I=>{let R=0;for(;Ry(I),v=I=>{const R=r(I);return R?o(I)?!0:/^(?:#{1,6}[ \t]+|>|[*+-][ \t]+|\d+[.)][ \t]+|`{3,}|~{3,}|\||\$\$|:{3,}|\[\^[^\]]+\]:|-{3,}|\*{3,}|_{3,})/.test(R):!1},C=(I,R,W)=>{let z=I,F=0;for(;zz&&e[O-1]==="\r",$=B?j?O-1:O:e.length,V=e.slice(z,$),ne=l(V),K=ne?.key??"";if(F>0&&R&&K!==R)break;const ee=ne?.content??V,ue=d(ee);if(ue?.name===W){if(ue.type==="open")ue.complete||F++;else if(F>0&&(F--,F===0))return!1}else if(F>0&&(u(ee)||v(ee)))return!0;if(B)z=O+1;else break}return!1};let w="",M=0,N=!0,T=!1,S=!1,x=` -`;const A=[];let E="";for(;MM&&e[I-1]==="\r",z=R?W?I-1:I:e.length,F=e.slice(M,z),O=R?W?`\r -`:` -`:"",B=l(F),j=B?.key??"",$=B?.content??F,V=b($);V&&(p?V.markerChar===m&&V.markerLen>=g&&/^\s*$/.test(V.rest)&&(p=!1,m="",g=0):(p=!0,m=V.markerChar,g=V.markerLen));const ne=A.length>0;if(!p&&!ne){const ee=c($),ue=!!ee&&!N&&T&&S&&C(M,j,ee);ee&&!N&&(!T||ue)&&(j&&E&&j===E?w+=`${j}${x}`:j||(w+=x))}if(w+=F,w+=O,O&&(x=O),!p){const ee=d($);if(ee){if(ee.type==="open")ee.complete||A.push(ee.name);else for(let ue=A.length-1;ue>=0;ue--)if(A[ue]===ee.name){A.length=ue;break}}}const K=u($);N=K,T=!K&&a($),S=!K&&!!h($),E=j,M=R?I+1:e.length}return w}function $2e(e){let t=!1,n="",i=0,o=!1,s=!1,r=!1,l=0;const a=(c,d)=>{const h=hx(c);if(h){t?h.markerChar===n&&h.markerLen>=i&&/^\s*$/.test(h.rest)&&(t=!1,n="",i=0):(t=!0,n=h.markerChar,i=h.markerLen);return}if(t)return;let p=0;for(;p{for(;l=c?c:d,p=h>l&&e[h-1]==="\r"?h-1:h;if(a(e.slice(l,p)),d===-1||d>=c){l=c;break}r=!1,l=d+1}},inMath:()=>o||s||r}}function K8(e,t,n,i){let o=e.replace(/([^\\])\r(ight|ho)/g,"$1\\r$2");const s=$2e(o);if(o=o.replace(/([^\\])\r?\n(abla|eq|ot|exists)/g,(r,l,a,u)=>{s.scanTo(u+1);const c=s.inMath();return s.scanTo(u+r.length),c?`${l}\\n${a}`:r}),t||(o.endsWith("- *")&&(o=o.replace(/- \*$/,"- \\*")),/(?:^|\n)\s*-\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*-\s*$/,r=>r.startsWith(` -`)?` -`:""):/(?:^|\n)\s*--\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*--\s*$/,r=>r.startsWith(` -`)?` -`:""):/(?:^|\n)\s*>\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*>\s*$/,r=>r.startsWith(` -`)?` -`:""):/\n\s*[*+]\s*$/.test(o)?o=o.replace(/\n\s*[*+]\s*$/,` -`):/(?:^|\n)\s*\d+\s*$/.test(o)?/^\d+$/.test(o.trim())||(o=o.replace(/(?:^|\n)\s*\d+\s*$/,r=>r.startsWith(` -`)?` -`:"")):/(?:^|\n)\s*\d+[.)]\s+\*{1,3}\s*$/.test(o)?o=o.replace(/((?:^|\n)\s*\d+[.)]\s+)(\*{1,3})\s*$/,(r,l,a)=>`${l}${a.split("").map(()=>"\\*").join("")}`):/(?:^|\n)\s*\d+[.)]\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*\d+[.)]\s*$/,r=>r.startsWith(` -`)?` -`:""):/\n[[(]\n*$/.test(o)&&(o=o.replace(/(\n\[|\n\()+\n*$/g,` -`)),o=o2e(o,i.customHtmlTags)??o),i.customHtmlTags?.length&&o.includes("<")){const r=kp(i.customHtmlTags);if(r.length&&(o=F2e(o,r),o=R2e(o,r),o=P2e(o,r),o=O2e(o,r),o.includes("[\t ]*)(\r?\n)(?![\t ]*\r?\n|$)`,"gim");o=o.replace(a,"$1$2$2")}}return t||(o=D2e(o)),o}function B2e(e,t,n,i){const o=e,s=`${n?"final":"stream"}:${(i.customHtmlTags??[]).join(",")}`,r=aA.get(o);let l;if(!n&&!i.customHtmlTags?.length&&r&&r.mode===s&&t.length>=r.source.length&&t.startsWith(r.source)){const a=Math.max(0,r.source.length-Rve-Ove),u=K8(t.slice(a),n,e,i),c=r.source.length-a;l=u.length>=c&&u.slice(0,c)===r.safeMarkdown.slice(-c)?r.safeMarkdown.slice(0,r.safeMarkdown.length-c)+u:K8(t,n,e,i)}else l=K8(t,n,e,i);return n||(l=s2e(l,e)),aA.set(o,{source:t,safeMarkdown:l,mode:s}),l}function NW(e,t,n={}){const i=kW(n),o=i?uu():0,s=!!n.final,r=(e??"").toString();Gve(t,n)&&(t.stream.reset(),Qve(t),aA.delete(t));const l=B2e(t,r,s,n);i&&Xd(i,"safeMarkdownMs",uu()-o);const a=p2e(l);if(a){if(n.includeSourceMap){const M={...n,__sourceLineMapper:cN(r,l)};a[0].sourceMap=_v(l,0,l.length,M)}const C=n.preTransformTokens,w=n.postTransformTokens;if(ux(t,n)||typeof C=="function"||typeof w=="function"){const M=oN(t,l,{__markstreamFinal:s},n),N=typeof C=="function"&&C(M)||M;typeof w=="function"&&w(N)}return JL(a,n,i,o)}const u=i?uu():0,c=oN(t,l,{__markstreamFinal:s},n);if(i&&Xd(i,"tokenizeMs",uu()-u),!c||!Array.isArray(c))return JL([],n,i,o);const d=n.preTransformTokens,h=n.postTransformTokens;let p=c;d&&typeof d=="function"&&(p=d(p)||p);const m=t,g=typeof m.validateLink=="function"&&m.__markstreamOriginalValidateLink&&m.validateLink!==m.__markstreamOriginalValidateLink?m.validateLink:void 0,y=n.validateLink??g??m.options?.validateLink??(typeof m.validateLink=="function"?m.validateLink:void 0),b={...n,validateLink:y,__markdownIt:t,__sourceLineMapper:n.includeSourceMap===!0?cN(r,l):void 0,__sourceMarkdown:l,__customHtmlBlockCursor:0};let v=Uve(t,l,p,b,i);if(h&&typeof h=="function"){const C=h(p);if(Array.isArray(C)){const w=C[0],M=w?.type;w&&typeof M=="string"?v=f1(C,{...b,__customHtmlBlockCursor:0},i):v=C}}if(M2e(v)){const C=i?uu():0;v=N2e(v,s,l,b),v=LW(v,l,t,b,s)[0],v=I2e(v,t,b,s),i&&Xd(i,"htmlBlockPassesMs",uu()-C)}if(s){const C=new WeakSet,w=M=>{if(!M||typeof M!="object"||C.has(M))return;if(C.add(M),Array.isArray(M)){for(const T of M)w(T);return}const N=M;N.type==="html_block"&&N.loading===!0&&(N.loading=!1);for(const T of Object.values(N))w(T)};w(v)}return v=wW(v,n),n.debug&&console.log("Parsed Markdown Tree Structure:",v),bW(v,i,o)}function dN(e,t){if(!e||!Array.isArray(e))return[];const n=[],i=Ff(t),o=t?.__linkifyDemotionSeed;if(Array.isArray(o)&&o.length)for(const l of o)i.remember(String(l??""));const s=t?.includeSourceMap===!0;let r=0;for(;rd.type==="html_block")){if(s)for(const d of c)Ei(d,a,t);for(const d of c)Ou(d,a,t);n.push(...c)}else{const d={type:"paragraph",raw:u,children:c};s&&Ei(d,a,t);const h=lN(d,t);if(h){s&&rN(h,d);for(const p of h)Ou(p,a,t);n.push(...h)}else Ou(d,a,t),n.push(d)}i.remember(u)}r+=1;break;default:r+=1;break}}return n}const z2e=/\\([ \\!"#$%&'()*+,./:;<=>?@[\]^_`{|}~-])/g,N0=/\d/u,j2e=/[,.!?;:,。;、!?:]/u,H2e=/\d\p{Script=Han}{1,3}$/u;function W2e(e){return e.pos>0&&e.pos+1{const u=l,c=u.posMax,d=u.pos;if(u.src.charCodeAt(d)!==r||a||s.refuseDigitRange&&W2e(u))return!1;u.pos=d+1;let h=!1;for(;u.pos]|$)/i,K2e=new Set([...i2,"base","button","datalist","dialog","embed","fieldset","form","iframe","input","legend","link","meta","object","optgroup","option","output","param","select","style","template","textarea","title"]),Z2e=new Set(["a","abbr","b","blockquote","br","caption","code","col","colgroup","dd","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","mark","ol","p","picture","pre","s","small","source","span","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","ul"]);function fN(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function G2e(e){return typeof e=="string"?e:e==null?"":String(e)}function DW(e){return/^[^\s"'<>`=]+$/.test(e)&&!/^on/i.test(e)}function jd(e){return G2e(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function FW(e){return jd(e).replace(/`/g,"`")}function I4(e){return String(e??"").trim().toLowerCase()}function mx(e,t="safe"){const n=I4(e);return n?t==="escape"?!0:t==="trusted"?i2.has(n):!Z2e.has(n):!1}function RW(e,t="safe"){const n=I4(e);return n?t==="escape"?!0:t==="trusted"?i2.has(n):K2e.has(n):!1}function hN(e){const t=Object.entries(e);return t.length===0?"":t.map(([n,i])=>i===""?` ${n}`:` ${n}="${FW(i)}"`).join("")}function OW(e){const t=e.startsWith("/"),n=t?e.slice(1):e,i=n.match(V2e);return i?{attrsStr:t?"":n.slice(i[0].length).trimStart(),isClosing:t,isSelfClosing:!t&&e.trimEnd().endsWith("/"),tagName:i[1]}:null}function Q2e(e,t){const n=e.split(",").map(i=>i.trim()).filter(Boolean);return n.length===0?!1:n.some(i=>{const o=i.split(/\s+/,1)[0]??"";return!o||Wh(o,{tagName:t,attrName:"srcset"})})}function PW(e,t,n,i){return N1e.has(e)||n==="safe"&&e==="style"?!0:e==="srcset"?Q2e(t,i):!!(D1e.has(e)&&t&&Wh(t,{tagName:i,attrName:e}))}function wh(e,t){const n=t.toLowerCase();return Object.keys(e).find(i=>i.toLowerCase()===n)}function $W(e,t,n,i=!1){if(t!=="safe"||I4(n)!=="a")return e;const o=wh(e,"href");if(i&&(!o||!e[o])){const a=wh(e,"target"),u=wh(e,"rel");return a&&delete e[a],u&&delete e[u],e}const s=wh(e,"target");if((s?String(e[s]).trim():"").toLowerCase()!=="_blank")return e;const r=wh(e,"rel"),l=new Set(String(r?e[r]:"").split(/\s+/).map(a=>a.trim()).filter(Boolean).filter(a=>a.toLowerCase()!=="opener"));return l.add("noopener"),l.add("noreferrer"),r&&r!=="rel"&&delete e[r],e.rel=Array.from(l).join(" "),e}function pN(e,t="safe",n){const i={};for(const[o,s]of Object.entries(e)){const r=o.trim(),l=r.toLowerCase();!r||!DW(r)||PW(l,s,t,n)||(i[r]=s)}return $W(i,t,n,!!wh(e,"href"))}function BW(e,t){const n=e.toLowerCase();return MH.has(n)?!1:fN(t,n)||fN(t,e)}function gx(e,t="safe",n){const i={};for(const[o,s]of Object.entries(e)){const r=o.trim(),l=r.toLowerCase();!r||!DW(r)||PW(l,s,t,n)||(i[r]=s)}return $W(i,t,n,!!wh(e,"href"))}function D0(e){const t={};if(!Array.isArray(e)||e.length===0)return t;for(const[n,i]of e)n&&(t[String(n)]=i==null?"":String(i));return t}function b9(e,t="safe",n){const i=gx(D0(e),t,n),o=Object.entries(i).map(([s,r])=>[s,r]);return o.length>0?o:void 0}function Y2e(e,t){const n=t.toLowerCase();if(["checked","disabled","readonly","required","autofocus","multiple","hidden"].includes(n))return e==="true"||e===""||e===t;if(["value","min","max","step","width","height","size","maxlength"].includes(n)){const i=Number(e);if(e!==""&&!Number.isNaN(i))return i}return e}function J2e(e){const t={};for(const[n,i]of Object.entries(e))t[n]=Y2e(i,n);return t}function Z8(e){return e.trim().length>0}function zW(e){const t=[];let n=0;for(;n",n);if(r!==-1){n=r+3;continue}break}const i=e.indexOf("<",n);if(i===-1){if(nn){const r=e.slice(n,i);Z8(r)&&t.push({type:"text",content:r})}if(e.startsWith("![CDATA[",i+1)){const r=e.indexOf("]]>",i);if(r!==-1){t.push({type:"text",content:e.slice(i,r+3)}),n=r+3;continue}break}if(e.startsWith("!",i+1)){const r=e.indexOf(">",i);if(r!==-1){n=r+1;continue}break}const o=e.indexOf(">",i);if(o===-1)break;const s=OW(e.slice(i+1,o));if(!s){const r=e.slice(i,o+1);Z8(r)&&t.push({type:"text",content:r}),n=o+1;continue}if(s.isClosing)t.push({type:"tag_close",tagName:s.tagName});else{const r={};if(s.attrsStr){const l=/([^\s=]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S*)))?/g;let a;for(;(a=l.exec(s.attrsStr))!==null;){const u=a[1],c=a[2]??a[3]??a[4]??"";u&&!u.endsWith("/")&&(r[u]=c)}}t.push({type:s.isSelfClosing||mf.has(s.tagName.toLowerCase())?"self_closing":"tag_open",tagName:s.tagName,attrs:r})}n=o+1}return t}function X2e(e){const t=[];let n=0;for(;n",n);if(l!==-1){n=l+3;continue}break}const i=e.indexOf("<",n);if(i===-1){nn&&t.push({type:"text",content:e.slice(n,i)}),e.startsWith("![CDATA[",i+1)){const l=e.indexOf("]]>",i);if(l!==-1){t.push({type:"text",content:e.slice(i,l+3)}),n=l+3;continue}break}if(e.startsWith("!",i+1)){const l=e.indexOf(">",i);if(l!==-1){n=l+1;continue}break}const o=e.indexOf(">",i);if(o===-1)break;const s=OW(e.slice(i+1,o));if(!s){t.push({type:"text",content:e.slice(i,o+1)}),n=o+1;continue}if(s.isClosing){t.push({type:"tag_close",tagName:s.tagName}),n=o+1;continue}const r={};if(s.attrsStr){const l=/([^\s=]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S*)))?/g;let a;for(;(a=l.exec(s.attrsStr))!==null;){const u=a[1],c=a[2]??a[3]??a[4]??"";u&&!u.endsWith("/")&&(r[u]=c)}}t.push({type:s.isSelfClosing||mf.has(s.tagName.toLowerCase())?"self_closing":"tag_open",tagName:s.tagName,attrs:r}),n=o+1}return t}function eye(e){const t=String(e.tagName??"").trim();if(!t)return"";if(e.type==="tag_close")return`</${jd(t)}>`;const n=Object.entries(e.attrs??{}).map(([i,o])=>o===""?` ${jd(i)}`:` ${jd(i)}="${FW(o)}"`).join("");return e.type==="self_closing"?`<${jd(t)}${n} />`:`<${jd(t)}${n}>`}function tye(e,t){if(!e||!e.includes("<")||!t||Object.keys(t).length===0)return!1;for(const n of zW(e))if((n.type==="tag_open"||n.type==="self_closing")&&BW(n.tagName??"",t))return!0;return!1}function K1(e,t="safe"){if(!e)return"";if(t==="escape")return jd(e);const n=X2e(e),i=[],o=[],s=[];for(const r of n){if(r.type==="text"){s.length===0&&o.push(jd(r.content??""));continue}const l=I4(r.tagName);if(!l)continue;if(RW(l,t)){r.type==="tag_open"?s.push(l):r.type==="tag_close"&&s[s.length-1]===l&&s.pop();continue}if(s.length>0)continue;if(t==="safe"&&mx(l,t)){o.push(eye(r));continue}if(r.type==="self_closing"){o.push(`<${l}${hN(pN(r.attrs??{},t,l))}>`);continue}if(r.type==="tag_open"){o.push(`<${l}${hN(pN(r.attrs??{},t,l))}>`),mf.has(l)||i.push(l);continue}const a=i.lastIndexOf(l);if(a===-1)continue;for(;i.length>a+1;){const c=i.pop();c&&o.push(``)}const u=i.pop();u&&o.push(``)}for(;i.length>0;){const r=i.pop();r&&o.push(``)}return o.join("")}const nye=[/javascript:/i,/vbscript:/i,/data:text\/html/i,/expression\s*\(/i,/@import/i],mN="http://www.w3.org/2000/svg",iye=new Set(["script","style","iframe","object","embed","link","meta"]),oye=new Set(["svg","style","g","a","defs","marker","path","rect","circle","ellipse","line","polyline","polygon","text","tspan","title","desc","use","image","lineargradient","radialgradient","stop","clippath","mask","pattern"]),sye=new Set(["href","xlink:href","src","srcdoc","action","data","formaction","poster"]),rye=new Set(["clip-path","fill","filter","marker-end","marker-mid","marker-start","mask","stroke"]),lye=new Set(["circle","ellipse","image","line","path","polygon","polyline","rect","text","tspan","use"]);function aye(e){return(e.getAttribute("href")||e.getAttribute("xlink:href"))?.startsWith("#")===!0}function uye(e){return!!(e.getAttribute("href")||e.getAttribute("xlink:href")||e.getAttribute("src"))}function cye(e){const t=e.nodeName.toLowerCase();return t==="use"?aye(e):t==="image"?uye(e):t==="text"||t==="tspan"?!!e.textContent?.trim():lye.has(t)}function dye(e){return e.replace(/(["'])\s*javascript:/gi,"$1#").replace(/\bjavascript:/gi,"#").replace(/(["'])\s*vbscript:/gi,"$1#").replace(/\bvbscript:/gi,"#").replace(/\bdata:text\/html/gi,"#")}function fye(e,t,n){const i=e.toLowerCase(),o=t.toLowerCase(),s=String(n??"").trim();return s?(i==="use"||i==="marker"||i==="clippath"||i==="mask")&&(o==="href"||o==="xlink:href")?s.startsWith("#")?s:"":i==="a"&&(o==="href"||o==="xlink:href")?Wh(s,{tagName:"a",attrName:"href"})?"":s:i==="image"&&(o==="href"||o==="xlink:href"||o==="src")?Wh(s,{tagName:"img",attrName:"src"})?"":s:o==="href"||o==="xlink:href"?s.startsWith("#")?s:"":Wh(s,{tagName:i,attrName:o})?"":s:""}function hye(e,t){let n=t+4;for(;n{const i=n.trim();if(/^[0-9a-f]+$/i.test(i)){const o=Number.parseInt(i,16);try{return Number.isFinite(o)?String.fromCodePoint(o):""}catch{return""}}return String(n).trim()})}function HW(e){const t=jW(e),n=t.toLowerCase();let i=0;for(;in.test(t))||HW(t)}function pye(e){if(e.tagName.toLowerCase()!=="a"||e.getAttribute("target")?.trim().toLowerCase()!=="_blank")return;const t=new Set(String(e.getAttribute("rel")??"").split(/\s+/).map(n=>n.trim()).filter(Boolean).filter(n=>n.toLowerCase()!=="opener"));t.add("noopener"),t.add("noreferrer"),e.setAttribute("rel",Array.from(t).join(" "))}function yy(e){const t=Number.parseFloat(String(e??""));return Number.isFinite(t)?t:0}function WW(e,t){if(e.nodeType===Node.TEXT_NODE){const o=e.textContent??"";o&&t.push(o);return}if(e.nodeType!==Node.ELEMENT_NODE)return;const n=e,i=n.tagName.toLowerCase();if(!iye.has(i)){if(i==="br"){t.push(` -`);return}for(const o of Array.from(n.childNodes))WW(o,t)}}function mye(e){for(const t of Array.from(e.querySelectorAll("foreignObject"))){const n=[];WW(t,n);const i=n.join("").split(/\r?\n/).map(c=>c.trim()).filter(Boolean);if(!i.length){t.remove();continue}const o=yy(t.getAttribute("width")),s=yy(t.getAttribute("height")),r=yy(t.getAttribute("x")),l=yy(t.getAttribute("y")),a=e.ownerDocument.createElementNS(mN,"text");a.setAttribute("x",String(r+o/2)),a.setAttribute("y",String(l+s/2)),a.setAttribute("text-anchor","middle"),a.setAttribute("dominant-baseline","central");const u=t.querySelector(".nodeLabel");if(u?.getAttribute("class")&&a.setAttribute("class",u.getAttribute("class")),i.length===1)a.textContent=i[0];else{const c=-.6*(i.length-1);for(const[d,h]of i.entries()){const p=e.ownerDocument.createElementNS(mN,"tspan");p.setAttribute("x",String(r+o/2)),p.setAttribute("dy",d===0?`${c}em`:"1.2em"),p.textContent=h,a.appendChild(p)}}t.parentNode?.replaceChild(a,t)}}function gye(e){mye(e);const t=[e,...Array.from(e.querySelectorAll("*"))];for(const n of t){const i=n.tagName.toLowerCase();if(!oye.has(i)){n.remove();continue}if(i==="style"&&gN(n.textContent??"")){n.remove();continue}const o=Array.from(n.attributes);for(const s of o){const r=s.name.toLowerCase();if(/^on/i.test(r)){n.removeAttribute(s.name);continue}if(r==="style"&&s.value&&gN(s.value)){n.removeAttribute(s.name);continue}if(r==="srcdoc"){n.removeAttribute(s.name);continue}if(sye.has(r)&&s.value){const l=fye(i,r,s.value);if(!l){n.removeAttribute(s.name);continue}l!==s.value&&n.setAttribute(s.name,l);continue}if(rye.has(r)&&s.value&&HW(s.value)){n.removeAttribute(s.name);continue}if(s.value){const l=dye(s.value);l!==s.value&&n.setAttribute(s.name,l)}}pye(n)}}function s8t(e){if(typeof DOMParser>"u"||!e)return null;try{const t=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(!t||t.nodeName.toLowerCase()!=="svg")return null;const n=t;return gye(n),vye(n)?null:n}catch{return null}}function vye(e){const t=e.getAttribute("viewBox");if(t){const o=t.trim().split(/[\s,]+/);if(o.length===4){const s=Number.parseFloat(o[2]||""),r=Number.parseFloat(o[3]||"");if(!Number.isFinite(s)||!Number.isFinite(r)||s<=0||r<=0)return!0}}const n=[e,...Array.from(e.querySelectorAll("*"))];let i=!1;for(const o of n){cye(o)&&(i=!0);for(const s of Array.from(o.attributes))if(/\bNaN\b/i.test(s.value)||s.name==="style"&&/max-width:\s*0(?:px)?/i.test(s.value))return!0}return!i}const ky=[];function G8(e){return String(e??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function yye(e){return(String(e||"text").trim().split(/\s+/)[0]||"text").replace(/[^\w+.#:-]/g,"-").replace(/-+/g,"-")||"text"}function kye(e){return e.replace(/[^\w:.+-]/g,"-").replace(/-+/g,"-")}function vN(e=`editor-${Date.now()}`,t={}){const n=Yge(t),i=n;i.__markstreamRegisteredPluginCount=ky.length,i.__markstreamHasCustomParserExtensions=!!(t.plugin?.length||t.apply?.length||ky.length);const o={"common.copy":"Copy"};let s;if(typeof t.i18n=="function")s=t.i18n;else if(t.i18n&&typeof t.i18n=="object"){const p=t.i18n;s=m=>p[m]??o[m]??m}else s=p=>o[p]??p;if(Array.isArray(t.plugin))for(const p of t.plugin){const m=p;if(Array.isArray(m)){const[g,...y]=m;typeof g=="function"&&n.use(g,...y)}else typeof m=="function"&&n.use(m)}if(Array.isArray(t.apply))for(const p of t.apply)try{p(n)}catch(m){console.error("[getMarkdown] apply function threw an error",m)}if(ky.length)for(const p of ky)if(Array.isArray(p)){const[m,...g]=p;typeof m=="function"&&n.use(m,...g)}else typeof p=="function"&&n.use(p);n.use(U2e),n.use(vde),n.use(pde);const r=Ede,l=r.default??r;n.use(l),n.use(hde),n.use(fde),n.core.ruler.after("block","mark_fence_closed",p=>{const m=p,g=m.src,y=!!m.env?.__markstreamFinal,b=g.split(/\r?\n/);for(const v of m.tokens){if(v.type!=="fence"||!v.map||!v.markup)continue;const C=v.map[0],w=v.map[1],M=v.markup,N=M[0],T=M.length,S=b[Math.max(0,w-1)]??"";let x=0;for(;xC+1&&A>=T&&E===S.length,R=v;R.meta=R.meta??{},R.meta.unclosed=!I,R.meta.closed=!!I}}),n.renderer.rules.fence=(p,m)=>{const g=p[m],y=String(g.info??"").trim(),b=String(g.content??""),v=btoa(unescape(encodeURIComponent(b))),C=yye(y),w=G8(C),M=kye(`editor-${e}-${m}-${C}`),N=G8(s("common.copy"));return`
    -
    - ${G8(C.toUpperCase())} - -
    -
    -
    `};const a=/^\[(\d+)\]/,u=/^\[([^\]\n]+)\]/,c=p=>{if(!p.startsWith("["))return!1;const m=u.exec(p);if(!m)return p!=="["&&!/^\[\d+$/.test(p);const g=String(m[1]??"");return p.slice(m[0].length).startsWith("(")?!1:!/^\d+$/.test(g)},d=(p,m)=>{const g=p;if(g.src[g.pos]!=="[")return!1;const y=a.exec(g.src.slice(g.pos));if(!y)return!1;const b=g.src.slice(Math.max(0,g.pos-120),g.pos);if(/"[^"\n]{1,80}"\s*:\s*$/.test(b))return!1;const v=g.src.slice(g.pos+y[0].length);if(v.startsWith("](")||v.startsWith("(")||c(v))return!1;if(!m){const C=y[1],w=g.push("reference","span",0);w.content=C,w.markup=y[0],w.raw=y[0]}return g.pos+=y[0].length,!0};n.inline.ruler.before("escape","reference",d),n.renderer.rules.reference=(p,m)=>{const y=String(p[m].content??"");return`${y}`};const h=n.use.bind(n);return n.use=((...p)=>(i.__markstreamHasCustomParserExtensions=!0,h(...p))),n}const bye="modulepreload",wye=function(e){return"/"+e},yN={},_s=function(t,n,i){let o=Promise.resolve();if(n&&n.length>0){let r=function(u){return Promise.all(u.map(c=>Promise.resolve(c).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),a=l?.nonce||l?.getAttribute("nonce");o=r(n.map(u=>{if(u=wye(u),u in yN)return;yN[u]=!0;const c=u.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=c?"stylesheet":bye,c||(h.as="script"),h.crossOrigin="",h.href=u,a&&h.setAttribute("nonce",a),document.head.appendChild(h),c)return new Promise((p,m)=>{h.addEventListener("load",p),h.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function s(r){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=r,window.dispatchEvent(l),!l.defaultPrevented)throw r}return o.then(r=>{for(const l of r||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})};function Cye({nextContent:e,previousContent:t,typewriterEnabled:n}){return n?e===t?{settledContent:e,streamedDelta:"",appended:!1}:t&&e.startsWith(t)&&e.length>t.length?{settledContent:t,streamedDelta:e.slice(t.length),appended:!0}:{settledContent:e,streamedDelta:"",appended:!1}:{settledContent:e,streamedDelta:"",appended:!1}}function qW({nextContent:e,persistedContent:t,currentState:n,typewriterEnabled:i,streamRenderVersionChanged:o=!1}){const s=`${n.settledContent}${n.streamedDelta}`;return i?n.streamedDelta&&s===e?o?{settledContent:s,streamedDelta:"",appended:!1}:{settledContent:n.settledContent,streamedDelta:n.streamedDelta,appended:!1}:Cye({nextContent:e,previousContent:t??s,typewriterEnabled:i}):{settledContent:e,streamedDelta:"",appended:!1}}const Aye={plain:"plaintext",text:"plaintext",txt:"plaintext",js:"javascript",mjs:"javascript",cjs:"javascript",ts:"typescript",mts:"typescript",cts:"typescript",golang:"go",py:"python",rb:"ruby",rs:"rust",kt:"kotlin",kts:"kotlin",md:"markdown",yml:"yaml",sh:"shellscript",bash:"shellscript",zsh:"shellscript",shell:"shellscript",shellscript:"shellscript",ps:"powershell",ps1:"powershell",pwsh:"powershell","c++":"cpp","c#":"csharp",cs:"csharp",objc:"objective-c",objectivec:"objective-c","objective-c":"objective-c",objectivecpp:"objective-cpp","objective-c++":"objective-cpp","objective-cpp":"objective-cpp"};function xye(e){const t=String(e??"").trim();if(!t)return"";const[n=""]=t.split(/\s+/);return n.split(":")[0]?.trim().toLowerCase()??""}function UW(e){const t=xye(e);return Aye[t]??t}function Sye(e){if(!Array.isArray(e))return;const t=e.filter(i=>typeof i=="string").map(i=>UW(i)).filter(Boolean),n=Array.from(new Set(t)).sort();return n.length>0?n:void 0}function _ye(e){if(!Array.isArray(e))return;const t=[],n=new Set;for(const i of e){if(typeof i!="string")continue;const o=i.trim();!o||n.has(o)||(n.add(o),t.push(o))}return t.length>0?t:void 0}function Iye(e){return _ye(e)?.join("\0")??""}function Mye(e,t){return`${Iye(e)}\0\0${Sye(t)?.join("\0")??""}`}function Gp(e,t,n=1){const i=Number(e);return Number.isFinite(i)?Math.max(n,i):t}function kN(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}var Tye=class{constructor(e={},t){this.source="",this.visible="",this.done=!1,this.paused=!1,this.listeners=new Set,this.rafId=0,this.startedAt=0,this.lastTick=0,this.charBudget=0,this.hasStarted=!1,this.destroyed=!1,this.getSnapshot=()=>({source:this.source,visible:this.visible,done:this.done,paused:this.paused,pendingChars:this.pendingChars,caughtUp:this.caughtUp,final:this.final}),this.subscribe=d=>this.destroyed?()=>{}:(this.listeners.add(d),()=>{this.listeners.delete(d)}),this.enqueue=d=>{if(this.destroyed||!d)return;this.done&&(this.done=!1);const h=this.source.length>0,p=this.pendingChars<=0;if(this.source+=d,p){const m=bN();this.startedAt=h&&this.hasStarted?m-this.normalizedStartDelayMs:m,this.lastTick=m,this.charBudget=0}this.hasStarted=!0,this.emit(),this.ensureLoop()},this.finish=(d={})=>{if(!this.destroyed){if(this.done=!0,d.flush??this.flushOnFinish){this.visible=this.source,this.charBudget=0,this.currentCps=this.minCharsPerSecond,this.cancelLoop(),this.emit();return}this.emit(),this.ensureLoop()}},this.flush=()=>{this.destroyed||(this.visible=this.source,this.charBudget=0,this.currentCps=this.minCharsPerSecond,this.cancelLoop(),this.emit())},this.reset=(d="")=>{this.destroyed||(this.cancelLoop(),this.source=d,this.visible=d,this.done=!1,this.paused=!1,this.hasStarted=!1,this.startedAt=0,this.lastTick=0,this.charBudget=0,this.currentCps=this.minCharsPerSecond,this.emit())},this.pause=()=>{this.destroyed||this.paused||(this.paused=!0,this.cancelLoop(),this.emit())},this.resume=()=>{if(this.destroyed||!this.paused)return;this.paused=!1;const d=bN();this.lastTick=d,this.startedAt||=d,this.emit(),this.ensureLoop()},this.destroy=()=>{this.destroyed||(this.destroyed=!0,this.cancelLoop(),this.listeners.clear())},this.dispose=()=>{this.destroy()},this.tick=d=>{if(this.rafId=0,this.destroyed||this.paused)return;if(this.pendingChars<=0){this.startedAt=0,this.lastTick=0,this.charBudget=0,this.currentCps=this.minCharsPerSecond;return}if(d-this.startedAtthis.normalizedCatchUpThreshold?this.normalizedCatchUpLatencyMs:this.normalizedTargetLatencyMs,y=Dye(m/Math.max(.001,g/1e3),this.minCharsPerSecond,this.maxCharsPerSecond);if(this.currentCps+=(y-this.currentCps)*.2,this.charBudget+=this.currentCps*(p/1e3),this.charBudget<1){this.ensureLoop();return}const b=Math.min(Math.floor(this.charBudget),this.maxCharsPerCommit),v=Nye(this.source.slice(this.visible.length),b,this.segmenter);v.text&&(this.visible+=v.text,this.charBudget=Math.max(0,this.charBudget-v.graphemeCount),this.emit()),this.ensureLoop()};const{minCharsPerSecond:n=40,maxCharsPerSecond:i=1e3,targetLatencyMs:o=900,catchUpLatencyMs:s=350,catchUpThreshold:r=600,maxCommitFps:l=30,startDelayMs:a=80,maxCharsPerCommit:u=80,flushOnFinish:c=!1}=e;this.minCharsPerSecond=Gp(n,40,1),this.maxCharsPerSecond=Math.max(this.minCharsPerSecond,Gp(i,1e3,1)),this.normalizedTargetLatencyMs=Gp(o,900,1),this.normalizedCatchUpLatencyMs=Gp(s,350,1),this.normalizedCatchUpThreshold=kN(r,600),this.normalizedStartDelayMs=kN(a,80),this.maxCommitFps=Math.trunc(Gp(l,30,1)),this.maxCharsPerCommit=Math.trunc(Gp(u,80,1)),this.flushOnFinish=c,this.segmenter=Lye(),t&&this.listeners.add(t),this.currentCps=this.minCharsPerSecond}get pendingChars(){return Math.max(0,this.source.length-this.visible.length)}get caughtUp(){return this.pendingChars===0}get final(){return this.done&&this.caughtUp}ensureLoop(){if(!(this.destroyed||this.rafId||this.paused||this.pendingChars<=0)){if(typeof requestAnimationFrame!="function"){this.flush();return}this.rafId=requestAnimationFrame(this.tick)}}cancelLoop(){this.rafId&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.rafId),this.rafId=0)}emit(){if(!this.destroyed)for(const e of this.listeners)e()}};function Eye(e={},t){const n=new Tye(e,t);return{getSnapshot:n.getSnapshot,subscribe:n.subscribe,enqueue:n.enqueue,finish:n.finish,flush:n.flush,reset:n.reset,pause:n.pause,resume:n.resume,destroy:n.destroy,dispose:n.dispose}}function Lye(){if(typeof Intl>"u")return null;const e=Intl.Segmenter;return e?new e(void 0,{granularity:"grapheme"}):null}function Nye(e,t,n){if(!e||t<=0)return{text:"",graphemeCount:0};if(!n){const s=Array.from(e).slice(0,t);return{text:s.join(""),graphemeCount:s.length}}let i="",o=0;for(const s of n.segment(e)){if(o>=t)break;i+=s.segment,o++}return{text:i,graphemeCount:o}}function bN(){return typeof performance<"u"?performance.now():Date.now()}function Dye(e,t,n){return Math.min(n,Math.max(t,e))}var Fye=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});const cA=Symbol.for("markstream-vue:node-lifecycle");function r8t(){}const vx=new Map;let VW="material";const C1=new Map,wN=new Map;let dA=null;function Rye(e){vx.set(e.id,e)}function Oye(e){const t=vx.get(VW);if(!t)return;const n=t.core[e];if(n)return n;const i=C1.get(t.id);if(i){const o=i[e];if(o)return o}t.loadExtended&&!C1.has(t.id)&&$ye(t)}function Pye(){var e,t;return(t=(e=vx.get(VW))==null?void 0:e.fallback)!=null?t:""}function $ye(e){return Fye(this,null,function*(){var t,n,i;if(C1.has(e.id))return(t=C1.get(e.id))!=null?t:null;let o=wN.get(e.id);return o||(o=((i=(n=e.loadExtended)==null?void 0:n.call(e))!=null?i:Promise.resolve(null)).then(s=>(C1.set(e.id,s),dA?.(),s)).catch(()=>(C1.set(e.id,null),null)),wN.set(e.id,o)),o})}const CN='',AN='',Bye={id:"material",core:{"":AN,plain:'',text:AN,javascript:'',typescript:'',jsx:'',tsx:'',html:'',css:'',scss:'',json:'',python:'',ruby:'',go:'',java:'',kotlin:'',c:'',cpp:'',cs:CN,csharp:CN,php:'',shell:'',powershell:'',sql:'',yaml:'',markdown:'',xml:'',rust:'',vue:'',mermaid:''},fallback:'',loadExtended:()=>_s(()=>import("./extended-p72mFE2C.js"),[]).then(e=>e.materialExtendedMap)},zye=_u(0);dA=()=>{zye.value++},Rye(Bye);const jye={"":"",javascript:"javascript",js:"javascript",mjs:"javascript",cjs:"javascript",typescript:"typescript",ts:"typescript",jsx:"jsx",tsx:"tsx",golang:"go",py:"python",rb:"ruby",sh:"shell",bash:"shell",zsh:"shell",shellscript:"shell",bat:"shell",batch:"shell",ps1:"powershell",plaintext:"plain",text:"plain",txt:"plain","c++":"cpp","c#":"csharp",cs:"csharp","objective-c":"objectivec","objective-c++":"objectivecpp",yml:"yaml",md:"markdown",rs:"rust",kt:"kotlin"};function M4(e){var t;const n=(function(i){if(!i)return"";const o=i.trim();if(!o)return"";const[s]=o.split(/\s+/),[r]=s.split(":");return r.toLowerCase()})(e);return(t=jye[n])!=null?t:n}function l8t(e){const t=M4(e);if(!t)return"plaintext";switch(t){case"plain":return"plaintext";case"jsx":return"javascript";case"tsx":return"typescript";case"objectivec":return"objective-c";case"objectivecpp":return"objective-cpp";default:return t}}function a8t(e){return Oye(M4(e))||Pye()}const xN={js:"JavaScript",javascript:"JavaScript",ts:"TypeScript",jsx:"JSX",tsx:"TSX",html:"HTML",css:"CSS",scss:"SCSS",json:"JSON",py:"Python",python:"Python",rb:"Ruby",go:"Go",java:"Java",c:"C",cpp:"C++",cs:"C#",csharp:"C#",php:"PHP",sh:"Shell",bash:"Bash",sql:"SQL",yaml:"YAML",md:"Markdown",d2:"D2",d2lang:"D2","":"Plain Text",plain:"Plain Text"};var T4=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});let gl=null,Th=!1,Eh=null,E4=kx;function l2(e){var t;const n=(t=e?.default)!=null?t:e;return n&&typeof n.renderToString=="function"?n:null}function yx(){try{const e=globalThis;return l2(e?.katex)}catch{return null}}function kx(){return T4(null,null,function*(){const e=yx();if(e)return e;const t=yield _s(()=>import("./katex-DnlPpQZa.js"),[]);try{yield _s(()=>import("./mhchem-DtR62fUK.js"),__vite__mapDeps([0,1]))}catch{}return l2(t)})}function KW(e){const t=Promise.resolve(e).then(n=>{var i;return Eh===t&&n?(gl=(i=l2(n))!=null?i:n,gl):null}).catch(()=>null).finally(()=>{Eh===t&&(Eh=null)});return Eh=t,Th=!0,t}function Hye(e){E4=e,gl=null,Th=!1,Eh=null}function Wye(e){Hye(kx)}function ZW(){return typeof E4=="function"}function u8t(){var e;const t=E4;if(!t||t===kx)return null;if(gl)return gl;const n=yx();if(n)return gl=n,gl;if(Th)return null;try{const i=t();return i?typeof i?.then=="function"?(KW(i),null):(gl=(e=l2(i))!=null?e:i,gl):null}catch{return null}}function GW(){return T4(this,null,function*(){var e;const t=yx();if(t)return gl=t,gl;if(gl)return gl;if(Eh)return Eh;if(Th)return null;const n=E4;if(!n)return Th=!0,null;try{const i=n();if(typeof i?.then=="function")return KW(i);if(i)return gl=(e=l2(i))!=null?e:i,Th=!0,gl}catch{}return Th=!0,null})}function QW(e){return e?e.replace(/·/g,"⋅").replace(/℃/g,"°C"):""}let w9=null,dh=null;const pl=new Map,qc=new Map;let Iv=5;const Uh=new Set;function F0(){if(pl.size{const{id:n,html:i,error:o}=t.data,s=pl.get(n);if(s)if(pl.delete(n),clearTimeout(s.timeoutId),s.cleanup(),F0(),o)s.aborted||s.reject(new Error(o));else{const{content:r,displayMode:l}=t.data;if(r){const a=`${l?"d":"i"}:${r}`;if(qc.set(a,i),qc.size>200){const u=qc.keys().next().value;qc.delete(u)}}s.aborted||s.resolve(i)}},w9.onerror=t=>{console.error("[katexWorkerClient] Worker error:",t);for(const[n,i]of pl.entries())clearTimeout(i.timeoutId),i.cleanup(),i.aborted||i.reject(new Error(`Worker error: ${t.message}`));pl.clear(),qye()}}function Vye(e,t=!0,n=2e3,i){return T4(this,null,function*(){performance.now();const o=QW(e);if(!ZW()){const a=new Error("KaTeX rendering disabled");return a.name="KaTeXDisabled",a.code="KATEX_DISABLED",Promise.reject(a)}if(dh)return Promise.reject(dh);const s=`${t?"d":"i"}:${o}`,r=qc.get(s);if(r)return F0(),Promise.resolve(r);const l=w9||(dh=new Error("[katexWorkerClient] No worker instance set. Please inject a Worker via setKaTeXWorker()."),dh.name="WorkerInitError",dh.code="WORKER_INIT_ERROR",null);if(!l)return Promise.reject(dh);if(pl.size>=Iv){const a=new Error("Worker busy");return a.name="WorkerBusy",a.code="WORKER_BUSY",a.busy=!0,a.inFlight=pl.size,a.max=Iv,Promise.reject(a)}return new Promise((a,u)=>{if(i?.aborted){const g=new Error("Aborted");return g.name="AbortError",void u(g)}const c=Math.random().toString(36).slice(2);let d=null;const h=globalThis.setTimeout(()=>{const g=pl.get(c);if(!g)return;pl.delete(c),g.cleanup();const y=new Error("Worker render timed out");y.name="WorkerTimeout",y.code="WORKER_TIMEOUT",g.aborted||g.reject(y),F0()},n);d=()=>{const g=pl.get(c);if(!g||g.aborted)return;g.aborted=!0,g.cleanup();const y=new Error("Aborted");y.name="AbortError",u(y)},i&&i.addEventListener("abort",d,{once:!0});const p=a,m=u;pl.set(c,{resolve:g=>{p(g)},reject:g=>{m(g)},timeoutId:h,aborted:!1,cleanup:()=>{i&&d&&i.removeEventListener("abort",d),d=null}});try{l.postMessage({id:c,content:o,displayMode:t})}catch(g){const y=pl.get(c);pl.delete(c),clearTimeout(h),y?.cleanup(),y?.reject(g),F0()}})})}function c8t(e,t=!0,n){const i=`${t?"d":"i"}:${QW(e)}`;if(qc.set(i,n),qc.size>200){const o=qc.keys().next().value;qc.delete(o)}}const Kye="WORKER_BUSY";function Zye(e=2e3,t){return pl.size{let o,s=!1,r=null,l=()=>{};const a=()=>{o&&globalThis.clearTimeout(o),Uh.delete(l),t&&r&&t.removeEventListener("abort",r),r=null};l=()=>{s||(s=!0,a(),n())},Uh.add(l),o=globalThis.setTimeout(()=>{if(s)return;s=!0,a();const u=new Error("Wait for worker slot timed out");u.name="WorkerBusyTimeout",u.code="WORKER_BUSY_TIMEOUT",i(u)},e),queueMicrotask(()=>F0()),t&&(r=()=>{if(s)return;s=!0,a();const u=new Error("Aborted");u.name="AbortError",i(u)},t.aborted?r():t.addEventListener("abort",r,{once:!0}))})}const Ig={timeout:2e3,waitTimeout:1500,backoffMs:30,maxRetries:1};function d8t(e){return T4(this,arguments,function*(t,n=!0,i={}){var o,s,r,l;if(!ZW()){const g=new Error("KaTeX rendering disabled");throw g.name="KaTeXDisabled",g.code="KATEX_DISABLED",g}const a=(o=i.timeout)!=null?o:Ig.timeout,u=(s=i.waitTimeout)!=null?s:Ig.waitTimeout,c=(r=i.backoffMs)!=null?r:Ig.backoffMs,d=(l=i.maxRetries)!=null?l:Ig.maxRetries,h=Number.isFinite(d)?Math.max(0,Math.min(Math.floor(d),8)):Ig.maxRetries,p=i.signal;let m=0;for(;;){if(p?.aborted){const g=new Error("Aborted");throw g.name="AbortError",g}try{return yield Vye(t,n,a,p)}catch(g){if(g?.code!==Kye||m>=h)throw g;if(m++,yield Zye(u,p).catch(()=>{}),p?.aborted){const y=new Error("Aborted");throw y.name="AbortError",y}c>0&&(yield new Promise(y=>globalThis.setTimeout(y,c*m)))}}})}function A1(e){const t=typeof e=="number"?e:Number.parseFloat(String(e??""));return Number.isFinite(t)&&t>0?t:null}function Gye(e){var t;for(const n of e.split(/\r?\n/)){const i=n.trim();if(!i||i.startsWith("%%"))continue;const o=i.match(/^([A-Z][\w-]*)\b/i);return((t=o?.[1])==null?void 0:t.toLowerCase())||""}return""}function Vk(e){const t=e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o&&!o.startsWith("%%")),n=Math.max(1,t.length),i=Gye(e);return i==="gantt"?220+28*n:i==="sequencediagram"?180+26*n:i==="classdiagram"||i==="statediagram"||i==="erdiagram"?180+24*n:i==="flowchart"||i==="graph"?170+28*n:200+22*n}function Kk(e){const t=e.split(/\r?\n/).filter(n=>/^\s*-\s+/.test(n)).length;return t>=3?500:t>0?280+60*t:360}function YW(e,t=360,n=500){return n==null?Math.max(t,e):Math.min(Math.max(t,e),n)}function Zk(e,t=360,n=500){return YW(e,t,n)}function Gk(e,t=360,n=500){return YW(e,t,n)}var Qye=Object.defineProperty,Yye=Object.defineProperties,Jye=Object.getOwnPropertyDescriptors,SN=Object.getOwnPropertySymbols,Xye=Object.prototype.hasOwnProperty,e9e=Object.prototype.propertyIsEnumerable,_N=(e,t,n)=>t in e?Qye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,JW=(e,t)=>{for(var n in t||(t={}))Xye.call(t,n)&&_N(e,n,t[n]);if(SN)for(var n of SN(t))e9e.call(t,n)&&_N(e,n,t[n]);return e},IN=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});const Qk=()=>_s(()=>import("./mermaid.core-CqiFQExc.js").then(e=>e.bp),__vite__mapDeps([2,3]));let Ec=null,x1=Qk,e0=null,fA=!1,hA=!1,t0=0;function t9e(e){x1=e,t0++,Ec=null,e0=null,fA=!1,hA=!1}function n9e(e){t9e(Qk)}function MN(){return typeof x1=="function"}function TN(e){if(!e)return e;const t=e&&e.default?e.default:e;if(t&&(typeof t.render=="function"||typeof t.parse=="function"||typeof t.initialize=="function"))return t;if(t&&t.mermaidAPI&&(typeof t.mermaidAPI.render=="function"||typeof t.mermaidAPI.parse=="function")){const o=t.mermaidAPI;return n=JW({},t),i={render:o.render.bind(o),parse:o.parse?o.parse.bind(o):void 0,initialize:s=>typeof t.initialize=="function"?t.initialize(s):o.initialize?o.initialize(s):void 0},Yye(n,Jye(i))}var n,i;return e.mermaid&&typeof e.mermaid.render=="function"?e.mermaid:t}function EN(e){if(e)try{const t=e?.initialize;e.initialize=n=>{const i=JW({suppressErrorRendering:!0},n||{});return typeof t=="function"?t.call(e,i):e?.mermaidAPI&&typeof e.mermaidAPI.initialize=="function"?e.mermaidAPI.initialize(i):void 0}}catch{}}function f8t(){return IN(this,null,function*(){if(Ec)return Ec;const e=(function(){try{const i=globalThis;return TN(i?.mermaid)}catch{return null}})();if(e)return Ec=e,EN(Ec),Ec;const t=x1,n=t0;return t?t===Qk&&fA?null:e0||(e0=IN(null,null,function*(){let i;try{i=yield t()}catch(o){if(t===Qk)return n===t0&&t===x1&&(fA=!0,(function(s){hA||(hA=!0,console.warn('[markstream-vue] Optional dependency "mermaid" is not installed. Mermaid blocks will render as source.',s))})(o)),null;throw o}finally{n===t0&&t===x1&&(e0=null)}return n!==t0||t!==x1?null:i?(Ec=TN(i),EN(Ec),Ec):null}),e0):null})}let Bu=null,fh=null;const cu=new Map,hh=new Map;function Q8(e){for(const t of cu.values())t.reject(e);cu.clear(),hh.clear()}let LN=5,NN=!1;const i9e="WORKER_BUSY",DN="MERMAID_DISABLED";function o9e(e){if(Bu&&Bu!==e){const n=new Error("Worker replaced");n.code="WORKER_REPLACED",Q8(n)}Bu=e,fh=null;const t=e;Bu.onmessage=n=>{if(Bu!==t)return;const{id:i,ok:o,result:s,error:r}=n.data,l=cu.get(i);l&&(o===!1||r?l.reject(new Error(r||"Unknown error")):l.resolve(s))},Bu.onerror=n=>{var i,o;if(Bu===t)if(cu.size!==0){try{NN?console.error("[mermaidWorkerClient] Worker error:",n?.message||n):(o=console.debug)==null||o.call(console,"[mermaidWorkerClient] Worker error:",n?.message||n)}catch{}Q8(new Error(`Worker error: ${n.message}`))}else(i=console.debug)==null||i.call(console,"[mermaidWorkerClient] Worker error (no pending):",n?.message||n)},Bu.onmessageerror=n=>{var i,o;if(Bu===t)if(cu.size!==0){try{NN?console.error("[mermaidWorkerClient] Worker messageerror:",n):(o=console.debug)==null||o.call(console,"[mermaidWorkerClient] Worker messageerror:",n)}catch{}Q8(new Error("Worker messageerror"))}else(i=console.debug)==null||i.call(console,"[mermaidWorkerClient] Worker messageerror (no pending):",n)}}function XW(e,t,n,i){if(!MN()){const r=new Error("Mermaid rendering disabled");return r.name="MermaidDisabled",r.code=DN,Promise.reject(r)}const o=`${e}\0${t.theme}\0${n}\0${t.code}`;let s=hh.get(o);return s||(s=(function(r,l,a=1400){if(!MN()){const c=new Error("Mermaid rendering disabled");return c.name="MermaidDisabled",c.code=DN,Promise.reject(c)}if(fh)return Promise.reject(fh);const u=Bu||(fh=new Error("[mermaidWorkerClient] No worker instance set. Please inject a Worker via setMermaidWorker()."),fh.name="WorkerInitError",fh.code="WORKER_INIT_ERROR",null);if(!u)return Promise.reject(fh);if(cu.size>=LN){const c=new Error("Worker busy");return c.name="WorkerBusy",c.code=i9e,c.inFlight=cu.size,c.max=LN,Promise.reject(c)}return new Promise((c,d)=>{const h=Math.random().toString(36).slice(2);let p,m=!1;const g=()=>{m||(m=!0,p!=null&&globalThis.clearTimeout(p),cu.delete(h))},y={resolve:b=>{g(),c(b)},reject:b=>{g(),d(b)}};cu.set(h,y);try{u.postMessage({id:h,action:r,payload:l})}catch(b){return cu.delete(h),void d(b)}p=globalThis.setTimeout(()=>{const b=new Error("Worker call timed out");b.name="WorkerTimeout",b.code="WORKER_TIMEOUT";const v=cu.get(h);v&&v.reject(b)},a)})})(e,t,n),hh.set(o,s),s.then(()=>{hh.get(o)===s&&hh.delete(o)},()=>{hh.get(o)===s&&hh.delete(o)})),(function(r,l){if(!l)return r;if(l.aborted){const a=new Error("Aborted");return a.name="AbortError",Promise.reject(a)}return new Promise((a,u)=>{let c=()=>{};const d=()=>l.removeEventListener("abort",c);c=()=>{d();const h=new Error("Aborted");h.name="AbortError",u(h)},l.addEventListener("abort",c,{once:!0}),r.then(h=>{d(),a(h)},h=>{d(),u(h)})})})(s,i)}function h8t(e,t,n=1400,i){return XW("canParse",{code:e,theme:t},n,i)}function p8t(e,t,n=1400,i){return XW("findPrefix",{code:e,theme:t},n,i)}var s9e=Object.defineProperty,r9e=Object.defineProperties,l9e=Object.getOwnPropertyDescriptors,FN=Object.getOwnPropertySymbols,a9e=Object.prototype.hasOwnProperty,u9e=Object.prototype.propertyIsEnumerable,RN=(e,t,n)=>t in e?s9e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ht=(e,t)=>{for(var n in t||(t={}))a9e.call(t,n)&&RN(e,n,t[n]);if(FN)for(var n of FN(t))u9e.call(t,n)&&RN(e,n,t[n]);return e},Hn=(e,t)=>r9e(e,l9e(t)),xo=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});const c9e="__global__",Y8="__MARKSTREAM_VUE_CUSTOM_COMPONENTS_STORE__",pA=(()=>{const e=globalThis;if(e[Y8])return e[Y8];const t={scopedCustomComponents:{},revision:_u(0)};return e[Y8]=t,t})(),ON=pA.revision,d9e=Symbol("markstreamCustomComponents"),f9e=new Set(["text","paragraph","heading","code_block","list","list_item","blockquote","table","table_row","table_cell","definition_list","definition_item","footnote","footnote_reference","footnote_anchor","admonition","hardbreak","link","image","thematic_break","math_inline","math_block","strong","emphasis","strikethrough","highlight","insert","subscript","superscript","emoji","checkbox","checkbox_input","inline_code","html_inline","html_block","reference","mermaid","infographic","d2","vmr_container"]);function a2(e){return f9e.has(String(e).trim().toLowerCase())}function h9e(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}function J8(e={}){const t={};for(const[n,i]of Object.entries(e))if(i!=null){t[n]=i;for(const o of new Set([Ga(n),Ga(h9e(n))]))!o||a2(o)||Object.prototype.hasOwnProperty.call(t,o)||(t[o]=i)}return t}function Ks(e){const t=rn(d9e,null);return D(()=>{var n;return ON.value,(function(i,o={}){return ON.value,Ht(Ht(Ht({},J8(pA.scopedCustomComponents[c9e]||{})),J8(o)),J8((function(s){return s&&pA.scopedCustomComponents[s]||{}})(i)))})(e?.(),(n=t?.value)!=null?n:{})})}const p9e=["aria-label"],m9e={key:0,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",class:"checkbox-icon checkbox-unchecked"},g9e={key:1,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",class:"checkbox-icon checkbox-checked"},Hi=(e,t)=>{const n=e.__vccOpts||e;for(const[i,o]of t)n[i]=o;return n},ha=Hi(dt({__name:"CheckboxNode",props:{node:{}},setup:e=>(t,n)=>(k(),L("span",{class:"checkbox-node",role:"img","aria-label":e.node.checked?"checked":"unchecked"},[e.node.checked?(k(),L("svg",g9e,[...n[1]||(n[1]=[_("rect",{x:"3",y:"3",width:"18",height:"18",rx:"4",fill:"currentColor"},null,-1),_("path",{d:"M9 12l2 2 4-4",stroke:"hsl(var(--ms-background))","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round"},null,-1)])])):(k(),L("svg",m9e,[...n[0]||(n[0]=[_("rect",{x:"3",y:"3",width:"18",height:"18",rx:"4",stroke:"currentColor","stroke-width":"2"},null,-1)])]))],8,p9e))}),[["__scopeId","data-v-be21ab83"]]);ha.install=e=>{e.component(ha.__name,ha)};const v9e={class:"emoji-node"},ql=Hi(dt({__name:"EmojiNode",props:{node:{}},setup:e=>(t,n)=>(k(),L("span",v9e,P(e.node.name),1))}),[["__scopeId","data-v-de55dc97"]]);ql.install=e=>{e.component(ql.__name,ql)};const y9e=["id"],k9e=["title"],pa=Hi(dt({__name:"FootnoteReferenceNode",props:{node:{}},setup(e){const t=`#fnref--${e.node.id}`;function n(){if(typeof document>"u")return;const i=document.querySelector(t);i?i.scrollIntoView({behavior:"smooth"}):console.warn(`Element with href: ${t} not found`)}return(i,o)=>(k(),L("sup",{id:`fnref-${e.node.id}`,class:"footnote-reference",onClick:n},[_("span",{href:t,title:`查看脚注 ${e.node.id}`,class:"footnote-link cursor-pointer"},"["+P(e.node.id)+"]",9,k9e)],8,y9e))}}),[["__scopeId","data-v-c1463a29"]]);pa.install=e=>{e.component(pa.__name,pa)};const eq=(()=>{try{return!1}catch{}return!1})();function X8(e){eq&&console.warn(e)}function PN(e,t="safe",n){return gx(e,t,n)}function tq(e){return J2e(e)}function ew(e){return e===!0?"":e===!1?"false":e==null?null:String(e)}function bx(e,t="safe"){const n=String(e.tag||e.type||"").trim(),i=b9((o=e.attrs)?Array.isArray(o)?o.every(Array.isArray)?o.map(([r,l])=>[String(r),ew(l)]):o.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)&&"name"in r).map(r=>[String(r.name),ew(r.value)]):Object.entries(o).map(([r,l])=>[r,ew(l)]):null,t,n);var o;if(!i)return;const s=tq(D0(i));return Object.keys(s).length>0?s:void 0}function $N(e,t,n=!1){const i=Object.entries(t??{}),o=i.length>0?i.map(([s,r])=>r===""?` ${s}`:` ${s}="${r}"`).join(""):"";return n?`<${e}${o} />`:`<${e}${o}>`}function Mg(e,t){Array.isArray(t)?e.push(...t):t!=null&&e.push(t)}function tw(e,t,n,i,o,s,r=!1){const l=(function(d,h){return BW(d,h)})(e,i);if(i2.has(e.toLowerCase())||!l&&RW(e,s))return null;if(!l&&mx(e,s))return r?[$N(e,t,!0)]:[$N(e,t),...n,``];const a=gx(t,s,e),u=a.key,c=u!=null&&u!==""?u:o;if(l){const d=i[e]||i[e.toLowerCase()],h=tq(a);return jn(d,Hn(Ht({},h),{key:c}),n.length>0?n:void 0)}return jn(e,Hn(Ht({},a),{innerHTML:void 0,key:c}),n.length>0?n:void 0)}function nq(e,t){return tye(e,t)}function Yk(e,t,n="safe"){if(!e)return[];try{return(function(s,r,l="safe"){let a=0;const u=[],c=[];for(const d of s)if(d.type==="text")(u.length>0?u[u.length-1].children:c).push(d.content);else if(d.type==="self_closing"){const h=tw(d.tagName,d.attrs||{},[],r,"ms-html-"+a++,l,!0);Mg(u.length>0?u[u.length-1].children:c,h)}else if(d.type==="tag_open")u.push({tagName:d.tagName,children:[],attrs:d.attrs,autoKey:"ms-html-"+a++});else if(d.type==="tag_close"){const h=d.tagName.toLowerCase();let p=-1;for(let m=u.length-1;m>=0;m--)if(u[m].tagName.toLowerCase()===h){p=m;break}if(p!==-1)for(;u.length>p;){const m=u.pop(),g=tw(m.tagName,m.attrs||{},m.children,r,m.autoKey,l);u.length>0?Mg(u[u.length-1].children,g):Mg(c,g),m.tagName.toLowerCase()!==h&&u.length>p&&X8(`Auto-closing unclosed tag: <${m.tagName}>`)}else X8(`Ignoring closing tag with no matching opening tag: `)}for(;u.length>0;){const d=u.pop(),h=tw(d.tagName,d.attrs||{},d.children,r,d.autoKey,l);u.length>0?Mg(u[u.length-1].children,h):Mg(c,h),X8(`Auto-closing unclosed tag: <${d.tagName}>`)}return c})(zW(e),t,n)}catch(o){return i=o,eq&&console.error("Failed to parse HTML to VNodes:",i),null}var i}const b9e=["innerHTML"],ma=Hi(dt({__name:"HtmlInlineNode",props:{node:{},customId:{},htmlPolicy:{}},setup(e){const t=e,n=rn("markstreamHtmlPolicy",void 0),i=D(()=>{var l,a;return(a=(l=t.htmlPolicy)!=null?l:n?.value)!=null?a:"safe"}),o=Ks(()=>t.customId),s=dt({name:"DynamicRenderer",props:{nodes:{type:Array,required:!0}},render(){return this.nodes}}),r=D(()=>{const l=t.node.content;if(!l)return{mode:"html",content:""};if(i.value==="escape")return{mode:"html",content:K1(l,i.value)};if(t.node.loading&&!t.node.autoClosed)return{mode:"text",content:l};if(t.node.loading&&t.node.autoClosed){const u=Yk(l,o.value,i.value);if(u!==null)return{mode:"dynamic",nodes:u}}if(!nq(l,o.value))return{mode:"html",content:K1(l,i.value)};const a=Yk(l,o.value,i.value);return a===null?{mode:"html",content:K1(l,i.value)}:{mode:"dynamic",nodes:a}});return(l,a)=>r.value.mode==="dynamic"?(k(),L("span",{key:0,class:Pe(["html-inline-node",{"html-inline-node--loading":t.node.loading}])},[U(f(s),{nodes:r.value.nodes},null,8,["nodes"])],2)):r.value.mode==="text"?(k(),L("span",{key:1,class:Pe(["html-inline-node",{"html-inline-node--loading":t.node.loading}])},P(r.value.content),3)):(k(),L("span",{key:2,class:Pe(["html-inline-node",{"html-inline-node--loading":t.node.loading}]),innerHTML:r.value.content},null,10,b9e))}}),[["__scopeId","data-v-d17f12b0"]]);ma.install=e=>{e.component(ma.__name,ma)};const w9e={class:"inline-code"},C9e={key:0},il=Hi(dt({__name:"InlineCodeNode",props:{node:{}},setup(e){const t=e,n=Nm(),i=rn("markstreamFade",void 0),o=rn("markstreamTextStreamState",void 0),s=rn("markstreamStreamVersion",void 0),r=D(()=>{const v=n.fade;return v===""||v===!0||v==="true"||v!==!1&&v!=="false"&&void 0}),l=D(()=>typeof r.value=="boolean"?r.value:typeof i?.value!="boolean"||i.value),a=D(()=>{var v;return String((v=t.node.code)!=null?v:"")}),u=D(()=>!l.value),c=D(()=>{var v;const C=(v=n["index-key"])!=null?v:n.indexKey;return C==null||C===""?"":String(C)}),d=q(t.node.code),h=q(""),p=q(0);let m;function g(){m?.(),m=void 0}function y(){g(),h.value&&(d.value=d.value+h.value,h.value="")}qe([()=>t.node.code,c,l],([v])=>{const C=String(v??""),w=c.value,M=qW({nextContent:C,persistedContent:w?o?.get(w):void 0,currentState:{settledContent:d.value,streamedDelta:h.value},typewriterEnabled:l.value});d.value=M.settledContent,h.value=M.streamedDelta,M.appended?(p.value+=1,(function(){if(!h.value||m||!s)return;const N=s.value;m=qe(()=>s.value,T=>{T!==N&&y()},{flush:"sync"})})()):h.value||g(),w&&o?.set(w,C)},{immediate:!0}),ad(g);const b=D(()=>p.value%2==0?"inline-code-stream-delta--a":"inline-code-stream-delta--b");return(v,C)=>(k(),L("code",w9e,[u.value?(k(),L(Fe,{key:0},[He(P(a.value),1)],64)):(k(),L(Fe,{key:1},[d.value?(k(),L("span",C9e,P(d.value),1)):J("",!0),h.value?(k(),L("span",{key:1,class:Pe(["inline-code-stream-delta",[b.value]]),onAnimationend:y},P(h.value),35)):J("",!0)],64))]))}}),[["__scopeId","data-v-4e331c97"]]);il.install=e=>{e.component(il.__name,il)};const mA=q(!1),BN=q(""),zN=q("top"),R0=q(null),O0=q(null),gA=q(null),vA=q(null),jN=q(null);let C9=null,A9=null,yA=0;function iq(){C9&&(clearTimeout(C9),C9=null),A9&&(clearTimeout(A9),A9=null)}let by=!1,wy=null,HN=!1;function A9e(e,t,n="top",i=!1,o,s){if(!e)return;const r=++yA;iq();const l=()=>xo(null,null,function*(){var a,u;if(yield(function(){return xo(this,null,function*(){if(!by&&!HN&&typeof document<"u"){wy!=null||(wy=xo(null,null,function*(){const[{createApp:c,h:d},{default:h}]=yield Promise.all([_s(()=>import("./vue.runtime.esm-bundler-D7X8t2I9.js"),[]),_s(()=>import("./Tooltip-DebxPz-0.js"),[])]),p=document.createElement("div");p.setAttribute("data-singleton-tooltip","1"),document.body.appendChild(p),c({setup:()=>()=>{var m;return d(h,{visible:mA.value,"anchor-el":R0.value,content:BN.value,placement:zN.value,id:O0.value,originX:gA.value,originY:vA.value,isDark:(m=jN.value)!=null?m:void 0})}}).mount(p),by=!0}));try{yield wy}catch(c){by=!1,wy=null,HN=!0,console.warn("[markstream-vue] Failed to mount Tooltip component. Tooltips will be disabled.",c)}}})})(),by&&r===yA){O0.value=`tooltip-${Date.now()}-${Math.floor(1e3*Math.random())}`,R0.value=e,BN.value=t,zN.value=n,gA.value=(a=o?.x)!=null?a:null,vA.value=(u=o?.y)!=null?u:null,jN.value=typeof s=="boolean"?s:null,mA.value=!0;try{e.setAttribute("aria-describedby",O0.value)}catch{}}});i?l():C9=setTimeout(l,80)}function x9e(e=!1){yA+=1,iq();const t=()=>{if(R0.value&&O0.value)try{R0.value.removeAttribute("aria-describedby")}catch{}mA.value=!1,R0.value=null,O0.value=null,gA.value=null,vA.value=null};e?t():A9=setTimeout(t,120)}const S9e={"common.copy":"Copy","common.copied":"Copied","common.decrease":"Decrease","common.reset":"Reset","common.increase":"Increase","common.expand":"Expand","common.collapse":"Collapse","common.preview":"Preview","common.source":"Source","common.export":"Export","common.open":"Open","common.minimize":"Minimize","common.zoomIn":"Zoom in","common.zoomOut":"Zoom out","common.resetZoom":"Reset zoom","image.loadError":"Image failed to load","image.loading":"Loading image..."},_9e=Symbol("markstreamI18nFallback");function oq(e,t){var n;return(n=t?.[e])!=null?n:S9e[e]}const kA=(e,t)=>{var n;return(n=oq(e,t))!=null?n:(function(i){return(i.split(".").pop()||i).replace(/[_-]/g," ").replace(/([A-Z])/g," $1").replace(/\s+/g," ").replace(/\b\w/g,o=>o.toUpperCase()).trim()})(e)};function WN(e,t){return{t(n){const i=oq(n,t);if(e.te&&i!=null&&!e.te(n))return kA(n,t);const o=e.t(n);return o===n&&i!=null?kA(n,t):o}}}function I9e(){const e=(function(){var n,i,o;try{const s=Vs(),r=_9e,l=s?.provides,a=(n=s?.appContext)==null?void 0:n.provides;return(o=(i=l?.[r])!=null?i:a?.[r])!=null?o:null}catch{}return null})(),t=(function(){var n,i;try{const o=Vs(),s=o?.proxy,r=s?.$t;if(typeof r=="function"){const u=s?.$te;return{t:r.bind(s),te:typeof u=="function"?u.bind(s):void 0}}const l=(i=(n=o?.appContext)==null?void 0:n.config)==null?void 0:i.globalProperties,a=l?.$t;if(typeof a=="function"){const u=l?.$te;return{t:a.bind(l),te:typeof u=="function"?u.bind(l):void 0}}}catch{}return null})();if(t)return WN(t,e);try{const n=globalThis.$vueI18nUse||null;if(n&&typeof n=="function")try{const i=n();if(i&&typeof i.t=="function")return WN({t:i.t.bind(i),te:typeof i.te=="function"?i.te.bind(i):void 0},e)}catch{}}catch{}return{t:n=>kA(n,e)}}const sq=Symbol("ViewportPriority"),rq=Symbol("ViewportPriorityOptions"),lq=Symbol("OffscreenHeavyNodeDeferral"),M9e=D(()=>!1),op="400px";function wx(){return rn(rq,void 0)}function Cx(){return rn(lq,M9e)}function T9e(e,t){var n,i;const o=typeof window<"u"&&typeof document<"u",s=typeof t=="boolean"?q(t):t,r=o?(n=window.requestIdleCallback)!=null?n:T=>window.setTimeout(()=>T({didTimeout:!0,timeRemaining:()=>0}),16):null,l=o?(i=window.cancelIdleCallback)!=null?i:T=>window.clearTimeout(T):null,a=new WeakMap;let u=1;const c=new Map,d=new Map,h=new Set;let p=null,m=null;function g(T){if(!T)return"viewport";let S=a.get(T);return S||(S=u++,a.set(T,S)),String(S)}function y(){if(p!=null){try{l?.(p)}catch{}p=null}}function b(T){if(T){const S=c.get(T);if(S&&!S.targets.size){try{S.io.disconnect()}catch{}c.delete(T)}}d.size||h.size||y()}function v(T){const S=d.get(T);if(!S)return;const x=c.get(S.bucketKey);if(!S.visible.value){S.visible.value=!0;try{S.resolve()}catch{}}try{x?.io.unobserve(T)}catch{}x?.targets.delete(T),d.delete(T),h.delete(T),b(S.bucketKey)}function C(){window.__MARKSTREAM_DISABLE_VIEWPORT_PRIORITY_IDLE_DRAIN__!==!0&&r&&p==null&&h.size&&(p=r(()=>{p=null;const T=h.values().next().value;T&&(h.delete(T),v(T),h.size&&C())},{timeout:1200}))}function w(T,S){if(!o||typeof IntersectionObserver>"u")return null;const x=(function(z,F){var O,B,j;return{root:(O=e?.(z??null))!=null?O:null,rootMargin:(B=F?.rootMargin)!=null?B:op,threshold:(j=F?.threshold)!=null?j:0}})(T,S),A=[g((E=x).root),E.rootMargin,E.threshold].join("\0");var E;const I=c.get(A);if(I)return{key:A,bucket:I};let R;try{R=new IntersectionObserver(z=>{for(const F of z)(F.isIntersecting||F.intersectionRatio>0)&&v(F.target)},{root:x.root,rootMargin:x.rootMargin,threshold:x.threshold})}catch{return null}const W={io:R,targets:new Map};return c.set(A,W),{key:A,bucket:W}}function M(){if(o&&s.value)for(const[T,S]of Array.from(d.entries())){const x=w(T,S.opts);if(!x){v(T);continue}if(x.key===S.bucketKey)continue;const A=S.bucketKey,E=c.get(A);try{E?.io.unobserve(T)}catch{}E?.targets.delete(T),S.bucketKey=x.key,x.bucket.targets.set(T,S),x.bucket.io.observe(T),b(A)}}qe(s,T=>{if(!T){for(const S of Array.from(d.keys()))v(S);y()}},{flush:"sync"});const N=(T,S)=>{const x=q(!1);let A,E=!1;const I=new Promise(F=>{A=()=>{E||(E=!0,F())}}),R=()=>{const F=d.get(T);if(!F)return h.delete(T),void b();const O=c.get(F.bucketKey);try{O?.io.unobserve(T)}catch{}O?.targets.delete(T),d.delete(T),h.delete(T),b(F.bucketKey)};if(!o||!s.value)return x.value=!0,A(),{isVisible:x,whenVisible:I,destroy:R};const W=w(T,S);if(!W)return x.value=!0,A(),{isVisible:x,whenVisible:I,destroy:R};const z={resolve:A,visible:x,bucketKey:W.key,opts:S};return d.set(T,z),W.bucket.targets.set(T,z),W.bucket.io.observe(T),o&&m==null&&(m=window.requestAnimationFrame(()=>{m=null,M()})),S?.allowIdle!==!1&&(h.add(T),C()),{isVisible:x,whenVisible:I,destroy:R}};return N.refresh=M,ui(sq,N),N}function Ax(){var e,t;const n=rn(sq,void 0);if(n)return n;const i=new WeakMap,o=new Map,s=new Set;let r=null;const l=typeof window<"u"?(e=window.requestIdleCallback)!=null?e:p=>window.setTimeout(()=>p({didTimeout:!0,timeRemaining:()=>0}),16):null,a=typeof window<"u"?(t=window.cancelIdleCallback)!=null?t:p=>window.clearTimeout(p):null,u=()=>{if(r!=null){try{a?.(r)}catch{}r=null}},c=p=>{if(!p)return;const m=o.get(p);if(m&&!m.targets.size){try{m.io.disconnect()}catch{}o.delete(p)}},d=p=>{const m=i.get(p);if(!m)return;const g=o.get(m.bucketKey);if(!m.visible.value){m.visible.value=!0;try{m.resolve()}catch{}}try{g?.io.unobserve(p)}catch{}i.delete(p),g?.targets.delete(p),s.delete(p),c(m.bucketKey),s.size||u()},h=()=>{window.__MARKSTREAM_DISABLE_VIEWPORT_PRIORITY_IDLE_DRAIN__!==!0&&l&&r==null&&s.size&&(r=l(()=>{r=null;const p=s.values().next().value;p&&(s.delete(p),d(p),s.size&&h())},{timeout:1200}))};return(p,m)=>{const g=q(!1);let y,b=!1;const v=new Promise(M=>{y=()=>{b||(b=!0,M())}}),C=()=>{const M=i.get(p);if(!M)return s.delete(p),void(s.size||u());const N=o.get(M.bucketKey);try{N?.io.unobserve(p)}catch{}i.delete(p),N?.targets.delete(p),s.delete(p),c(M.bucketKey),s.size||u()},w=(M=>{var N,T;if(typeof window>"u"||typeof IntersectionObserver>"u")return null;const S=(R=>{var W,z;return[(W=R?.rootMargin)!=null?W:op,(z=R?.threshold)!=null?z:0].join("\0")})(M),x=o.get(S);if(x)return{key:S,bucket:x};const A=(N=M?.rootMargin)!=null?N:op;let E;try{E=new IntersectionObserver(R=>{for(const W of R)(W.isIntersecting||W.intersectionRatio>0)&&d(W.target)},{root:null,rootMargin:A,threshold:(T=M?.threshold)!=null?T:0})}catch{return null}const I={io:E,targets:new Set};return o.set(S,I),{key:S,bucket:I}})(m);return w?(i.set(p,{resolve:y,visible:g,bucketKey:w.key}),w.bucket.targets.add(p),w.bucket.io.observe(p),m?.allowIdle!==!1&&(s.add(p),h()),{isVisible:g,whenVisible:v,destroy:C}):(g.value=!0,y(),{isVisible:g,whenVisible:v,destroy:C})}}function E9e(e,t){var n,i;const o=(i=(n=e.indexKey)!=null?n:t["index-key"])!=null?i:t.indexKey;return o==null||o===""?"":String(o)}const L9e=["data-markstream-viewport-pending"],N9e=["src","alt","title","loading","fetchpriority","decoding","tabindex","aria-label"],D9e={key:1,class:"image-placeholder"},F9e={key:1,class:"image-node__raw-text"},R9e={key:2,class:"image-shimmer-overlay"},O9e={key:1,class:"image-node__raw-text"},P9e={key:3,class:"image-error"},ef=Hi(dt({__name:"ImageNode",props:{node:{},fallbackSrc:{default:""},lazy:{type:Boolean,default:!1},usePlaceholder:{type:Boolean,default:!0}},emits:["load","error","click"],setup(e,{emit:t}){var n,i,o;const s=e,r=t,l=q(!1),a=q(!1),u=q(""),c=q("primary"),d=q(null),h=Nm(),p=rn(cA,null),m=Ax(),g=wx(),y=Cx(),b=D(()=>dL(s.node.src)),v=D(()=>dL(s.fallbackSrc)),C=(o=(i=(n=Vs())==null?void 0:n.vnode.el)==null?void 0:i.querySelector)==null?void 0:o.call(i,"img"),w=typeof window<"u"&&C?.getAttribute("src")===(b.value||v.value),M=q(typeof window>"u"||w||!y.value),N=_u(null);let T="",S=null;const x=D(()=>u.value),A=D(()=>!s.lazy),E=D(()=>typeof window<"u"&&y.value&&!w),I=D(()=>!E.value||M.value),R=D(()=>I.value?x.value:""),W=D(()=>{var Te,Ee;return(Ee=(Te=g?.value.heavyBlockMargin)!=null?Te:g?.value.rootMargin)!=null?Ee:op}),z=D(()=>!s.node.loading&&c.value!=="failed"&&u.value.length>0),F=D(()=>c.value==="failed"),O=D(()=>(!A.value||E.value&&!M.value)&&!l.value&&!a.value&&c.value!=="failed"&&u.value.length>0),B=D(()=>E9e(s,h));function j(Te=B.value){Te&&d.value&&p?.reportHeight(Te,d.value.offsetHeight)}function $(Te=B.value){Te&&mt(()=>{j(Te)})}function V(){S&&(clearTimeout(S),S=null)}function ne(){const Te=B.value;Te&&T!==Te&&(T&&p?.markSettled(T),V(),T=Te,p?.markPending(Te),typeof window<"u"&&(S=window.setTimeout(()=>{T===Te&&($(Te),K())},8e3)))}function K(){return xo(this,null,function*(){const Te=T;Te&&(V(),T="",yield mt(),j(Te),p?.markSettled(Te))})}function ee(){if(c.value==="primary"&&v.value&&v.value!==u.value)return c.value="fallback",u.value=v.value,l.value=!1,a.value=!1,void $();c.value="failed",a.value=!0,r("error",u.value),$()}function ue(){l.value=!0,a.value=!1,r("load",x.value),$()}function ie(Te){Te.preventDefault(),l.value&&!a.value&&r("click",[Te,x.value])}const{t:ye}=I9e();return qe([b,v,()=>s.node.loading],()=>(l.value=!1,a.value=!1,s.node.loading||b.value?(u.value=b.value,void(c.value="primary")):v.value?(u.value=v.value,void(c.value="fallback")):(u.value="",c.value="failed",void(a.value=!0))),{immediate:!0}),typeof window<"u"&&qe([d,E],([Te,Ee],Me,G)=>{var oe;if((oe=N.value)==null||oe.destroy(),N.value=null,!Ee||M.value)return void(M.value=!0);if(!Te)return void(M.value=!1);let Z=!0;const Q=m(Te,{rootMargin:W.value,allowIdle:!1});N.value=Q,M.value=Q.isVisible.value,Q.whenVisible.then(()=>{Z&&N.value===Q&&(M.value=!0)}),G(()=>{Z=!1,Q.destroy(),N.value===Q&&(N.value=null)})},{immediate:!0}),qe([z,l,a,x,()=>s.lazy,I],([Te,Ee,Me,G,oe,Z])=>Te&&G&&!Me&&Z?Ee?(K(),void $()):oe?(ne(),void $()):void(Ee||Me||ne()):(K(),void $()),{flush:"post",immediate:!0}),si(()=>{var Te;(Te=N.value)==null||Te.destroy(),N.value=null,(function(){const Ee=T;Ee&&(V(),T="",p?.markSettled(Ee))})()}),(Te,Ee)=>{var Me,G,oe,Z,Q;return k(),L("span",{ref_key:"rootRef",ref:d,class:"image-node-container","data-markstream-viewport-pending":E.value&&!M.value?"true":void 0},[z.value?(k(),L("img",{key:0,src:R.value||void 0,alt:String((G=(Me=s.node.alt)!=null?Me:s.node.title)!=null?G:""),title:String((Z=(oe=s.node.title)!=null?oe:s.node.alt)!=null?Z:""),class:Pe(["image-node__img",{"is-loading":!A.value&&!l.value,"is-loaded":A.value||l.value,"has-natural-size":l.value,"cursor-pointer":l.value}]),loading:s.lazy?"lazy":void 0,fetchpriority:A.value?"high":void 0,decoding:A.value?"sync":"async",tabindex:l.value?0:-1,"aria-label":(Q=s.node.alt)!=null?Q:f(ye)("image.preview"),onError:ee,onLoad:ue,onClick:ie},null,42,N9e)):J("",!0),e.node.loading&&!a.value?(k(),L("span",D9e,[s.usePlaceholder?Gn(Te.$slots,"placeholder",{key:0,node:s.node,displaySrc:x.value,imageLoaded:l.value,hasError:a.value,fallbackSrc:s.fallbackSrc,lazy:s.lazy},()=>[Ee[0]||(Ee[0]=_("span",{class:"image-shimmer"},null,-1))],!0):(k(),L("span",F9e,P(e.node.raw),1))])):J("",!0),O.value&&!e.node.loading?(k(),L("span",R9e,[s.usePlaceholder?Gn(Te.$slots,"placeholder",{key:0,node:s.node,displaySrc:x.value,imageLoaded:l.value,hasError:a.value,fallbackSrc:s.fallbackSrc,lazy:s.lazy},()=>[Ee[1]||(Ee[1]=_("span",{class:"image-shimmer"},null,-1))],!0):(k(),L("span",O9e,P(e.node.raw),1))])):J("",!0),F.value?(k(),L("span",P9e,[Gn(Te.$slots,"error",{node:s.node,displaySrc:x.value,imageLoaded:l.value,hasError:a.value,fallbackSrc:s.fallbackSrc,lazy:s.lazy},()=>[Ee[2]||(Ee[2]=_("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24"},[_("path",{fill:"currentColor",d:"M2 2h20v10h-2V4H4v9.586l5-5L14.414 14L13 15.414l-4-4l-5 5V20h8v2H2zm13.547 5a1 1 0 1 0 0 2a1 1 0 0 0 0-2m-3 1a3 3 0 1 1 6 0a3 3 0 0 1-6 0m3.625 6.757L19 17.586l2.828-2.829l1.415 1.415L20.414 19l2.829 2.828l-1.415 1.415L19 20.414l-2.828 2.829l-1.415-1.415L17.586 19l-2.829-2.828z"})],-1)),_("span",null,P(f(ye)("image.loadError")),1)],!0)])):J("",!0)],8,L9e)}}}),[["__scopeId","data-v-046e82ac"]]);ef.install=e=>{e.component(ef.__name,ef)};const $9e={key:2},mc=dt({__name:"NodeChildRenderer",props:{node:{},components:{},customId:{},indexKey:{},fallbackToText:{type:Boolean,default:!1}},setup(e){const t=e,n=Ks(()=>t.customId),i=rn("markstreamHtmlPolicy",void 0),o=rn("markstreamNestedRendererProps",void 0),s=D(()=>{var m;return(m=i?.value)!=null?m:"safe"}),r=D(()=>{var m,g;const y=(m=o?.value)!=null?m:{};return Hn(Ht({},y),{customId:(g=t.customId)!=null?g:y.customId,htmlPolicy:s.value})}),l=Yu({loader:()=>Promise.resolve().then(()=>Fx),suspensible:!1}),a=D(()=>t.components[String(t.node.type)]),u=D(()=>!!(a.value&&n.value[t.node.type]&&!a2(String(t.node.type)))),c=D(()=>u.value?bx(t.node,s.value):void 0),d=D(()=>Array.isArray(t.node.children)&&t.node.children.length>0),h=D(()=>{var m;return String((m=t.node.content)!=null?m:"")}),p=D(()=>{var m,g;return String((g=(m=t.node.content)!=null?m:t.node.raw)!=null?g:"")});return(m,g)=>a.value&&u.value?(k(),ce(fs(a.value),yi({key:0},c.value,{node:e.node,loading:e.node.loading,"index-key":e.indexKey,"custom-id":e.customId,"is-dark":r.value.isDark}),{default:ae(()=>[d.value?(k(),ce(f(l),yi({key:0},r.value,{nodes:e.node.children,"index-key":e.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):h.value?(k(),ce(f(l),yi({key:1},r.value,{content:h.value,final:!e.node.loading,"index-key":`${e.indexKey||"child"}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):J("",!0)]),_:1},16,["node","loading","index-key","custom-id","is-dark"])):a.value?(k(),ce(fs(a.value),{key:1,node:e.node,"custom-id":e.customId,"index-key":e.indexKey},null,8,["node","custom-id","index-key"])):e.fallbackToText?(k(),L("span",$9e,P(p.value),1)):J("",!0)}}),qN=Object.freeze({enabled:!0,contextLineCount:2,minimumLineCount:4,revealLineCount:5});function B9e(e){var t;if(typeof e=="boolean")return e;if(e&&typeof e=="object"){const n=e;return Hn(Ht(Ht({},qN),n),{enabled:(t=n.enabled)==null||t})}return Ht({},qN)}function xx(e,t){if(e.renderSideBySide===!1)return!0;if(e.useInlineViewWhenSpaceIsLimited!==!0)return!1;const n=e.renderSideBySideInlineBreakpoint,i=typeof n=="number"&&Number.isFinite(n)?n:900;return t>0&&t<=i}function aq(e){var t,n;const i=(n=(t=String(e??"").split(/\r?\n/,1)[0])==null?void 0:t.trim())!=null?n:"";if(i.length<3)return"";const o=i[0];if(o!=="`"&&o!=="~"||i[1]!==o||i[2]!==o)return"";let s=3;for(;i[s]===o;)s+=1;return i.slice(s).trim()}function UN(e){var t;return((t=String(e??"").trim().split(/\s+/,1)[0])!=null?t:"")==="diff"}function z9e(e){var t;return e.diff===!0||UN(e.language)||UN(aq(String((t=e.raw)!=null?t:"")))}function j9e(e,t,n){const i=(function(o){const s=aq(o);if(!s)return"";const r=s.split(/\s+/).filter(Boolean);if(!r.length)return"";const l=r[0]==="diff"?r.slice(1):r;for(const a of l){const u=a.includes(":")?a.slice(a.indexOf(":")+1):a;if(u&&/[./\\-]/.test(u))return u}return""})(e);return{title:i||t,caption:i?n?`Diff / ${t}`:t:""}}const H9e=["aria-busy","aria-label","data-language","data-markstream-line-numbers"],W9e={key:0,translate:"no",class:"markstream-pre__diff-code"},q9e={class:"markstream-pre__diff-pane-content"},U9e={class:"markstream-pre__diff-number","aria-hidden":"true"},V9e={class:"markstream-pre__diff-content"},K9e={class:"markstream-pre__diff-content-inner"},Z9e={key:0,class:"markstream-pre__line-numbers","aria-hidden":"true"},G9e=["textContent"],Q9e=["textContent"],Ol=dt({__name:"PreCodeNode",props:{node:{},loading:{type:Boolean},showLineNumbers:{type:Boolean},diffInline:{type:Boolean},diffHideUnchangedRegions:{type:[Boolean,Object]},reservedHeightPx:{}},setup(e){const t=e;function n(ie,ye){const Te=String(ie??"");return ye?Te:Te.replace(/\r\n$|\n$|\r$/,"")}const i=D(()=>{var ie,ye,Te;const Ee=String((ye=(ie=t.node)==null?void 0:ie.language)!=null?ye:"");return String((Te=String(Ee).split(/\s+/g)[0])!=null?Te:"").toLowerCase().replace(/[^\w-]/g,"")||"plaintext"}),o=D(()=>`language-${i.value}`),s=D(()=>{var ie;return t.loading===!0||((ie=t.node)==null?void 0:ie.loading)===!0}),r=D(()=>{var ie;return n((ie=t.node)==null?void 0:ie.code,s.value)});let l="",a=1;const u=D(()=>(function(ie){let ye=0,Te=1;ie.startsWith(l)&&(ye=l.length,Te=a,ye>0&&ie[ye-1]==="\r"&&ie[ye]===` -`&&ye++);for(let Ee=ye;Eer.value.split(/\r\n|\n|\r/));let d=0,h="";const p=D(()=>{const ie=u.value;ie{var ie;return t.showLineNumbers===!0&&((ie=t.node)==null?void 0:ie.diff)===!0}),g=D(()=>m.value&&t.diffInline===!0),y=D(()=>{const ie=Number(t.reservedHeightPx);if(!Number.isFinite(ie)||ie<=0)return;const ye=`${Math.ceil(ie)}px`;return s.value?{maxHeight:ye,overflow:"auto"}:{height:ye,minHeight:ye,maxHeight:ye,overflow:"auto"}}),b=["diff ","index ","--- ","+++ ","@@ "];function v(ie){return String(ie??"").trim().length===0}function C(ie,ye="context",Te={}){const Ee=v(ie);return{code:ie,kind:Ee&&ye!=="hunk"&&ye!=="spacer"&&!Te.preserveBlankKind?"context":ye,empty:Ee}}function w(ie){const ye=n(ie,s.value);return ye?ye.split(/\r\n|\n|\r/):[]}function M(ie,ye){return!v(ie[ye])||yeb.some(Te=>ye.startsWith(Te)))}function x(ie,ye){return ye||!ie.startsWith(" ")||ie.startsWith(" ")?ie:` ${ie}`}function A(ie,ye){const Te=ie.length,Ee=ye.length,Me=[];let G=0;for(;G=G&&Q>=G&&ie[Z]===ye[Q];)oe.unshift({originalIndex:Z,modifiedIndex:Q}),Z--,Q--;const fe=Z-G+1,de=Q-G+1;if(fe<=0||de<=0||s.value||(fe+1)*(de+1)>15e5)return Me.concat(oe);const pe=de+1,X=new Uint32Array((fe+1)*(de+1));for(let se=fe-1;se>=0;se--)for(let _e=de-1;_e>=0;_e--){const ge=se*pe+_e;if(ie[G+se]===ye[G+_e])X[ge]=X[(se+1)*pe+_e+1]+1;else{const Le=X[(se+1)*pe+_e],be=X[se*pe+_e+1];X[ge]=Le>=be?Le:be}}const re=[];let ke=0,le=0;for(;ke=X[ke*pe+le+1]?ke++:le++;return Me.concat(re,oe)}function E(ie){var ye;const Te=(function(){var Q,fe;const de=t.diffHideUnchangedRegions;if(de==null||de===!1)return null;const pe=de===!0?{}:de;return pe.enabled===!1?null:{contextLineCount:Math.max(0,Math.floor((Q=pe.contextLineCount)!=null?Q:2)),minimumLineCount:Math.max(1,Math.floor((fe=pe.minimumLineCount)!=null?fe:4))}})();if(!Te||ie.length<1||ie.length>2||ie.length===2&&ie[0].lines.length!==ie[1].lines.length)return ie;const Ee=ie[0].lines,Me=(ye=ie[1])==null?void 0:ye.lines,G=Q=>Ee[Q].kind==="context"&&(Me===void 0||Me[Q].kind==="context"&&Ee[Q].code===Me[Q].code),oe=[];let Z=0;for(;Z=Te.minimumLineCount){const de=Q+(Q===0?0:Te.contextLineCount),pe=fe-(fe===Ee.length?0:Te.contextLineCount);pe-de>=Te.minimumLineCount&&oe.push({start:de,end:pe})}Z===Q&&Z++}return oe.length?ie.map((Q,fe)=>{const de=[];let pe=0;for(const X of oe)de.push(...Q.lines.slice(pe,X.start)),de.push({code:fe===0?"Unmodified lines":"",kind:"collapsed",empty:!1,key:`${Q.key}-collapsed-${X.start}-${X.end}`,number:""}),pe=X.end;return de.push(...Q.lines.slice(pe)),Hn(Ht({},Q),{lines:de})}):ie}const I=D(()=>{var ie,ye,Te,Ee;if(!m.value)return[];const Me=(function(fe){const de=fe.some(X=>N(X)),pe=fe.some(X=>T(X));return de&&pe||(function(){var X,re,ke,le;if(i.value==="diff")return!0;const se=(le=(ke=String((re=(X=t.node)==null?void 0:X.raw)!=null?re:"").split(/\r?\n/,1)[0])==null?void 0:ke.trim())!=null?le:"";return/^`{3,}\s*diff(?:\s|$)|^~{3,}\s*diff(?:\s|$)/.test(se)})()&&(de||pe)})(c.value),G=(function(){var fe,de;return((fe=t.node)==null?void 0:fe.originalCode)!=null||((de=t.node)==null?void 0:de.updatedCode)!=null})();if(g.value){const fe=G?(function(de,pe){const X=w(de),re=w(pe),ke=A(X,re);if(ke.length>0){const be=[];let xe=0,Oe=0;for(const Ze of ke){for(;xe=se&&ge>=se&&X[_e]===re[ge];)Le.unshift(Hn(Ht({},C(re[ge])),{key:`inline-suffix-${ge}`,number:ge+1})),_e--,ge--;for(let be=se;be<=_e;be++)le.push(Hn(Ht({},C(X[be],"removed",{preserveBlankKind:M(X,be)})),{key:`inline-removed-source-${be}`,number:be+1}));for(let be=se;be<=ge;be++)le.push(Hn(Ht({},C(re[be],"added",{preserveBlankKind:M(re,be)})),{key:`inline-added-source-${be}`,number:be+1}));return le.concat(Le)})((ie=t.node)==null?void 0:ie.originalCode,(ye=t.node)==null?void 0:ye.updatedCode):(function(de){const pe=[];let X=1,re=1;const ke=S(de);for(const[le,se]of de.entries())if(se.startsWith("@@")){const _e=se.match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);_e&&(X=Number(_e[1]),re=Number(_e[2])),pe.push(Hn(Ht({},C(se,"hunk")),{key:`inline-hunk-${le}`,number:""}))}else if(N(se))pe.push(Hn(Ht({},C(x(se.slice(1),ke),"removed",{preserveBlankKind:!0})),{key:`inline-removed-${le}`,number:X++}));else if(T(se))pe.push(Hn(Ht({},C(x(se.slice(1),ke),"added",{preserveBlankKind:!0})),{key:`inline-added-${le}`,number:re++}));else{const _e=ke&&se.startsWith(" ")?se.slice(1):se;pe.push(Hn(Ht({},C(_e)),{key:`inline-context-${le}`,number:re})),X++,re++}return pe})(c.value);return E([{key:"inline",className:"markstream-pre__diff-pane--inline",lines:fe}])}if(!Me&&G)return(function(fe,de){const pe=w(fe),X=w(de),re=A(pe,X),ke=[],le=[];let se=0,_e=0,ge=0;const Le=(be,xe)=>{const Oe=Math.max(be-se,xe-_e);for(let Ze=0;ZeHn(Ht({},fe),{key:`original-${de}`,number:de+1}))},{key:"modified",className:"markstream-pre__diff-pane--modified",lines:Z.map((fe,de)=>Hn(Ht({},fe),{key:`modified-${de}`,number:de+1}))}])}),R=D(()=>{var ie,ye;if(t.showLineNumbers!==!0)return;let Te=m.value?1:u.value;if(m.value){Te=Math.max(Te,w((ie=t.node)==null?void 0:ie.originalCode).length,w((ye=t.node)==null?void 0:ye.updatedCode).length);for(const Me of I.value)for(const G of Me.lines)typeof G.number=="number"&&(Te=Math.max(Te,G.number))}const Ee=`${Math.max(2,String(Te).length)}ch`;return{"--markstream-pre-line-number-width":Ee,"--markstream-pre-diff-line-number-width":Ee,"--markstream-code-padding-left":"calc(var(--markstream-pre-line-number-padding-left, 2ch) + var(--markstream-pre-line-number-width, 2ch) + var(--markstream-pre-line-number-padding-right, 1ch) + var(--markstream-pre-line-number-separator-width, 2px) + var(--markstream-pre-line-number-gap-to-code, 1ch))"}}),W=D(()=>I.value.some(ie=>ie.lines.some(ye=>ye.kind==="collapsed"))),z=D(()=>{const ie=i.value;return ie?`Code block: ${ie}`:"Code block"}),F=q(null),O=q([]);let B=null,j=!1,$=null;function V(ie){const ye=Number.parseFloat(String(ie??""));return Number.isFinite(ye)&&ye>0?ye:0}function ne(ie,ye){var Te;if(!ie)return ye;if(ie.classList.contains("markstream-pre__diff-line--collapsed"))return 32;const Ee=ie.querySelector(".markstream-pre__diff-content"),Me=Ee?.getBoundingClientRect(),G=(Te=Me?.height)!=null?Te:0;return Math.max(ye,Math.ceil(G))}function K(){j||typeof window>"u"||(B!=null&&window.cancelAnimationFrame(B),B=window.requestAnimationFrame(()=>{B=null,j||(function(){var ie,ye;B=null;const Te=F.value;if(!Te||!m.value||g.value||!Te.classList.contains("is-wrap"))return void(O.value.length&&(O.value=[]));const Ee=(function(de){const pe=window.getComputedStyle(de),X=V(pe.getPropertyValue("--markstream-pre-diff-line-height"));if(X>0)return X;const re=V(pe.lineHeight);return re>0?re:18})(Te),Me=Array.from(Te.querySelectorAll(".markstream-pre__diff-pane--original .markstream-pre__diff-line")),G=Array.from(Te.querySelectorAll(".markstream-pre__diff-pane--modified .markstream-pre__diff-line")),oe=Math.max(Me.length,G.length),Z=[];for(let de=0;de{const X=fe[pe];return X&&Math.abs(de.rowHeight-X.rowHeight)<=.5&&Math.abs(de.originalHeight-X.originalHeight)<=.5&&Math.abs(de.modifiedHeight-X.modifiedHeight)<=.5})||(O.value=Z)})()}))}function ee(ie){$?.disconnect(),$=null,ie&&m.value&&!g.value&&typeof ResizeObserver<"u"&&($=new ResizeObserver(()=>{K()}),$.observe(ie))}function ue(ie,ye){const Te=O.value[ie];if(!Te)return;const Ee=ye==="original"?Te.originalHeight:Te.modifiedHeight;return{"--markstream-pre-diff-synced-row-height":`${Math.ceil(Te.rowHeight)}px`,"--markstream-pre-diff-content-height":`${Math.ceil(Ee)}px`}}return qe(F,ie=>{ee(ie),mt(()=>K())},{flush:"post"}),qe([m,g,I],()=>{ee(F.value),mt(()=>K())},{flush:"post",immediate:!0}),si(()=>{j=!0,B!=null&&(window.cancelAnimationFrame(B),B=null),$?.disconnect(),$=null}),(ie,ye)=>(k(),L("pre",{ref_key:"preRef",ref:F,style:an([y.value,R.value]),class:Pe([o.value,{"markstream-pre--line-numbers":t.showLineNumbers,"markstream-pre--diff-preview":m.value,"markstream-pre--diff-inline":g.value,"markstream-pre--diff-collapsed":W.value}]),"aria-busy":s.value,"aria-label":z.value,"data-language":i.value,"data-markstream-line-numbers":t.showLineNumbers?"1":void 0,"data-markstream-pre":"1",tabindex:"0"},[m.value?(k(),L("code",W9e,[(k(!0),L(Fe,null,xt(I.value,Te=>(k(),L("span",{key:Te.key,class:Pe(["markstream-pre__diff-pane",Te.className])},[_("span",q9e,[(k(!0),L(Fe,null,xt(Te.lines,(Ee,Me)=>(k(),L("span",{key:Ee.key,class:Pe(["markstream-pre__diff-line",[`markstream-pre__diff-line--${Ee.kind}`,{"markstream-pre__diff-line--empty":Ee.empty}]]),style:an(ue(Me,Te.key))},[ye[0]||(ye[0]=_("span",{class:"markstream-pre__diff-rail","aria-hidden":"true"},null,-1)),_("span",U9e,P(Ee.number),1),_("span",V9e,[_("span",K9e,P(Ee.code),1)])],6))),128))])],2))),128))])):(k(),L(Fe,{key:1},[t.showLineNumbers?(k(),L("span",Z9e,[_("span",{class:"markstream-pre__line-numbers-text",textContent:P(p.value)},null,8,G9e)])):J("",!0),_("code",{translate:"no",class:"markstream-pre__code",textContent:P(r.value)},null,8,Q9e)],64))],14,H9e))}});Ol.install=e=>{e.component(Ol.__name,Ol)};const vs=Hi(dt({__name:"TextNode",props:{node:{}},emits:["copy"],setup(e){const t=e,n=Nm(),i=rn("markstreamFade",void 0),o=rn("markstreamTextStreamState",void 0),s=rn("markstreamStreamVersion",void 0),r=D(()=>{const M=n.fade;return M===""||M===!0||M==="true"||M!==!1&&M!=="false"&&void 0}),l=D(()=>typeof r.value=="boolean"?r.value:typeof i?.value!="boolean"||i.value),a=D(()=>{var M;const N=(M=n["index-key"])!=null?M:n.indexKey;return N==null||N===""?"":String(N)}),u=q(t.node.content),c=q(""),d=q(0),h=q(t.node.content);let p;const m=q(null),g=q(null);let y="",b=null;function v(){p?.(),p=void 0}function C(){v(),c.value&&(u.value=u.value+c.value,c.value="")}qe([u,m,g],function(){var M,N;const T=m.value;if(!T)return;const S=String((M=u.value)!=null?M:""),x=g.value;return b||(b=T.firstChild,y=(N=b?.data)!=null?N:""),S.startsWith(y)?!b&&S?(T.textContent=S,b=T.firstChild,void(y=S)):void(S.length>y.length&&x&&(x.appendChild(document.createTextNode(S.slice(y.length))),y=S)):(T.textContent=S,b=T.firstChild,x&&(x.textContent=""),void(y=S))},{immediate:!0}),qe([()=>t.node.content,a,l],([M])=>{const N=String(M??""),T=a.value,S=qW({nextContent:N,persistedContent:T?o?.get(T):void 0,currentState:{settledContent:u.value,streamedDelta:c.value},typewriterEnabled:l.value});u.value=S.settledContent,c.value=S.streamedDelta,S.appended?(d.value+=1,(function(){if(!c.value||p||!s)return;const x=s.value;p=qe(()=>s.value,A=>{A!==x&&C()},{flush:"sync"})})()):c.value||v(),T&&o?.set(T,N)},{immediate:!0}),ad(v);const w=D(()=>d.value%2==0?"text-node-stream-delta--a":"text-node-stream-delta--b");return(M,N)=>(k(),L("span",{class:Pe([[e.node.center?"text-node-center":""],"text-node"])},[mi(_("span",{ref_key:"settledTextEl",ref:m},P(h.value),513),[[hs,u.value!==""]]),mi(_("span",{ref_key:"settledAppendsEl",ref:g},null,512),[[hs,u.value!==""]]),c.value?(k(),L("span",{key:0,class:Pe(["text-node-stream-delta",[w.value]]),onAnimationend:C},P(c.value),35)):J("",!0)],2))}}),[["__scopeId","data-v-fd79037c"]]);function n0(e,t,n){return dt({name:e,inheritAttrs:!1,setup(i,{attrs:o,slots:s}){var r,l;const a=Ax(),u=wx(),c=Cx(),d=typeof window<"u"&&((l=(r=Vs())==null?void 0:r.vnode.el)==null?void 0:l.nodeType)===1,h=q(typeof window>"u"||d||!c.value),p=_u(null);let m=null;function g(y){const b=y&&"$el"in y?y.$el:y;p.value=b instanceof HTMLElement?b:null}return typeof window<"u"&&qe([p,c],([y,b],v,C)=>{if(m?.destroy(),m=null,!b||h.value)return void(h.value=!0);if(!y)return;let w=!0;const M=a(y,{rootMargin:u?.value.heavyBlockMargin,allowIdle:!1});m=M,h.value=M.isVisible.value,M.whenVisible.then(()=>{w&&m===M&&(h.value=!0)}),C(()=>{w=!1,M.destroy(),m===M&&(m=null)})},{immediate:!0}),si(()=>{m?.destroy(),m=null}),()=>jn(h.value?t:n,Hn(Ht({},o),{ref:g}),s)}})}vs.install=e=>{e.component(vs.__name,vs)};const Jk=dt({name:"CodeBlockNodeLoading",inheritAttrs:!1,props:["node","isDark","loading","stream","theme","darkTheme","lightTheme","isShowPreview","monacoOptions","enableFontSizeControl","minWidth","maxWidth","themes","showHeader","showCopyButton","showExpandButton","showPreviewButton","showCollapseButton","showFontSizeButtons","showTooltips","htmlPreviewAllowScripts","htmlPreviewSandbox","customId","estimatedHeightPx","estimatedContentHeightPx","estimatedDiffInline"],emits:["previewCode","copy"],setup(e,{attrs:t}){const n=e;return()=>{var i,o,s,r,l,a,u;const c=M4(String((o=(i=n.node)==null?void 0:i.language)!=null?o:"")),d=xN[c]||(c?c.charAt(0).toUpperCase()+c.slice(1):xN[""]),h=z9e(n.node),p=j9e(String((r=(s=n.node)==null?void 0:s.raw)!=null?r:""),d,h),m=n.monacoOptions,g=h&&((l=n.estimatedDiffInline)!=null?l:xx(m??{},typeof window>"u"?0:window.innerWidth)),y=m?.diffAppearance,b=y==="dark"||y!=="light"&&n.isDark===!0,v=typeof m?.fontSize=="number"&&Number.isFinite(m.fontSize)&&m.fontSize>0?m.fontSize:12,C=typeof m?.lineHeight=="number"&&Number.isFinite(m.lineHeight)&&m.lineHeight>0?m.lineHeight:v===12?18:Math.max(12,Math.round(1.5*v)),w=typeof m?.tabSize=="number"&&Number.isFinite(m.tabSize)&&m.tabSize>0?m.tabSize:4,M=h?0:8,N=typeof((a=m?.padding)==null?void 0:a.top)=="number"&&Number.isFinite(m.padding.top)&&m.padding.top>=0?m.padding.top:M,T=typeof((u=m?.padding)==null?void 0:u.bottom)=="number"&&Number.isFinite(m.padding.bottom)&&m.padding.bottom>=0?m.padding.bottom:M,S=typeof m?.fontFamily=="string"?m.fontFamily.trim():"",x=Ht(Ht({fontSize:`${v}px`,lineHeight:`${C}px`,tabSize:w,paddingTop:`${N}px`,paddingBottom:`${T}px`,"--markstream-pre-line-number-top":`${N}px`},h?{"--markstream-pre-diff-line-height":`${C}px`}:{}),S?{"--markstream-code-font-family":S}:{}),A=()=>jn("button",{class:"code-action-btn inline-flex items-center justify-center p-[var(--ms-action-btn-padding)] rounded leading-none shrink-0","aria-hidden":"true",disabled:!0,tabindex:-1,type:"button"},[jn("svg",{class:"action-icon",width:"14",height:"14"})]),E=n.isShowPreview!==!1&&(c==="html"||c==="svg"),I=n.showFontSizeButtons!==!1&&n.enableFontSizeControl!==!1||n.showExpandButton!==!1||E&&n.showPreviewButton!==!1,R=z=>{if(z!=null)return typeof z=="number"?`${z}px`:String(z)},W=Ht(Ht(Ht({"--markstream-code-layout-character-width":"1ch"},R(n.minWidth)?{minWidth:R(n.minWidth)}:{}),R(n.maxWidth)?{maxWidth:R(n.maxWidth)}:{}),h?{}:{color:"var(--vscode-editor-foreground, var(--markstream-code-fallback-fg, var(--code-fg)))",backgroundColor:"var(--markstream-code-fallback-bg, var(--code-bg, #fff))",borderColor:"var(--markstream-code-border-color, var(--code-border))"});return jn("div",Hn(Ht({},t),{class:["code-block-container","rounded-lg","border",{dark:n.isDark===!0,"is-rendering":n.loading!==!1,"is-dark":b,"is-diff":h,"is-plain-text":c===""||c==="plaintext"||c==="text"},t.class],style:[W,t.style],"data-markstream-code-block":"1","data-markstream-enhanced":"false","data-markstream-code-block-state":n.loading?"streaming":"settled","data-markstream-code-loading":"1"}),[n.showHeader===!1?null:jn("div",{class:"code-block-header flex justify-between items-center border-b px-[var(--ms-inset-panel-x)] py-[var(--ms-inset-panel-y)] border-[var(--code-border)] bg-[var(--code-header-bg)] text-[var(--code-fg)]"},[jn("div",{class:"code-header-main",style:{minWidth:0,flex:"1 1 auto",display:"flex",alignItems:"center",gap:"var(--ms-gap-header-main, 0.625rem)",overflow:"hidden"}},[jn("span",{class:"icon-slot h-4 w-4 flex-shrink-0","aria-hidden":"true",style:{display:"inline-flex",width:"1rem",height:"1rem",flex:"0 0 auto"}}),jn("div",{class:"code-header-copy",style:{minWidth:0,display:"grid",gap:"2px"}},[jn("div",{class:"code-header-title",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"var(--ms-text-label, 0.75rem)",fontWeight:"500",color:"var(--code-action-fg)"}},p.title),p.caption?jn("div",{class:"code-header-caption",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.75rem",color:"var(--code-line-number)"}},p.caption):null])]),jn("div",{class:"flex items-center gap-0.5",style:{visibility:"hidden"}},[h?jn("div",{class:"code-diff-stats","aria-hidden":"true"},[jn("span",{class:"code-diff-stat removed"},"-0"),jn("span",{class:"code-diff-stat added"},"+0")]):null,n.showCopyButton===!1?null:A(),n.showCollapseButton===!1?null:A(),I?jn("div",{class:"relative"},[A()]):null])]),jn("div",{class:"code-block-shell-content",style:n.stream!==!1||n.loading===!1?void 0:{display:"none"}},[jn(Ol,{node:n.node,loading:n.loading,showLineNumbers:!0,reservedHeightPx:h?void 0:n.estimatedContentHeightPx,diffInline:g,diffHideUnchangedRegions:h?B9e(m?.diffHideUnchangedRegions):void 0,class:"code-pre-fallback",style:x,"data-markstream-code-loading":"1"})]),jn("div",{class:"code-loading-placeholder",style:n.stream===!1&&n.loading!==!1?void 0:{display:"none"}},[jn("div",{class:"loading-skeleton"},[jn("div",{class:"skeleton-line"}),jn("div",{class:"skeleton-line"}),jn("div",{class:"skeleton-line short"})])]),jn("span",{class:"sr-only","aria-live":"polite",role:"status"})])}}}),nw=n0("ViewportDeferredCodeBlockNode",Yu({loader:()=>xo(null,null,function*(){try{return(yield _s(()=>import("./CodeBlockNode-BNOCy4ai.js"),__vite__mapDeps([4,5]))).default}catch(e){return console.warn('[markstream-vue] Failed to load the enhanced CodeBlockNode chunk; falling back to preformatted code rendering. Enhanced code blocks require the optional "stream-diffs" peer (or "stream-monaco" as a fallback).',e),Ol}}),loadingComponent:Jk,delay:0,suspensible:!1}),Jk),Iu=Yu(()=>xo(null,null,function*(){var e;if(((e=(function(){const t=Reflect.get(globalThis,"process");return t?.env})())==null?void 0:e.NODE_ENV)==="test"&&typeof window<"u")return t=>{var n,i,o,s;return jn(vs,Hn(Ht({},t),{node:{type:"text",content:(i=t.node.raw)!=null?i:`$${(n=t.node.content)!=null?n:""}$`,raw:(s=t.node.raw)!=null?s:`$${(o=t.node.content)!=null?o:""}$`}}))};try{return yield GW(),(yield _s(()=>import("./index7-N0eJaunx.js"),[])).default}catch(t){console.warn('[markstream-vue] Optional peer dependencies for MathInlineNode are missing. Falling back to text rendering. To enable full math rendering features, please install "katex".',t)}return t=>{var n,i,o,s;return jn(vs,Hn(Ht({},t),{node:{type:"text",content:(i=t.node.raw)!=null?i:`$${(n=t.node.content)!=null?n:""}$`,raw:(s=t.node.raw)!=null?s:`$${(o=t.node.content)!=null?o:""}$`}}))}})),uq=Yu(()=>xo(null,null,function*(){try{return yield GW(),(yield _s(()=>import("./index6-BW9QZVgb.js"),[])).default}catch(e){console.warn('[markstream-vue] Optional peer dependencies for MathBlockNode are missing. Falling back to text rendering. To enable full math rendering features, please install "katex".',e)}return e=>{var t,n,i,o;return jn(vs,Hn(Ht({},e),{node:{type:"text",content:(n=e.node.raw)!=null?n:`$$${(t=e.node.content)!=null?t:""}$$`,raw:(o=e.node.raw)!=null?o:`$$${(i=e.node.content)!=null?i:""}$$`}}))}})),yl=Hi(dt({__name:"ReferenceNode",props:{node:{},messageId:{},threadId:{}},emits:["click","mouseEnter","mouseLeave"],setup:e=>(t,n)=>(k(),L("span",{class:"reference-node cursor-pointer text-xs rounded-md px-1.5 mx-0.5",role:"button",tabindex:"0",onClick:n[0]||(n[0]=i=>t.$emit("click",i,e.node.id,e.messageId,e.threadId)),onMouseenter:n[1]||(n[1]=i=>t.$emit("mouseEnter",i,e.node.id,e.messageId,e.threadId)),onMouseleave:n[2]||(n[2]=i=>t.$emit("mouseLeave",i,e.node.id,e.messageId,e.threadId))},P(e.node.id),33))}),[["__scopeId","data-v-775c65e4"]]);yl.install=e=>{e.component(yl.__name,yl)};const Y9e={class:"superscript-node"},Ul=Hi(dt({__name:"SuperscriptNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>Ht({text:vs,inline_code:il,link:wl,html_inline:ma,strong:kl,emphasis:Cl,footnote_reference:pa,strikethrough:bl,highlight:ga,insert:Kl,subscript:Vl,emoji:ql,math_inline:Iu,reference:yl},n.value));return(o,s)=>(k(),L("sup",Y9e,[(k(!0),L(Fe,null,xt(e.node.children,(r,l)=>(k(),ce(f(mc),{key:`${e.indexKey||"superscript"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"superscript"}-${l}`,"fallback-to-text":""},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-24160b22"]]);Ul.install=e=>{e.component(Ul.__name,Ul)};const J9e={class:"subscript-node"},Vl=Hi(dt({__name:"SubscriptNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>Ht({text:vs,inline_code:il,link:wl,html_inline:ma,strong:kl,emphasis:Cl,footnote_reference:pa,strikethrough:bl,highlight:ga,insert:Kl,superscript:Ul,emoji:ql,math_inline:Iu,reference:yl},n.value));return(o,s)=>(k(),L("sub",J9e,[(k(!0),L(Fe,null,xt(e.node.children,(r,l)=>(k(),ce(f(mc),{key:`${e.indexKey||"subscript"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"subscript"}-${l}`,"fallback-to-text":""},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-197fa13b"]]);Vl.install=e=>{e.component(Vl.__name,Vl)};const X9e={class:"strong-node"},kl=Hi(dt({__name:"StrongNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>Ht({text:vs,inline_code:il,link:wl,html_inline:ma,emphasis:Cl,strikethrough:bl,highlight:ga,insert:Kl,subscript:Vl,superscript:Ul,emoji:ql,footnote_reference:pa,math_inline:Iu,reference:yl},n.value));return(o,s)=>(k(),L("strong",X9e,[(k(!0),L(Fe,null,xt(e.node.children,(r,l)=>(k(),ce(f(mc),{key:`${e.indexKey||"strong"}-${l}`,components:i.value,node:r,"index-key":`${e.indexKey||"strong"}-${l}`,"custom-id":t.customId},null,8,["components","node","index-key","custom-id"]))),128))]))}}),[["__scopeId","data-v-a8647104"]]);kl.install=e=>{e.component(kl.__name,kl)};const eke={class:"strikethrough-node"},bl=Hi(dt({__name:"StrikethroughNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>Ht({text:vs,inline_code:il,link:wl,html_inline:ma,strong:kl,emphasis:Cl,highlight:ga,insert:Kl,subscript:Vl,superscript:Ul,emoji:ql,footnote_reference:pa,math_inline:Iu,reference:yl},n.value));return(o,s)=>(k(),L("del",eke,[(k(!0),L(Fe,null,xt(e.node.children,(r,l)=>(k(),ce(f(mc),{key:`${e.indexKey||"strikethrough"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"strikethrough"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-b7a531fa"]]);bl.install=e=>{e.component(bl.__name,bl)};const tke=["href","title","aria-label","aria-hidden","target","rel"],nke=["aria-hidden"],ike={class:"link-text-wrapper relative inline-flex"},oke={class:"leading-[normal] link-text"},wl=Hi(dt({__name:"LinkNode",props:{node:{},indexKey:{},customId:{},showTooltip:{type:Boolean,default:!0},color:{},underlineHeight:{},underlineBottom:{},animationDuration:{},animationOpacity:{},animationTiming:{},animationIteration:{}},setup(e){const t=e,n=rn("markstreamShowTooltips",void 0),i=D(()=>{const b=n?.value;return typeof b=="boolean"?b:t.showTooltip}),o=D(()=>{var b,v,C,w,M;const N=t.underlineBottom!==void 0?typeof t.underlineBottom=="number"?`${t.underlineBottom}px`:String(t.underlineBottom):"-3px",T=(b=t.animationOpacity)!=null?b:.35,S=Math.max(.12,Math.min(.5*T,T)),x={"--underline-height":`${(v=t.underlineHeight)!=null?v:2}px`,"--underline-bottom":N,"--underline-opacity":String(T),"--underline-rest-opacity":String(S),"--underline-duration":`${(C=t.animationDuration)!=null?C:1.6}s`,"--underline-timing":(w=t.animationTiming)!=null?w:"ease-in-out","--underline-iteration":typeof t.animationIteration=="number"?String(t.animationIteration):(M=t.animationIteration)!=null?M:"infinite"};return t.color&&(x["--link-color"]=t.color),x}),s=Ks(()=>t.customId),r=D(()=>Ht({text:vs,strong:kl,strikethrough:bl,emphasis:Cl,image:ef,html_inline:ma,inline_code:il},s.value)),l=Nm(),a=D(()=>{var b,v;const C=(b=t.node)==null?void 0:b.attrs;if(!C||typeof C!="object")return{};const w={};if(Array.isArray(C))for(const M of C)Array.isArray(M)&&M[0]&&(w[String(M[0])]=String((v=M[1])!=null?v:""));else for(const[M,N]of Object.entries(C))M&&N!=null&&N!==!1&&(w[M]=N===!0?"":String(N));return PN(w,"safe","a")}),u=D(()=>Ht(Ht({},l),a.value)),c=D(()=>{var b,v;return PN({href:String((v=(b=t.node)==null?void 0:b.href)!=null?v:"")},"safe","a").href}),d=D(()=>{if(!c.value)return;const b=u.value.target;return(typeof b=="string"?b.trim():String(b??"").trim())||(z1e(c.value)?"_blank":void 0)}),h=D(()=>{var b;return String((b=d.value)!=null?b:"").trim().toLowerCase()==="_blank"}),p=D(()=>{if(!c.value)return;const b=u.value.rel,v=new Set((typeof b=="string"?b:String(b??"")).split(/\s+/).filter(Boolean)),C=new Set(Array.from(v).filter(w=>w.toLowerCase()!=="opener"));return h.value&&(C.add("noopener"),C.add("noreferrer")),C.size>0?Array.from(C).join(" "):void 0}),m=D(()=>{const b=Ht({},u.value);return delete b.title,delete b.href,delete b.target,delete b.rel,b});function g(){i.value&&x9e()}const y=D(()=>{var b,v;const C=(b=t.node)==null?void 0:b.title;return typeof C=="string"&&C.trim().length>0?C:String((v=c.value)!=null?v:"")});return(b,v)=>{var C,w;return e.node.loading?(k(),L("span",yi({key:1,class:"link-loading inline-flex items-baseline gap-1.5","aria-hidden":e.node.loading?"false":"true"},f(l),{style:o.value}),[_("span",ike,[_("span",oke,[U(f(vs),{class:"leading-[normal] link-text",node:{type:"text",content:String((C=e.node.text)!=null?C:""),raw:String((w=e.node.text)!=null?w:"")},"index-key":`${e.indexKey||"link-text"}-loading`},null,8,["node","index-key"])]),v[1]||(v[1]=_("span",{class:"link-loading-indicator","aria-hidden":"true"},null,-1))])],16,nke)):(k(),L("a",yi({key:0,class:"link-node",href:c.value,title:i.value?"":y.value,"aria-label":`Link: ${y.value}`,"aria-hidden":e.node.loading?"true":"false",target:d.value,rel:p.value},m.value,{style:o.value,onMouseenter:v[0]||(v[0]=M=>(function(N){var T,S,x,A;if(!i.value)return;const E=N,I=E?.clientX!=null&&E?.clientY!=null?{x:E.clientX,y:E.clientY}:void 0,R=((T=t.node)==null?void 0:T.title)||((S=c.value)!=null&&S.includes("xn--")&&((A=(x=t.node)==null?void 0:x.text)!=null&&A.includes("://"))?t.node.text:c.value)||"";A9e(N.currentTarget,R,"top",!1,I)})(M)),onMouseleave:g}),[(k(!0),L(Fe,null,xt(e.node.children,(M,N)=>(k(),ce(f(mc),{key:`${e.indexKey||"emphasis"}-${N}`,components:r.value,node:M,"custom-id":t.customId,"index-key":`${e.indexKey||"link-text"}-${N}`},null,8,["components","node","custom-id","index-key"]))),128))],16,tke))}}}),[["__scopeId","data-v-367e6ca4"]]);wl.install=e=>{e.component(wl.__name,wl)};const ske={class:"insert-node"},Kl=Hi(dt({__name:"InsertNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>Ht({text:vs,inline_code:il,link:wl,html_inline:ma,strong:kl,emphasis:Cl,strikethrough:bl,highlight:ga,subscript:Vl,superscript:Ul,emoji:ql,footnote_reference:pa,math_inline:Iu,reference:yl},n.value));return(o,s)=>(k(),L("ins",ske,[(k(!0),L(Fe,null,xt(e.node.children,(r,l)=>(k(),ce(f(mc),{key:`${e.indexKey||"insert"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"insert"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-1e2c29d4"]]);Kl.install=e=>{e.component(Kl.__name,Kl)};const rke={class:"highlight-node"},ga=Hi(dt({__name:"HighlightNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>Ht({text:vs,inline_code:il,link:wl,html_inline:ma,strong:kl,emphasis:Cl,strikethrough:bl,insert:Kl,subscript:Vl,superscript:Ul,emoji:ql,footnote_reference:pa,math_inline:Iu,reference:yl},n.value));return(o,s)=>(k(),L("mark",rke,[(k(!0),L(Fe,null,xt(e.node.children,(r,l)=>(k(),ce(f(mc),{key:`${e.indexKey||"highlight"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"highlight"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-7a62982a"]]);ga.install=e=>{e.component(ga.__name,ga)};const lke={class:"emphasis-node"},Cl=Hi(dt({__name:"EmphasisNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>Ht({text:vs,inline_code:il,link:wl,html_inline:ma,strong:kl,strikethrough:bl,highlight:ga,insert:Kl,subscript:Vl,superscript:Ul,emoji:ql,footnote_reference:pa,math_inline:Iu,reference:yl},n.value));return(o,s)=>(k(),L("em",lke,[(k(!0),L(Fe,null,xt(e.node.children,(r,l)=>(k(),ce(f(mc),{key:`${e.indexKey||"emphasis"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"emphasis"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-2a5aafbf"]]);Cl.install=e=>{e.component(Cl.__name,Cl)};const ake={class:"hard-break"},tf=Hi(dt({__name:"HardBreakNode",props:{node:{}},setup:e=>(t,n)=>(k(),L("br",ake))}),[["__scopeId","data-v-50c58f70"]]);tf.install=e=>{e.component(tf.__name,tf)};const Mv=dt({__name:"SimpleInlineRenderer",props:{nodes:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ot({checkbox:ha,checkbox_input:ha,emoji:ql,emphasis:Cl,hardbreak:tf,highlight:ga,inline_code:il,insert:Kl,link:wl,reference:yl,strikethrough:bl,strong:kl,subscript:Vl,superscript:Ul,text:vs}),i=Ks(()=>t.customId),o=D(()=>{const s=i.value;return Object.keys(s).length>0?Ht(Ht({},n),s):n});return(s,r)=>(k(!0),L(Fe,null,xt(e.nodes,(l,a)=>(k(),ce(f(mc),{key:a,components:o.value,node:l,"custom-id":t.customId,"index-key":`${e.indexKey||"inline"}-${a}`},null,8,["components","node","custom-id","index-key"]))),128))}});function bA(e){if(!e||typeof e!="object")return!1;const t=`|${e.type}|`;if(!"|checkbox|checkbox_input|emoji|emphasis|hardbreak|highlight|inline_code|insert|link|reference|strikethrough|strong|subscript|superscript|text|".includes(t))return!1;if(!"|emphasis|highlight|insert|link|strikethrough|strong|subscript|superscript|".includes(t))return!0;const n=e.children;return Array.isArray(n)&&n.every(bA)}function Xk(e,t=!0,n=!1){if(!e||!n&&e.length===0)return null;if(e.every(bA))return e;if(!t||e.length!==1)return null;const i=e[0];if(i?.type!=="paragraph"||!Array.isArray(i.children))return null;const o=i.children;return(n||o.length>0)&&o.every(bA)?o:null}function sp(e){var t,n;if(!e?.length)return null;let i="";for(const o of e){if(o?.type!=="text"||o.center===!0)return null;i+=String((n=(t=o.content)!=null?t:o.raw)!=null?n:"")}return i}const uke=["cite"],cke={key:0,dir:"auto",class:"paragraph-node"},dke=["custom-id"],x9=Hi(dt({__name:"BlockquoteNode",props:{node:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},customId:{},showTooltips:{type:Boolean}},emits:["copy"],setup(e){const t=e,n=Ks(()=>t.customId),i=D(()=>!!n.value.paragraph),o=D(()=>!!n.value.text),s=D(()=>Xk(t.node.children,!i.value)),r=D(()=>t.fade!==!1||o.value?null:sp(s.value));return ui("markstreamShowTooltips",D(()=>t.showTooltips)),ui("markstreamFade",D(()=>t.fade)),(l,a)=>(k(),L("blockquote",{class:"blockquote blockquote-node",dir:"auto",cite:e.node.cite},[s.value?(k(),L("p",cke,[r.value!==null?(k(),L("span",{key:0,class:"text-node","custom-id":t.customId},P(r.value),9,dke)):(k(),ce(f(Mv),{key:1,nodes:s.value,"custom-id":t.customId,"index-key":`blockquote-${t.indexKey}-paragraph`},null,8,["nodes","custom-id","index-key"]))])):(k(),ce(f(Zl),{key:1,"show-tooltips":t.showTooltips,"index-key":`blockquote-${t.indexKey}`,nodes:t.node.children||[],"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:a[0]||(a[0]=u=>l.$emit("copy",u))},null,8,["show-tooltips","index-key","nodes","custom-id","typewriter","fade"]))],8,uke))}}),[["__scopeId","data-v-abfecebc"]]);x9.install=e=>{e.component(x9.__name,x9)};const fke={class:"definition-list"},hke={class:"definition-term"},pke={class:"definition-desc"},S9=Hi(dt({__name:"DefinitionListNode",props:{node:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},emits:["copy"],setup(e){const t=e;return(n,i)=>(k(),L("dl",fke,[(k(!0),L(Fe,null,xt(t.node.items,(o,s)=>(k(),L(Fe,{key:s},[_("dt",hke,[U(f(Zl),{"index-key":`definition-term-${t.indexKey}-${s}`,nodes:o.term,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:i[0]||(i[0]=r=>n.$emit("copy",r))},null,8,["index-key","nodes","custom-id","typewriter","fade"])]),_("dd",pke,[U(f(Zl),{"index-key":`definition-desc-${t.indexKey}-${s}`,nodes:o.definition,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:i[1]||(i[1]=r=>n.$emit("copy",r))},null,8,["index-key","nodes","custom-id","typewriter","fade"])])],64))),128))]))}}),[["__scopeId","data-v-4e103b30"]]);S9.install=e=>{e.component(S9.__name,S9)};const mke=["href","title"],P0=Hi(dt({__name:"FootnoteAnchorNode",props:{node:{}},setup(e){const t=e;function n(i){var o;if(i.preventDefault(),typeof document>"u")return;const s=`fnref-${String((o=t.node.id)!=null?o:"")}`,r=document.getElementById(s);r&&r.scrollIntoView({behavior:"smooth",block:"center"})}return(i,o)=>(k(),L("a",{class:"footnote-anchor text-sm hover:underline cursor-pointer",href:`#fnref-${e.node.id}`,title:`返回引用 ${e.node.id}`,onClick:n}," ↩︎ ",8,mke))}}),[["__scopeId","data-v-e1eb37b6"]]);P0.install=e=>{e.component(P0.__name,P0)};const gke=["id"],vke={class:"flex-1"},_9=dt({__name:"FootnoteNode",props:{node:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},emits:["copy"],setup(e){const t=e;return(n,i)=>(k(),L("div",{id:`fnref--${e.node.id}`,class:"footnote-node flex text-sm leading-relaxed border-t border-[var(--footnote-border)] pt-2"},[_("div",vke,[U(f(Zl),{"index-key":`footnote-${t.indexKey}`,nodes:t.node.children,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:i[0]||(i[0]=o=>n.$emit("copy",o))},null,8,["index-key","nodes","custom-id","typewriter","fade"])])],8,gke))}});_9.install=e=>{e.component(_9.__name,_9)};const yke=["custom-id"],wA=Hi(dt({__name:"HeadingNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=Ks(()=>t.customId),i=rn("markstreamFade",void 0),o=D(()=>i?.value!==!1||n.value.text?null:sp(t.node.children)),s=D(()=>Ht({text:vs,inline_code:il,link:wl,image:ef,strong:kl,emphasis:Cl,strikethrough:bl,highlight:ga,insert:Kl,subscript:Vl,superscript:Ul,emoji:ql,checkbox:ha,checkbox_input:ha,footnote_reference:pa,hardbreak:tf,math_inline:Iu,reference:yl},n.value));return(r,l)=>(k(),ce(fs(`h${e.node.level}`),yi({class:["heading-node",[`heading-${e.node.level}`]],dir:"auto"},e.node.attrs),{default:ae(()=>[o.value!==null?(k(),L("span",{key:0,class:"text-node","custom-id":t.customId},P(o.value),9,yke)):(k(!0),L(Fe,{key:1},xt(e.node.children,(a,u)=>(k(),ce(f(mc),{key:u,components:s.value,"custom-id":t.customId,node:a,"index-key":`${e.indexKey||"heading"}-${u}`},null,8,["components","custom-id","node","index-key"]))),128))]),_:1},16,["class"]))}}),[["__scopeId","data-v-7122dbe1"]]),L4=wA;L4.install=e=>{e.component(wA.__name,wA)};const kke={key:0,dir:"auto",class:"paragraph-node"},bke=["custom-id"],wke={dir:"auto",class:"paragraph-node"},Cke=["custom-id"],Z1=Hi(dt({__name:"ListItemNode",props:{node:{},item:{},indexKey:{},customId:{},typewriter:{type:Boolean},fade:{type:Boolean},showTooltips:{type:Boolean},value:{},isDark:{type:Boolean}},emits:["copy"],setup(e){const t=e,n=D(()=>{var p;return(p=t.node)!=null?p:t.item}),i=Ks(()=>t.customId),o=D(()=>!!i.value.paragraph),s=D(()=>!!i.value.text),r=D(()=>{var p;return Xk((p=n.value)==null?void 0:p.children,!o.value)}),l=D(()=>{var p;if(o.value)return null;const m=(p=n.value)==null?void 0:p.children;if(!Array.isArray(m)||m.length<2)return null;const g=m[0];if(g?.type!=="paragraph"||!Array.isArray(g.children))return null;const y=m.slice(1);if(!y.every(v=>v?.type==="list"))return null;const b=Xk([g]);return b?{paragraphChildren:b,nestedLists:y}:null});function a(){return t.fade===!1&&!s.value}const u=D(()=>a()?sp(r.value):null),c=D(()=>{var p;return a()?sp((p=l.value)==null?void 0:p.paragraphChildren):null}),d=Object.freeze({}),h=D(()=>{const{value:p}=t;return typeof p=="number"&&Number.isFinite(p)?{value:p}:d});return ui("markstreamShowTooltips",D(()=>t.showTooltips)),ui("markstreamFade",D(()=>t.fade)),(p,m)=>{var g,y;return k(),L("li",yi({class:"list-item",dir:"auto"},h.value),[r.value?(k(),L("p",kke,[u.value!==null?(k(),L("span",{key:0,class:"text-node","custom-id":t.customId},P(u.value),9,bke)):(k(),ce(f(Mv),{key:1,nodes:r.value,"custom-id":t.customId,"index-key":`list-item-${t.indexKey}-paragraph`},null,8,["nodes","custom-id","index-key"]))])):l.value?(k(),L(Fe,{key:1},[_("p",wke,[c.value!==null?(k(),L("span",{key:0,class:"text-node","custom-id":t.customId},P(c.value),9,Cke)):(k(),ce(f(Mv),{key:1,nodes:l.value.paragraphChildren,"custom-id":t.customId,"index-key":`list-item-${t.indexKey}-paragraph`},null,8,["nodes","custom-id","index-key"]))]),(k(!0),L(Fe,null,xt(l.value.nestedLists,(b,v)=>(k(),ce(f(Zl),{key:v,nodes:[b],"custom-id":t.customId,"index-key":`list-item-${t.indexKey}-nested-${v}`,"show-tooltips":t.showTooltips,typewriter:t.typewriter,fade:t.fade,"is-dark":t.isDark,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0,onCopy:m[0]||(m[0]=C=>p.$emit("copy",C))},null,8,["nodes","custom-id","index-key","show-tooltips","typewriter","fade","is-dark"]))),128))],64)):(k(),ce(f(Zl),{key:2,"show-tooltips":t.showTooltips,"index-key":`list-item-${t.indexKey}`,nodes:(y=(g=n.value)==null?void 0:g.children)!=null?y:[],"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,"is-dark":t.isDark,"batch-rendering":!1,onCopy:m[1]||(m[1]=b=>p.$emit("copy",b))},null,8,["show-tooltips","index-key","nodes","custom-id","typewriter","fade","is-dark"]))],16)}}}),[["__scopeId","data-v-617214f9"]]);Z1.install=e=>{e.component(Z1.__name,Z1)};const G1=Hi(dt({__name:"ListNode",props:{node:{},customId:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},showTooltips:{type:Boolean},isDark:{type:Boolean}},emits:["copy"],setup(e){const t=Ks(()=>e.customId),n=D(()=>t.value.list_item||Z1);return(i,o)=>(k(),ce(fs(e.node.ordered?"ol":"ul"),{class:Pe(["list-node",{"list-decimal":e.node.ordered,"list-disc":!e.node.ordered}])},{default:ae(()=>[(k(!0),L(Fe,null,xt(e.node.items,(s,r)=>{var l;return k(),ce(fs(n.value),yi({key:`${e.indexKey||"list"}-${r}`},{ref_for:!0},{showTooltips:e.showTooltips},{node:s,"custom-id":e.customId,"index-key":`${e.indexKey||"list"}-${r}`,typewriter:e.typewriter,fade:e.fade,"is-dark":e.isDark,value:e.node.ordered?((l=e.node.start)!=null?l:1)+r:void 0,onCopy:o[0]||(o[0]=a=>i.$emit("copy",a))}),null,16,["node","custom-id","index-key","typewriter","fade","is-dark","value"])}),128))]),_:1},8,["class"]))}}),[["__scopeId","data-v-99cb95e0"]]);G1.install=e=>{e.component(G1.__name,G1)};const Ake={key:2,class:"html-block-node__raw"},xke=["innerHTML"],Ske={key:1,class:"html-block-node__placeholder"},$0=Hi(dt({__name:"HtmlBlockNode",props:{node:{},customId:{},htmlPolicy:{}},setup(e){const t=e,n=rn("markstreamHtmlPolicy",void 0),i=rn("markstreamNestedRendererProps",void 0),o=D(()=>{var I,R;return(R=(I=t.htmlPolicy)!=null?I:n?.value)!=null?R:"safe"}),s=D(()=>{var I,R;const W=(I=i?.value)!=null?I:{};return Hn(Ht({},W),{customId:(R=t.customId)!=null?R:W.customId,htmlPolicy:o.value})}),r=Yu({loader:()=>Promise.resolve().then(()=>Fx),suspensible:!1}),l=D(()=>{const I=b9(t.node.attrs,o.value);if(!I)return;const R=D0(I);return Object.keys(R).length>0?R:void 0}),a=D(()=>{const I=String(t.node.tag||"").trim(),R=b9(t.node.attrs,o.value,I);if(!R)return;const W=D0(R);return Object.keys(W).length>0?W:void 0}),u=Ks(()=>t.customId),c=dt({name:"DynamicRenderer",props:{nodes:{type:Array,required:!0}},render(){return this.nodes}}),d=q(null),h=q(typeof window>"u"),p=q(t.node.content),m=D(()=>Array.isArray(t.node.children)?t.node.children:[]),g=D(()=>String(t.node.tag||"div")),y=D(()=>{var I;if(g.value.trim().toLowerCase()!=="details"||(I=t.node.attrs)!=null&&I.some(([W])=>String(W).toLowerCase()==="open"))return null;const R=m.value[0];return R?.type==="html_block"&&String(R.tag||"").toLowerCase()==="summary"?R:null}),b=D(()=>{var I;return sp((I=y.value)==null?void 0:I.children)}),v=D(()=>{const I=y.value;if(!I)return;const R=b9(I.attrs,o.value,"summary");if(!R)return;const W=D0(R);return Object.keys(W).length>0?W:void 0}),C=D(()=>b.value==null?m.value:m.value.slice(1)),w=D(()=>{const I=g.value.trim().toLowerCase();return TH.has(I)||mx(I,o.value)}),M=D(()=>m.value.length>0&&!!t.node.tag&&!w.value),N=D(()=>{var I,R,W;if(M.value)return{mode:"structured"};if(!h.value)return{mode:"html",content:(I=p.value)!=null?I:""};const z=(R=p.value)!=null?R:t.node.content;if(!z)return{mode:"html",content:""};if(o.value==="escape")return{mode:"html",content:K1(z,o.value)};if(t.node.loading){const O=Yk(z,u.value,o.value);return O===null?{mode:"text",content:(W=t.node.raw)!=null?W:z}:{mode:"dynamic",nodes:O}}if(!nq(z,u.value))return{mode:"html",content:K1(z,o.value)};const F=Yk(z,u.value,o.value);return F===null?{mode:"html",content:K1(z,o.value)}:{mode:"dynamic",nodes:F}}),T=Ax(),S=wx(),x=Cx(),A=_u(null),E=!!t.node.loading;return typeof window<"u"?(qe([()=>d.value,()=>S?.value.heavyBlockMargin,()=>S?.value.rootMargin],([I],R,W)=>{var z,F,O,B;if((F=(z=A.value)==null?void 0:z.destroy)==null||F.call(z),A.value=null,!E)return h.value=!0,void(p.value=t.node.content);if(!I)return void(h.value=!1);let j=!0;const $=(B=(O=S?.value.heavyBlockMargin)!=null?O:S?.value.rootMargin)!=null?B:op,V=T(I,{rootMargin:$,allowIdle:!x.value});A.value=V,h.value=h.value||V.isVisible.value,V.whenVisible.then(()=>{j&&A.value===V&&(h.value=!0)}),W(()=>{j=!1,V.destroy(),A.value===V&&(A.value=null)})},{immediate:!0}),qe(()=>t.node.content,I=>{E&&!h.value||(p.value=I)})):h.value=!0,si(()=>{var I,R;(R=(I=A.value)==null?void 0:I.destroy)==null||R.call(I),A.value=null}),(I,R)=>(k(),ce(fs(M.value?g.value:"div"),yi({ref_key:"htmlRef",ref:d,class:"html-block-node","data-markstream-viewport-pending":f(x)&&!h.value?"true":void 0},M.value?a.value:void 0),{default:ae(()=>[h.value?(k(),L(Fe,{key:0},[N.value.mode==="structured"?(k(),L(Fe,{key:0},[b.value!==null?(k(),L(Fe,{key:0},[_("summary",PY(rB(v.value)),P(b.value),17),C.value.length?(k(),ce(f(r),yi({key:0},s.value,{nodes:C.value,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes"])):J("",!0)],64)):(k(),ce(f(r),yi({key:1},s.value,{nodes:m.value,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes"]))],64)):N.value.mode==="dynamic"?(k(),ce(f(c),{key:1,nodes:N.value.nodes},null,8,["nodes"])):N.value.mode==="text"?(k(),L("pre",Ake,P(N.value.content),1)):(k(),L("div",yi({key:3},l.value,{innerHTML:N.value.content}),null,16,xke))],64)):(k(),L("div",Ske,[Gn(I.$slots,"placeholder",{node:e.node},()=>[R[0]||(R[0]=_("span",{class:"html-block-node__placeholder-bar"},null,-1)),R[1]||(R[1]=_("span",{class:"html-block-node__placeholder-bar w-4/5"},null,-1)),R[2]||(R[2]=_("span",{class:"html-block-node__placeholder-bar w-2/3"},null,-1))],!0)]))]),_:3},16,["data-markstream-viewport-pending"]))}}),[["__scopeId","data-v-e140a874"]]);$0.install=e=>{e.component($0.__name,$0)};const _ke={dir:"auto",class:"paragraph-node"},Ike=["custom-id"],Vh=Hi(dt({__name:"ParagraphNode",props:{node:{},customId:{},indexKey:{},customHtmlTags:{},parseOptions:{},customMarkdownIt:{type:Function}},setup(e){const t=e,n=Ks(()=>t.customId),i=rn("markstreamHtmlPolicy",void 0),o=rn("markstreamFade",void 0),s=rn("markstreamParseOptions",void 0),r=rn("markstreamCustomMarkdownIt",void 0),l=rn("markstreamNestedRendererProps",void 0),a=D(()=>{var S;return(S=i?.value)!=null?S:"safe"}),u=D(()=>{var S;return(S=t.parseOptions)!=null?S:s?.value}),c=D(()=>{var S;return(S=t.customMarkdownIt)!=null?S:r?.value}),d=D(()=>{var S,x;return(x=t.customHtmlTags)!=null?x:(S=l?.value)==null?void 0:S.customHtmlTags}),h=D(()=>{var S,x;const A=(S=l?.value)!=null?S:{};return Hn(Ht({},A),{customId:(x=t.customId)!=null?x:A.customId,customHtmlTags:d.value,parseOptions:u.value,customMarkdownIt:c.value,htmlPolicy:a.value})}),p=Yu({loader:()=>Promise.resolve().then(()=>Fx),suspensible:!1});function m(S){var x;return S.type==="text"&&String((x=S.content)!=null?x:"").trim()===""}const g=D(()=>t.node.children.filter(S=>!m(S))),y=D(()=>g.value.length>0&&g.value.every(S=>S.type==="image"||(function(x){var A;const E=(function(I){return I.type==="link"&&Array.isArray(I.children)?I.children.filter(R=>!m(R)):[]})(x);return E.length===1&&((A=E[0])==null?void 0:A.type)==="image"})(S))),b=D(()=>new Set(kp(d.value))),v=D(()=>{if(!y.value||g.value.length<=1)return t.node.children;const S=[];for(let x=0;x0,I=t.node.children.slice(x+1).some(R=>!m(R));E&&I&&S.push(Hn(Ht({},A),{content:" ",raw:" "}))}return S}),C=D(()=>o?.value===!1&&!n.value.text),w=D(()=>C.value?sp(v.value):null);function M(S,x){return{node:S,"index-key":`${t.indexKey}-${x}`,"custom-id":t.customId,"custom-html-tags":d.value}}const N=D(()=>Ht({inline_code:il,image:ef,link:wl,hardbreak:tf,emphasis:Cl,strong:kl,strikethrough:bl,highlight:ga,insert:Kl,subscript:Vl,superscript:Ul,html_inline:ma,html_block:$0,emoji:ql,checkbox:ha,math_inline:Iu,checkbox_input:ha,reference:yl,footnote_anchor:P0,footnote_reference:pa,text:vs},n.value)),T=D(()=>v.value.map((S,x)=>{var A;const E=(function(I){var R,W,z,F;if(I.type==="html_block"||I.type==="html_inline"){const O=String((R=I.tag)!=null?R:"").trim().toLowerCase()||FH(I.content);if(O&&!b.value.has(O)&&RH((W=I.content)!=null?W:I.raw,O)){const B=String((F=(z=I.content)!=null?z:I.raw)!=null?F:"");return{child:{type:"text",content:B,raw:B},component:vs,isCustomComponent:!1}}}return{child:I,component:N.value[I.type],isCustomComponent:!!(n.value[I.type]&&!a2(String(I.type)))}})(S);return Hn(Ht({},E),{index:x,key:`${t.indexKey||"paragraph"}-${x}`,customAttrs:E.isCustomComponent?bx(E.child,a.value):void 0,hasSlotChildren:Array.isArray(E.child.children)&&E.child.children.length>0,slotContent:String((A=E.child.content)!=null?A:""),originalChild:S})}));return(S,x)=>(k(),L("p",_ke,[w.value!==null?(k(),L("span",{key:0,class:"text-node","custom-id":t.customId},P(w.value),9,Ike)):(k(!0),L(Fe,{key:1},xt(T.value,A=>{return k(),L(Fe,{key:A.key},[y.value&&m(A.originalChild)?(k(),L(Fe,{key:0},[He(P((E=A.originalChild,String((I=E.content)!=null?I:""))),1)],64)):A.isCustomComponent?(k(),ce(fs(A.component),yi({key:1,ref_for:!0},A.customAttrs,{node:A.child,loading:A.child.loading,"index-key":A.key,"custom-id":t.customId,"custom-html-tags":d.value,"is-dark":h.value.isDark}),{default:ae(()=>[A.hasSlotChildren?(k(),ce(f(p),yi({key:0,ref_for:!0},h.value,{nodes:A.child.children,"index-key":A.key,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):A.slotContent?(k(),ce(f(p),yi({key:1,ref_for:!0},h.value,{content:A.slotContent,final:!A.child.loading,"index-key":`${A.key}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):J("",!0)]),_:2},1040,["node","loading","index-key","custom-id","custom-html-tags","is-dark"])):(k(),ce(fs(A.component),yi({key:2,ref_for:!0},M(A.child,A.index)),null,16))],64);var E,I}),128))]))}}),[["__scopeId","data-v-c59ff506"]]);Vh.install=e=>{e.component(Vh.__name,Vh)};const Mke={class:"table-node-wrapper"},Tke=["aria-busy"],Eke={key:0},Lke=["custom-id"],Nke=["aria-label","onPointerdown"],Dke=["custom-id"],Fke={key:0,class:"table-node__loading",role:"status","aria-live":"polite"},B0=Hi(dt({__name:"TableNode",props:{node:{},indexKey:{},isDark:{type:Boolean},typewriter:{type:Boolean},fade:{type:Boolean},customId:{},showTooltips:{type:Boolean}},emits:["copy"],setup(e){const t=e,n=D(()=>{var b;return(b=t.node.loading)!=null&&b}),i=D(()=>{var b;return(b=t.node.rows)!=null?b:[]}),o=q(null),s=q([]);let r=null;const l=D(()=>t.node.header.cells.length),a=D(()=>s.value.some(b=>Number.isFinite(b)&&b>0)),u=D(()=>a.value?s.value.map(b=>b>0?{width:`${b}px`}:void 0):[]);ui("markstreamShowTooltips",D(()=>t.showTooltips)),ui("markstreamFade",D(()=>t.fade));const c=Ks(()=>t.customId),d=D(()=>!!c.value.text),h=D(()=>!!c.value.paragraph),p=new WeakMap;function m(b){const v=t.fade===!1&&!d.value,C=!h.value,w=p.get(b);if(w?.children===b.children&&w.textFastPath===v&&w.paragraphFastPath===C)return w.info;const M=Xk(b.children,C,!0),N={simpleChildren:M,plainText:M&&v?sp(M):null};return p.set(b,{children:b.children,textFastPath:v,paragraphFastPath:C,info:N}),N}function g(b){if(!r)return;b.preventDefault();const v=r.startWidth+r.nextStartWidth,C=Math.min(48,Math.floor(v/2)),w=Math.max(C,Math.min(v-C,Math.round(r.startWidth+b.clientX-r.startX))),M=[...r.widths];M[r.index]=w,M[r.index+1]=v-w,s.value=M}function y(){r&&(window.removeEventListener("pointermove",g),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),r=null)}return qe(l,()=>{y(),s.value=[]}),si(y),(b,v)=>(k(),L("div",Mke,[_("table",{ref_key:"tableRef",ref:o,class:Pe(["table-node",{"table-node--loading":n.value}]),"aria-busy":n.value},[a.value?(k(),L("colgroup",Eke,[(k(!0),L(Fe,null,xt(e.node.header.cells,(C,w)=>(k(),L("col",{key:w,style:an(u.value[w])},null,4))),128))])):J("",!0),_("thead",null,[_("tr",null,[(k(!0),L(Fe,null,xt(e.node.header.cells,(C,w)=>(k(),L("th",{key:w,dir:"auto",class:Pe([C.align==="right"?"text-right":C.align==="center"?"text-center":"text-left"])},[m(C).plainText!==null?(k(),L("span",{key:0,class:"text-node","custom-id":t.customId},P(m(C).plainText),9,Lke)):m(C).simpleChildren?(k(),ce(f(Mv),{key:1,nodes:m(C).simpleChildren,"custom-id":t.customId,"index-key":`table-th-${t.indexKey}-${w}`},null,8,["nodes","custom-id","index-key"])):(k(),ce(f(Zl),{key:2,nodes:C.children,"index-key":`table-th-${t.indexKey}`,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,"show-tooltips":t.showTooltips,onCopy:v[0]||(v[0]=M=>b.$emit("copy",M))},null,8,["nodes","index-key","custom-id","typewriter","fade","show-tooltips"])),w(function(N,T){if(T.button!==0)return;const S=(function(){var E;const I=(E=o.value)==null?void 0:E.querySelectorAll("thead th");return Array.from(I??[],R=>Math.round(R.getBoundingClientRect().width))})(),x=S[N],A=S[N+1];x&&A&&(T.preventDefault(),r={index:N,startX:T.clientX,startWidth:x,nextStartWidth:A,widths:S},s.value=S,window.addEventListener("pointermove",g),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y))})(w,M)},null,40,Nke)):J("",!0)],2))),128))])]),_("tbody",null,[(k(!0),L(Fe,null,xt(i.value,(C,w)=>(k(),L("tr",{key:w},[(k(!0),L(Fe,null,xt(C.cells,(M,N)=>(k(),L("td",{key:N,class:Pe([M.align==="right"?"text-right":M.align==="center"?"text-center":"text-left"]),dir:"auto"},[m(M).plainText!==null?(k(),L("span",{key:0,class:"text-node","custom-id":t.customId},P(m(M).plainText),9,Dke)):m(M).simpleChildren?(k(),ce(f(Mv),{key:1,nodes:m(M).simpleChildren,"custom-id":t.customId,"index-key":`table-td-${t.indexKey}-${w}-${N}`},null,8,["nodes","custom-id","index-key"])):(k(),ce(f(Zl),{key:2,nodes:M.children,"index-key":`table-td-${t.indexKey}`,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,"show-tooltips":t.showTooltips,onCopy:v[1]||(v[1]=T=>b.$emit("copy",T))},null,8,["nodes","index-key","custom-id","typewriter","fade","show-tooltips"]))],2))),128))]))),128))])],10,Tke),U(Po,{name:"table-node-fade"},{default:ae(()=>[n.value?(k(),L("div",Fke,[Gn(b.$slots,"loading",{isLoading:n.value},()=>[v[2]||(v[2]=_("span",{class:"table-node__spinner animate-spin","aria-hidden":"true"},null,-1)),v[3]||(v[3]=_("span",{class:"sr-only"},"Loading",-1))],!0)])):J("",!0)]),_:3})]))}}),[["__scopeId","data-v-39f87b5d"]]);B0.install=e=>{e.component(B0.__name,B0)};const Rke={class:"hr-node"},I9=Hi({},[["render",function(e,t){return k(),L("hr",Rke)}],["__scopeId","data-v-39b2349c"]]);I9.install=e=>{e.component(I9.__name,I9)};const Oke={class:"unknown-node"},CA=dt({__name:"FallbackComponent",props:{node:{}},setup:e=>(t,n)=>(k(),L("div",Oke,P(e.node.raw),1))}),M9=Hi(dt({__name:"VmrContainerNode",props:{node:{},indexKey:{},isDark:{type:Boolean},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},setup(e){const t=e,n=D(()=>`vmr-container vmr-container-${t.node.name}`),i=Ks(()=>t.customId),o=D(()=>Ht({text:vs,paragraph:Vh,heading:L4,inline_code:il,link:wl,image:ef,strong:kl,emphasis:Cl,strikethrough:bl,insert:Kl,subscript:Vl,superscript:Ul,checkbox:ha,checkbox_input:ha,hardbreak:tf,math_inline:Iu,reference:yl,list:G1,math_block:uq,table:B0},i.value));return(s,r)=>(k(),L("div",yi({class:n.value},e.node.attrs),[(k(!0),L(Fe,null,xt(e.node.children,(l,a)=>{return k(),ce(fs((u=l.type,o.value[u]||CA)),{key:`${e.indexKey||"vmr-container"}-${a}`,"custom-id":t.customId,node:l,"index-key":`${e.indexKey||"vmr-container"}-${a}`,typewriter:t.typewriter,fade:t.fade},null,8,["custom-id","node","index-key","typewriter","fade"]);var u}),128))],16))}}),[["__scopeId","data-v-911e41c4"]]);M9.install=e=>{e.component(M9.__name,M9)};const Pke=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","ON","ON","ET","ET","ET","ON","ON","ON","ON","ON","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","ON","ET","ET","ET","ET","ON","ON","ON","ON","L","ON","ON","BN","ON","ON","ET","ET","EN","EN","ON","L","ON","ON","ON","EN","L","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L"],VN=[[697,698,"ON"],[706,719,"ON"],[722,735,"ON"],[741,749,"ON"],[751,767,"ON"],[768,879,"NSM"],[884,885,"ON"],[894,894,"ON"],[900,901,"ON"],[903,903,"ON"],[1014,1014,"ON"],[1155,1161,"NSM"],[1418,1418,"ON"],[1421,1422,"ON"],[1423,1423,"ET"],[1424,1424,"R"],[1425,1469,"NSM"],[1470,1470,"R"],[1471,1471,"NSM"],[1472,1472,"R"],[1473,1474,"NSM"],[1475,1475,"R"],[1476,1477,"NSM"],[1478,1478,"R"],[1479,1479,"NSM"],[1480,1535,"R"],[1536,1541,"AN"],[1542,1543,"ON"],[1544,1544,"AL"],[1545,1546,"ET"],[1547,1547,"AL"],[1548,1548,"CS"],[1549,1549,"AL"],[1550,1551,"ON"],[1552,1562,"NSM"],[1563,1610,"AL"],[1611,1631,"NSM"],[1632,1641,"AN"],[1642,1642,"ET"],[1643,1644,"AN"],[1645,1647,"AL"],[1648,1648,"NSM"],[1649,1749,"AL"],[1750,1756,"NSM"],[1757,1757,"AN"],[1758,1758,"ON"],[1759,1764,"NSM"],[1765,1766,"AL"],[1767,1768,"NSM"],[1769,1769,"ON"],[1770,1773,"NSM"],[1774,1775,"AL"],[1776,1785,"EN"],[1786,1808,"AL"],[1809,1809,"NSM"],[1810,1839,"AL"],[1840,1866,"NSM"],[1867,1957,"AL"],[1958,1968,"NSM"],[1969,1983,"AL"],[1984,2026,"R"],[2027,2035,"NSM"],[2036,2037,"R"],[2038,2041,"ON"],[2042,2044,"R"],[2045,2045,"NSM"],[2046,2069,"R"],[2070,2073,"NSM"],[2074,2074,"R"],[2075,2083,"NSM"],[2084,2084,"R"],[2085,2087,"NSM"],[2088,2088,"R"],[2089,2093,"NSM"],[2094,2136,"R"],[2137,2139,"NSM"],[2140,2143,"R"],[2144,2191,"AL"],[2192,2193,"AN"],[2194,2198,"AL"],[2199,2207,"NSM"],[2208,2249,"AL"],[2250,2273,"NSM"],[2274,2274,"AN"],[2275,2306,"NSM"],[2362,2362,"NSM"],[2364,2364,"NSM"],[2369,2376,"NSM"],[2381,2381,"NSM"],[2385,2391,"NSM"],[2402,2403,"NSM"],[2433,2433,"NSM"],[2492,2492,"NSM"],[2497,2500,"NSM"],[2509,2509,"NSM"],[2530,2531,"NSM"],[2546,2547,"ET"],[2555,2555,"ET"],[2558,2558,"NSM"],[2561,2562,"NSM"],[2620,2620,"NSM"],[2625,2626,"NSM"],[2631,2632,"NSM"],[2635,2637,"NSM"],[2641,2641,"NSM"],[2672,2673,"NSM"],[2677,2677,"NSM"],[2689,2690,"NSM"],[2748,2748,"NSM"],[2753,2757,"NSM"],[2759,2760,"NSM"],[2765,2765,"NSM"],[2786,2787,"NSM"],[2801,2801,"ET"],[2810,2815,"NSM"],[2817,2817,"NSM"],[2876,2876,"NSM"],[2879,2879,"NSM"],[2881,2884,"NSM"],[2893,2893,"NSM"],[2901,2902,"NSM"],[2914,2915,"NSM"],[2946,2946,"NSM"],[3008,3008,"NSM"],[3021,3021,"NSM"],[3059,3064,"ON"],[3065,3065,"ET"],[3066,3066,"ON"],[3072,3072,"NSM"],[3076,3076,"NSM"],[3132,3132,"NSM"],[3134,3136,"NSM"],[3142,3144,"NSM"],[3146,3149,"NSM"],[3157,3158,"NSM"],[3170,3171,"NSM"],[3192,3198,"ON"],[3201,3201,"NSM"],[3260,3260,"NSM"],[3276,3277,"NSM"],[3298,3299,"NSM"],[3328,3329,"NSM"],[3387,3388,"NSM"],[3393,3396,"NSM"],[3405,3405,"NSM"],[3426,3427,"NSM"],[3457,3457,"NSM"],[3530,3530,"NSM"],[3538,3540,"NSM"],[3542,3542,"NSM"],[3633,3633,"NSM"],[3636,3642,"NSM"],[3647,3647,"ET"],[3655,3662,"NSM"],[3761,3761,"NSM"],[3764,3772,"NSM"],[3784,3790,"NSM"],[3864,3865,"NSM"],[3893,3893,"NSM"],[3895,3895,"NSM"],[3897,3897,"NSM"],[3898,3901,"ON"],[3953,3966,"NSM"],[3968,3972,"NSM"],[3974,3975,"NSM"],[3981,3991,"NSM"],[3993,4028,"NSM"],[4038,4038,"NSM"],[4141,4144,"NSM"],[4146,4151,"NSM"],[4153,4154,"NSM"],[4157,4158,"NSM"],[4184,4185,"NSM"],[4190,4192,"NSM"],[4209,4212,"NSM"],[4226,4226,"NSM"],[4229,4230,"NSM"],[4237,4237,"NSM"],[4253,4253,"NSM"],[4957,4959,"NSM"],[5008,5017,"ON"],[5120,5120,"ON"],[5760,5760,"WS"],[5787,5788,"ON"],[5906,5908,"NSM"],[5938,5939,"NSM"],[5970,5971,"NSM"],[6002,6003,"NSM"],[6068,6069,"NSM"],[6071,6077,"NSM"],[6086,6086,"NSM"],[6089,6099,"NSM"],[6107,6107,"ET"],[6109,6109,"NSM"],[6128,6137,"ON"],[6144,6154,"ON"],[6155,6157,"NSM"],[6158,6158,"BN"],[6159,6159,"NSM"],[6277,6278,"NSM"],[6313,6313,"NSM"],[6432,6434,"NSM"],[6439,6440,"NSM"],[6450,6450,"NSM"],[6457,6459,"NSM"],[6464,6464,"ON"],[6468,6469,"ON"],[6622,6655,"ON"],[6679,6680,"NSM"],[6683,6683,"NSM"],[6742,6742,"NSM"],[6744,6750,"NSM"],[6752,6752,"NSM"],[6754,6754,"NSM"],[6757,6764,"NSM"],[6771,6780,"NSM"],[6783,6783,"NSM"],[6832,6877,"NSM"],[6880,6891,"NSM"],[6912,6915,"NSM"],[6964,6964,"NSM"],[6966,6970,"NSM"],[6972,6972,"NSM"],[6978,6978,"NSM"],[7019,7027,"NSM"],[7040,7041,"NSM"],[7074,7077,"NSM"],[7080,7081,"NSM"],[7083,7085,"NSM"],[7142,7142,"NSM"],[7144,7145,"NSM"],[7149,7149,"NSM"],[7151,7153,"NSM"],[7212,7219,"NSM"],[7222,7223,"NSM"],[7376,7378,"NSM"],[7380,7392,"NSM"],[7394,7400,"NSM"],[7405,7405,"NSM"],[7412,7412,"NSM"],[7416,7417,"NSM"],[7616,7679,"NSM"],[8125,8125,"ON"],[8127,8129,"ON"],[8141,8143,"ON"],[8157,8159,"ON"],[8173,8175,"ON"],[8189,8190,"ON"],[8192,8202,"WS"],[8203,8205,"BN"],[8207,8207,"R"],[8208,8231,"ON"],[8232,8232,"WS"],[8233,8233,"B"],[8234,8238,"BN"],[8239,8239,"CS"],[8240,8244,"ET"],[8245,8259,"ON"],[8260,8260,"CS"],[8261,8286,"ON"],[8287,8287,"WS"],[8288,8303,"BN"],[8304,8304,"EN"],[8308,8313,"EN"],[8314,8315,"ES"],[8316,8318,"ON"],[8320,8329,"EN"],[8330,8331,"ES"],[8332,8334,"ON"],[8352,8399,"ET"],[8400,8432,"NSM"],[8448,8449,"ON"],[8451,8454,"ON"],[8456,8457,"ON"],[8468,8468,"ON"],[8470,8472,"ON"],[8478,8483,"ON"],[8485,8485,"ON"],[8487,8487,"ON"],[8489,8489,"ON"],[8494,8494,"ET"],[8506,8507,"ON"],[8512,8516,"ON"],[8522,8525,"ON"],[8528,8543,"ON"],[8585,8587,"ON"],[8592,8721,"ON"],[8722,8722,"ES"],[8723,8723,"ET"],[8724,9013,"ON"],[9083,9108,"ON"],[9110,9257,"ON"],[9280,9290,"ON"],[9312,9351,"ON"],[9352,9371,"EN"],[9450,9899,"ON"],[9901,10239,"ON"],[10496,11123,"ON"],[11126,11263,"ON"],[11493,11498,"ON"],[11503,11505,"NSM"],[11513,11519,"ON"],[11647,11647,"NSM"],[11744,11775,"NSM"],[11776,11869,"ON"],[11904,11929,"ON"],[11931,12019,"ON"],[12032,12245,"ON"],[12272,12287,"ON"],[12288,12288,"WS"],[12289,12292,"ON"],[12296,12320,"ON"],[12330,12333,"NSM"],[12336,12336,"ON"],[12342,12343,"ON"],[12349,12351,"ON"],[12441,12442,"NSM"],[12443,12444,"ON"],[12448,12448,"ON"],[12539,12539,"ON"],[12736,12773,"ON"],[12783,12783,"ON"],[12829,12830,"ON"],[12880,12895,"ON"],[12924,12926,"ON"],[12977,12991,"ON"],[13004,13007,"ON"],[13175,13178,"ON"],[13278,13279,"ON"],[13311,13311,"ON"],[19904,19967,"ON"],[42128,42182,"ON"],[42509,42511,"ON"],[42607,42610,"NSM"],[42611,42611,"ON"],[42612,42621,"NSM"],[42622,42623,"ON"],[42654,42655,"NSM"],[42736,42737,"NSM"],[42752,42785,"ON"],[42888,42888,"ON"],[43010,43010,"NSM"],[43014,43014,"NSM"],[43019,43019,"NSM"],[43045,43046,"NSM"],[43048,43051,"ON"],[43052,43052,"NSM"],[43064,43065,"ET"],[43124,43127,"ON"],[43204,43205,"NSM"],[43232,43249,"NSM"],[43263,43263,"NSM"],[43302,43309,"NSM"],[43335,43345,"NSM"],[43392,43394,"NSM"],[43443,43443,"NSM"],[43446,43449,"NSM"],[43452,43453,"NSM"],[43493,43493,"NSM"],[43561,43566,"NSM"],[43569,43570,"NSM"],[43573,43574,"NSM"],[43587,43587,"NSM"],[43596,43596,"NSM"],[43644,43644,"NSM"],[43696,43696,"NSM"],[43698,43700,"NSM"],[43703,43704,"NSM"],[43710,43711,"NSM"],[43713,43713,"NSM"],[43756,43757,"NSM"],[43766,43766,"NSM"],[43882,43883,"ON"],[44005,44005,"NSM"],[44008,44008,"NSM"],[44013,44013,"NSM"],[64285,64285,"R"],[64286,64286,"NSM"],[64287,64296,"R"],[64297,64297,"ES"],[64298,64335,"R"],[64336,64450,"AL"],[64451,64466,"ON"],[64467,64829,"AL"],[64830,64847,"ON"],[64848,64911,"AL"],[64912,64913,"ON"],[64914,64967,"AL"],[64968,64975,"ON"],[64976,65007,"BN"],[65008,65020,"AL"],[65021,65023,"ON"],[65024,65039,"NSM"],[65040,65049,"ON"],[65056,65071,"NSM"],[65072,65103,"ON"],[65104,65104,"CS"],[65105,65105,"ON"],[65106,65106,"CS"],[65108,65108,"ON"],[65109,65109,"CS"],[65110,65118,"ON"],[65119,65119,"ET"],[65120,65121,"ON"],[65122,65123,"ES"],[65124,65126,"ON"],[65128,65128,"ON"],[65129,65130,"ET"],[65131,65131,"ON"],[65136,65278,"AL"],[65279,65279,"BN"],[65281,65282,"ON"],[65283,65285,"ET"],[65286,65290,"ON"],[65291,65291,"ES"],[65292,65292,"CS"],[65293,65293,"ES"],[65294,65295,"CS"],[65296,65305,"EN"],[65306,65306,"CS"],[65307,65312,"ON"],[65339,65344,"ON"],[65371,65381,"ON"],[65504,65505,"ET"],[65506,65508,"ON"],[65509,65510,"ET"],[65512,65518,"ON"],[65520,65528,"BN"],[65529,65533,"ON"],[65534,65535,"BN"],[65793,65793,"ON"],[65856,65932,"ON"],[65936,65948,"ON"],[65952,65952,"ON"],[66045,66045,"NSM"],[66272,66272,"NSM"],[66273,66299,"EN"],[66422,66426,"NSM"],[67584,67870,"R"],[67871,67871,"ON"],[67872,68096,"R"],[68097,68099,"NSM"],[68100,68100,"R"],[68101,68102,"NSM"],[68103,68107,"R"],[68108,68111,"NSM"],[68112,68151,"R"],[68152,68154,"NSM"],[68155,68158,"R"],[68159,68159,"NSM"],[68160,68324,"R"],[68325,68326,"NSM"],[68327,68408,"R"],[68409,68415,"ON"],[68416,68863,"R"],[68864,68899,"AL"],[68900,68903,"NSM"],[68904,68911,"AL"],[68912,68921,"AN"],[68922,68927,"AL"],[68928,68937,"AN"],[68938,68968,"R"],[68969,68973,"NSM"],[68974,68974,"ON"],[68975,69215,"R"],[69216,69246,"AN"],[69247,69290,"R"],[69291,69292,"NSM"],[69293,69311,"R"],[69312,69327,"AL"],[69328,69336,"ON"],[69337,69369,"AL"],[69370,69375,"NSM"],[69376,69423,"R"],[69424,69445,"AL"],[69446,69456,"NSM"],[69457,69487,"AL"],[69488,69505,"R"],[69506,69509,"NSM"],[69510,69631,"R"],[69633,69633,"NSM"],[69688,69702,"NSM"],[69714,69733,"ON"],[69744,69744,"NSM"],[69747,69748,"NSM"],[69759,69761,"NSM"],[69811,69814,"NSM"],[69817,69818,"NSM"],[69826,69826,"NSM"],[69888,69890,"NSM"],[69927,69931,"NSM"],[69933,69940,"NSM"],[70003,70003,"NSM"],[70016,70017,"NSM"],[70070,70078,"NSM"],[70089,70092,"NSM"],[70095,70095,"NSM"],[70191,70193,"NSM"],[70196,70196,"NSM"],[70198,70199,"NSM"],[70206,70206,"NSM"],[70209,70209,"NSM"],[70367,70367,"NSM"],[70371,70378,"NSM"],[70400,70401,"NSM"],[70459,70460,"NSM"],[70464,70464,"NSM"],[70502,70508,"NSM"],[70512,70516,"NSM"],[70587,70592,"NSM"],[70606,70606,"NSM"],[70608,70608,"NSM"],[70610,70610,"NSM"],[70625,70626,"NSM"],[70712,70719,"NSM"],[70722,70724,"NSM"],[70726,70726,"NSM"],[70750,70750,"NSM"],[70835,70840,"NSM"],[70842,70842,"NSM"],[70847,70848,"NSM"],[70850,70851,"NSM"],[71090,71093,"NSM"],[71100,71101,"NSM"],[71103,71104,"NSM"],[71132,71133,"NSM"],[71219,71226,"NSM"],[71229,71229,"NSM"],[71231,71232,"NSM"],[71264,71276,"ON"],[71339,71339,"NSM"],[71341,71341,"NSM"],[71344,71349,"NSM"],[71351,71351,"NSM"],[71453,71453,"NSM"],[71455,71455,"NSM"],[71458,71461,"NSM"],[71463,71467,"NSM"],[71727,71735,"NSM"],[71737,71738,"NSM"],[71995,71996,"NSM"],[71998,71998,"NSM"],[72003,72003,"NSM"],[72148,72151,"NSM"],[72154,72155,"NSM"],[72160,72160,"NSM"],[72193,72198,"NSM"],[72201,72202,"NSM"],[72243,72248,"NSM"],[72251,72254,"NSM"],[72263,72263,"NSM"],[72273,72278,"NSM"],[72281,72283,"NSM"],[72330,72342,"NSM"],[72344,72345,"NSM"],[72544,72544,"NSM"],[72546,72548,"NSM"],[72550,72550,"NSM"],[72752,72758,"NSM"],[72760,72765,"NSM"],[72850,72871,"NSM"],[72874,72880,"NSM"],[72882,72883,"NSM"],[72885,72886,"NSM"],[73009,73014,"NSM"],[73018,73018,"NSM"],[73020,73021,"NSM"],[73023,73029,"NSM"],[73031,73031,"NSM"],[73104,73105,"NSM"],[73109,73109,"NSM"],[73111,73111,"NSM"],[73459,73460,"NSM"],[73472,73473,"NSM"],[73526,73530,"NSM"],[73536,73536,"NSM"],[73538,73538,"NSM"],[73562,73562,"NSM"],[73685,73692,"ON"],[73693,73696,"ET"],[73697,73713,"ON"],[78912,78912,"NSM"],[78919,78933,"NSM"],[90398,90409,"NSM"],[90413,90415,"NSM"],[92912,92916,"NSM"],[92976,92982,"NSM"],[94031,94031,"NSM"],[94095,94098,"NSM"],[94178,94178,"ON"],[94180,94180,"NSM"],[113821,113822,"NSM"],[113824,113827,"BN"],[117760,117973,"ON"],[118e3,118009,"EN"],[118010,118012,"ON"],[118016,118451,"ON"],[118458,118480,"ON"],[118496,118512,"ON"],[118528,118573,"NSM"],[118576,118598,"NSM"],[119143,119145,"NSM"],[119155,119162,"BN"],[119163,119170,"NSM"],[119173,119179,"NSM"],[119210,119213,"NSM"],[119273,119274,"ON"],[119296,119361,"ON"],[119362,119364,"NSM"],[119365,119365,"ON"],[119552,119638,"ON"],[120513,120513,"ON"],[120539,120539,"ON"],[120571,120571,"ON"],[120597,120597,"ON"],[120629,120629,"ON"],[120655,120655,"ON"],[120687,120687,"ON"],[120713,120713,"ON"],[120745,120745,"ON"],[120771,120771,"ON"],[120782,120831,"EN"],[121344,121398,"NSM"],[121403,121452,"NSM"],[121461,121461,"NSM"],[121476,121476,"NSM"],[121499,121503,"NSM"],[121505,121519,"NSM"],[122880,122886,"NSM"],[122888,122904,"NSM"],[122907,122913,"NSM"],[122915,122916,"NSM"],[122918,122922,"NSM"],[123023,123023,"NSM"],[123184,123190,"NSM"],[123566,123566,"NSM"],[123628,123631,"NSM"],[123647,123647,"ET"],[124140,124143,"NSM"],[124398,124399,"NSM"],[124643,124643,"NSM"],[124646,124646,"NSM"],[124654,124655,"NSM"],[124661,124661,"NSM"],[124928,125135,"R"],[125136,125142,"NSM"],[125143,125251,"R"],[125252,125258,"NSM"],[125259,126063,"R"],[126064,126143,"AL"],[126144,126207,"R"],[126208,126287,"AL"],[126288,126463,"R"],[126464,126703,"AL"],[126704,126705,"ON"],[126706,126719,"AL"],[126720,126975,"R"],[126976,127019,"ON"],[127024,127123,"ON"],[127136,127150,"ON"],[127153,127167,"ON"],[127169,127183,"ON"],[127185,127221,"ON"],[127232,127242,"EN"],[127243,127247,"ON"],[127279,127279,"ON"],[127338,127343,"ON"],[127405,127405,"ON"],[127584,127589,"ON"],[127744,128728,"ON"],[128732,128748,"ON"],[128752,128764,"ON"],[128768,128985,"ON"],[128992,129003,"ON"],[129008,129008,"ON"],[129024,129035,"ON"],[129040,129095,"ON"],[129104,129113,"ON"],[129120,129159,"ON"],[129168,129197,"ON"],[129200,129211,"ON"],[129216,129217,"ON"],[129232,129240,"ON"],[129280,129623,"ON"],[129632,129645,"ON"],[129648,129660,"ON"],[129664,129674,"ON"],[129678,129734,"ON"],[129736,129736,"ON"],[129741,129756,"ON"],[129759,129770,"ON"],[129775,129784,"ON"],[129792,129938,"ON"],[129940,130031,"ON"],[130032,130041,"EN"],[130042,130042,"ON"],[131070,131071,"BN"],[196606,196607,"BN"],[262142,262143,"BN"],[327678,327679,"BN"],[393214,393215,"BN"],[458750,458751,"BN"],[524286,524287,"BN"],[589822,589823,"BN"],[655358,655359,"BN"],[720894,720895,"BN"],[786430,786431,"BN"],[851966,851967,"BN"],[917502,917759,"BN"],[917760,917999,"NSM"],[918e3,921599,"BN"],[983038,983039,"BN"],[1048574,1048575,"BN"],[1114110,1114111,"BN"]];function $ke(e){if(e<=255)return Pke[e];let t=0,n=VN.length-1;for(;t<=n;){const i=t+n>>1,o=VN[i];if(eo[1]))return o[2];t=i+1}}return"L"}const Bke=/[ \t\n\r\f]+/g,zke=/[\t\n\r\f]| {2,}|^ | $/;let iw=null;const jke=new RegExp("\\p{Script=Arabic}","u"),yf=new RegExp("\\p{M}","u"),Sx=new RegExp("\\p{Nd}","u");function KN(e){return jke.test(e)}function ZN(e){return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=183984&&e<=191471||e>=191472&&e<=192093||e>=194560&&e<=195103||e>=196608&&e<=201551||e>=201552&&e<=205743||e>=205744&&e<=210041||e>=63744&&e<=64255||e>=12288&&e<=12351||e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12592&&e<=12687||e>=44032&&e<=55215||e>=65280&&e<=65519}function Xu(e){for(let t=0;t=55296&&n<=56319&&t+1=56320&&i<=57343){if(ZN(i-56320+(n-55296<<10)+65536))return!0;t++;continue}}if(ZN(n))return!0}}return!1}const Hke=new Set([" "," ","⁠","\uFEFF"]),Wke=new Set(["-","‐","–","—"]);function cq(e,t){return!((function(n){const i=z0(n);return i!==null&&Hke.has(i)})(e)||t&&((function(n){const i=z0(n);return i!==null&&(_x.has(i)||rp.has(i))})(e)||(function(n){const i=z0(n);return i!==null&&Wke.has(i)})(e)))}const _x=new Set([",",".","!",":",";","?","、","。","・",")","〕","〉","》","」","』","】","〗","〙","〛","ー","々","〻","ゝ","ゞ","ヽ","ヾ"]),N4=new Set(['"',"(","[","{","¡","¿","“","‘","‚","„","«","‹","⸘","(","〔","〈","《","「","『","【","〖","〘","〚"]),Ix=new Set(["'","’"]),rp=new Set([".",",","!","?",":",";","،","؛","؟","।","॥","၊","။","၌","၍","၏",")","]","}","%",'"',"”","’","»","›","…"]),qke=new Set([":",".","،","؛"]),Uke=new Set(["၏"]),Vke=new Set(["”","’","»","›","」","』","】","》","〉","〕",")"]);function Kke(e){if(Mx(e))return!0;let t=!1;for(const n of e)if(rp.has(n)||tb(n))t=!0;else if(!t||!yf.test(n))return!1;return t}function Zke(e){for(const t of e)if(!_x.has(t)&&!rp.has(t))return!1;return e.length>0}function Gke(e){if(Mx(e))return!0;for(const t of e)if(!(N4.has(t)||Ix.has(t)||yf.test(t)||tb(t)))return!1;return e.length>0}function Mx(e){let t=!1;for(const n of e)if(n!=="\\"&&!yf.test(n)){if(!(N4.has(n)||rp.has(n)||Ix.has(n)))return!1;t=!0}return t}function eb(e,t){const n=t-1;if(n<=0)return Math.max(n,0);const i=e.charCodeAt(n);if(i<56320||i>57343)return n;const o=n-1;if(o<0)return n;const s=e.charCodeAt(o);return s>=55296&&s<=56319?o:n}function z0(e){if(e.length===0)return null;const t=eb(e,e.length);return e.slice(t)}const Qke=[36,37,43,43,92,92,162,165,176,177,1423,1423,1545,1547,1642,1642,2046,2047,2546,2547,2553,2555,2801,2801,3065,3065,3449,3449,3647,3647,6107,6107,8240,8247,8279,8279,8352,8399,8451,8451,8457,8457,8470,8470,8722,8723,43064,43064,65020,65020,65129,65130,65284,65285,65504,65505,65509,65510,73693,73696,123647,123647,126124,126124,126128,126128];function tb(e){const t=e.codePointAt(0);return t!==void 0&&(function(n,i){for(let o=0;o=i[o]&&n<=i[o+1])return!0;return!1})(t,Qke)}function Yke(e){const t=(function(n){for(const i of n)if(!yf.test(i))return i;return null})(e);return t!==null&&Sx.test(t)}function Jke(e){const t=Array.from(e);let n=t.length;for(;n>0;){const i=t[n-1];if(yf.test(i))n--;else{if(!N4.has(i)&&!Ix.has(i))break;n--}}return n<=0||n===t.length?null:{head:t.slice(0,n).join(""),tail:t.slice(n).join("")}}function Xke(e,t,n){return n!=="text"||t||e.length!==1||e==="-"||e==="—"?null:e}function GN(e,t,n,i){const o=t[i],s=e[i];if(o==null)return s;const r=n[i];if(s.length===r)return s;const l=o.repeat(r);return e[i]=l,l}function QN(e,t){return e&&t!==null&&qke.has(t)}function ebe(e){const t=z0(e);return t!==null&&Uke.has(t)}function tbe(e){if(e.length<2||e[0]!==" ")return null;const t=e.slice(1);return new RegExp("^\\p{M}+$","u").test(t)?{space:" ",marks:t}:null}function AA(e){let t=e.length;for(;t>0;){const n=eb(e,t),i=e.slice(n,t);if(Vke.has(i))return!0;if(!rp.has(i))return!1;t=n}return!1}function nbe(e,t){if(t.preserveOrdinarySpaces||t.preserveHardBreaks){if(e===" ")return"preserved-space";if(e===" ")return"tab";if(t.preserveHardBreaks&&e===` -`)return"hard-break"}return e===" "?"space":e===" "||e===" "||e==="⁠"||e==="\uFEFF"?"glue":e==="​"?"zero-width-break":e==="­"?"soft-hyphen":"text"}const ibe=/[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;function lu(e){return e.length===1?e[0]:e.join("")}function obe(e,t){const n=[];for(let i=e.length-1;i>=0;i--)n.push(e[i]);return n.push(t),lu(n)}function sbe(e,t,n,i){if(!ibe.test(e))return[{text:e,isWordLike:t,kind:"text",start:n}];const o=[];let s=null,r=[],l=n,a=!1,u=0;for(const c of e){const d=nbe(c,i),h=d==="text"&&t;s===null||d!==s||h!==a?(s!==null&&o.push({text:lu(r),isWordLike:a,kind:s,start:l}),s=d,r=[c],l=n+u,a=h,u+=c.length):(r.push(c),u+=c.length)}return s!==null&&o.push({text:lu(r),isWordLike:a,kind:s,start:l}),o}function ow(e){return e==="space"||e==="preserved-space"||e==="zero-width-break"||e==="hard-break"}const rbe=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function lbe(e,t){const n=e.texts[t];return!!n.startsWith("www.")||rbe.test(n)&&t+1=33&&n<=47&&n!==45||n>=58&&n<=64&&n!==63||n>=91&&n<=96||n>=123&&n<=126})(t):!fbe.has(e)&&!dbe.test(e)&&cbe.test(e)}function YN(e){let t=!1;for(const n of e)if(!yf.test(n)){if(!dq(n))return!1;t=!0}return t}function hbe(e,t,n,i){const o=!t&&YN(e),s=!i&&YN(n),r=(function(a){const u=(function(c){for(let d=c.length;d>0;){const h=eb(c,d),p=c.slice(h,d);if(!yf.test(p))return p;d=h}return null})(a);return u!==null&&tb(u)})(e),l=(t||r)&&(function(a){for(let u=a.length;u>0;){const c=eb(a,u),d=a.slice(c,u);if(!yf.test(d))return dq(d)||tb(d);u=c}return!1})(e);return!!(o||s||l)&&!Xu(e)&&!Xu(n)&&(t||o||r)&&(i||s)}function JN(e){for(const t of e)if(Sx.test(t))return!0;return!1}function T9(e){if(e.length===0)return!1;for(const t of e)if(!Sx.test(t)&&!ube.has(t))return!1;return!0}function pbe(e,t){if(e.len===0)return[];if(!t.preserveHardBreaks)return[{startSegmentIndex:0,endSegmentIndex:e.len,consumedEndSegmentIndex:e.len}];const n=[];let i=0;for(let o=0;o0&&u.charCodeAt(u.length-1)===32&&(u=u.slice(0,-1)),u})(e);if(s.length===0)return{normalized:s,chunks:[],len:0,texts:[],isWordLike:[],kinds:[],starts:[]};const r=(function(a,u,c){var d,h,p;const m=(iw===null&&(iw=new Intl.Segmenter(void 0,{granularity:"word"})),iw);let g=0;const y=[],b=[],v=[],C=[],w=[],M=[],N=[],T=[],S=[],x=[],A=[],E=[];for(const F of m.segment(a))for(const O of sbe(F.segment,(d=F.isWordLike)!=null&&d,F.index,c)){let B=function(){M[ie]!==null&&(b[ie]=[GN(y,M,N,ie)],M[ie]=null),b[ie].push(O.text),v[ie]=v[ie]||O.isWordLike,T[ie]=T[ie]||V,S[ie]=S[ie]||ne,x[ie]=ee,A[ie]=ue,E[ie]=QN(S[ie],K)};const j=O.kind==="text",$=Xke(O.text,O.isWordLike,O.kind),V=Xu(O.text),ne=KN(O.text),K=z0(O.text),ee=AA(O.text),ue=ebe(O.text),ie=g-1;u.carryCJKAfterClosingQuote&&j&&g>0&&C[ie]==="text"&&V&&T[ie]&&x[ie]||j&&g>0&&C[ie]==="text"&&Zke(O.text)&&T[ie]||j&&g>0&&C[ie]==="text"&&A[ie]?B():j&&g>0&&C[ie]==="text"&&O.isWordLike&&ne&&E[ie]?(B(),v[ie]=!0):$!==null&&g>0&&C[ie]==="text"&&M[ie]===$?N[ie]=((h=N[ie])!=null?h:1)+1:j&&!O.isWordLike&&g>0&&C[ie]==="text"&&!T[ie]&&(Kke(O.text)||O.text==="-"&&v[ie])?B():(y[g]=O.text,b[g]=[O.text],v[g]=O.isWordLike,C[g]=O.kind,w[g]=O.start,M[g]=$,N[g]=$===null?0:1,T[g]=V,S[g]=ne,x[g]=ee,A[g]=ue,E[g]=QN(ne,K),g++)}for(let F=0;Fnull);let R=-1;for(let F=g-1;F>=0;F--){const O=y[F];if(O.length!==0){if(C[F]==="text"&&!v[F]&&R>=0&&C[R]==="text"&&(Gke(O)||O==="-"&&Yke(y[R]))){const B=(p=I[R])!=null?p:[];B.push(O),I[R]=B,w[R]=w[F],y[F]="";continue}R=F}}for(let F=0;FV+1){O.push(lu(ue)),B.push(ye),j.push("text"),$.push(F.starts[V]),V=ie;continue}}O.push(ne),B.push(ee),j.push(K),$.push(F.starts[V]),V++}return{len:O.length,texts:O,isWordLike:B,kinds:j,starts:$}})((function(F){const O=[],B=[],j=[],$=[];for(let V=0;V1;for(let ue=0;ue=F.len||ow(F.kinds[K]))continue;const ee=[],ue=F.starts[K];let ie=K;for(;ie0&&(O.push(lu(ee)),B.push(!0),j.push("text"),$.push(ue),V=ie-1)}return{len:O.length,texts:O,isWordLike:B,kinds:j,starts:$}})((function(F){const O=F.texts.slice(),B=F.isWordLike.slice(),j=F.kinds.slice(),$=F.starts.slice();for(let ne=0;ne=0&&!cq(u.texts[C-1],c)&&v(C),g<0&&(g=C),y=y||Xu(w))}return v(u.len),{len:d.length,texts:d,isWordLike:h,kinds:p,starts:m}})(s,r,t.breakKeepAllAfterPunctuation):r;return Ht({normalized:s,chunks:pbe(l,o)},l)}let Qp=null;const XN=new Map;let Yp=null;const gbe=new RegExp("\\p{Emoji_Presentation}","u"),vbe=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u;let sw=null;const eD=new Map;function xA(){if(Qp!==null)return Qp;if(typeof OffscreenCanvas<"u")return Qp=new OffscreenCanvas(1,1).getContext("2d"),Qp;if(typeof document<"u")return Qp=document.createElement("canvas").getContext("2d"),Qp;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function Ad(e,t){let n=t.get(e);return n===void 0&&(n={width:xA().measureText(e).width,containsCJK:Xu(e)},t.set(e,n)),n}function nb(){if(Yp!==null)return Yp;if(typeof navigator>"u")return Yp={lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,breakKeepAllAfterPunctuation:!0,preferPrefixWidthsForBreakableRuns:!1,preferEarlySoftHyphenBreak:!1},Yp;const e=navigator.userAgent,t=navigator.vendor==="Apple Computer, Inc."&&e.includes("Safari/")&&!e.includes("Chrome/")&&!e.includes("Chromium/")&&!e.includes("CriOS/")&&!e.includes("FxiOS/")&&!e.includes("EdgiOS/"),n=e.includes("Chrome/")||e.includes("Chromium/")||e.includes("CriOS/")||e.includes("Edg/");return Yp={lineFitEpsilon:t?1/64:.005,carryCJKAfterClosingQuote:n,breakKeepAllAfterPunctuation:!t,preferPrefixWidthsForBreakableRuns:t,preferEarlySoftHyphenBreak:t},Yp}function fq(){return sw===null&&(sw=new Intl.Segmenter(void 0,{granularity:"grapheme"})),sw}function ybe(e){return gbe.test(e)||e.includes("️")}function oh(e,t,n){return n===0?t.width:t.width-(function(i,o){return o.emojiCount===void 0&&(o.emojiCount=(function(s){let r=0;const l=fq();for(const a of l.segment(s))ybe(a.segment)&&r++;return r})(i)),o.emojiCount})(e,t)*n}function kbe(e){return e==="space"||e==="zero-width-break"||e==="soft-hyphen"}function tD(e){return e==="space"||e==="preserved-space"||e==="tab"||e==="zero-width-break"||e==="soft-hyphen"}function nD(e,t,n=e.widths.length){for(;t0?e.letterSpacing:0}function Tx(e,t){return t===0?0:e+t}function Cbe(e,t,n,i,o){return Tx(i,t==="tab"?o+(function(s,r){return s.letterSpacing!==0&&s.spacingGraphemeCounts[r]>0?s.letterSpacing:0})(e,n):e.lineEndFitAdvances[n])}function iD(e,t,n,i){return Tx(i,t==="tab"?0:e.lineEndFitAdvances[n])}function oD(e,t,n,i,o){return Tx(i,t==="tab"?o:e.lineEndPaintAdvances[n])}function Abe(e,t,n){return e.letterSpacing!==0&&t?n+e.letterSpacing:n}function xbe(e,t){return e.letterSpacing===0?t:t+e.letterSpacing}function Cy(e,t,n){let i=t;for(;iB){if(de!==null&&X>Z){ie(oe,X,re),ke=X,pe=Cy(de,pe,ke+1),X=-1,re=0;continue}ie(),Te(oe,ke,le)}else $+=le,ne=oe,K=ke+1;else Te(oe,ke,le);const se=ke+1;de!==null&&de[pe]===se&&(X=se,re=$,pe++),ke++}V&&ne===oe&&K===fe.length&&(ne=oe+1,K=0)}let G=0;for(;G=W.length)));){const oe=W[G],Z=tD(z[G]);if(V)if($+oe>B){if(Z){Ee(G,oe),ie(G+1,0,$-oe),G++;continue}if(ee>=0){if(ne>ee||ne===ee&&K>0){ie();continue}ie(ee,0,ue);continue}if(oe>B&&F[G]!==null){ie(),Me(G,0),G++;continue}ie()}else Ee(G,oe),Z&&(ee=G+1,ue=$-oe),G++;else oe>B&&F[G]!==null?Me(G,0):ye(G,oe),Z&&(ee=G+1,ue=$-oe),G++}return V&&ie(),j})(n,i);const{widths:o,kinds:s,breakableFitAdvances:r,breakablePreferredBreaks:l,discretionaryHyphenWidth:a,chunks:u}=n;if(o.length===0||u.length===0)return 0;const c=nb(),d=i+c.lineFitEpsilon;let h=0,p=0,m=!1,g=0,y=0,b=-1,v=0,C=null;function w(){b=-1,v=0,C=null}function M(I=g,R=y,W){h++,p=0,m=!1,w()}function N(I,R){m=!0,g=I+1,y=0,p=R}function T(I,R,W){m=!0,g=I,y=R+1,p=W}function S(I,R){m?(p+=R,g=I+1,y=0):N(I,R)}function x(I,R,W,z,F,O){if(!R)return;const B=iD(n,I,W,F);oD(n,I,W,F,z),b=W+1,v=p-O+B,C=I}function A(I,R){var W;const z=r[I],F=(W=l[I])!=null?W:null;let O=F===null?-1:Cy(F,0,R+1),B=-1,j=R;for(;jd){if(F!==null&&B>R){M(I,B),j=B,O=Cy(F,O,j+1),B=-1;continue}M(),T(I,j,$)}else p=K,g=I,y=j+1}else T(I,j,$);const V=j+1;F!==null&&F[O]===V&&(B=V,O++),j++}m&&g===I&&y===z.length&&(g=I+1,y=0)}function E(I){h++,w()}for(let I=0;I=R.endSegmentIndex)));){const z=s[W],F=tD(z),O=wbe(n,m,W),B=z==="tab"?bbe(p+O,n.tabStopAdvance):o[W],j=O+B,$=Cbe(n,z,W,O,B);if(z!=="soft-hyphen")if(m){if(p+$>d){const V=p+iD(n,z,W,O);if(oD(n,z,W,O,B),C==="soft-hyphen"&&c.preferEarlySoftHyphenBreak&&v<=d){M(b,0);continue}if(F&&V<=d){S(W,j),M(W+1,0),W++;continue}if(b>=0&&v<=d){if(g>b||g===b&&y>0){M();continue}const ne=b;M(ne,0),W=ne;continue}if($>d&&r[W]!==null){M(),A(W,0),W++;continue}M();continue}S(W,j),x(z,F,W,B,O,j),W++}else $>d&&r[W]!==null?A(W,0):N(W,B),x(z,F,W,B,O,j),W++;else m&&(g=W+1,y=0,b=W+1,v=p+a,C=z),W++}m&&(R.consumedEndSegmentIndex,M(R.consumedEndSegmentIndex,0))}return h})(e,t)}let rw=null;function Ex(){return rw===null&&(rw=new Intl.Segmenter(void 0,{granularity:"grapheme"})),rw}function _be(e,t){const n=[];let i=[],o=0,s=!1,r=!1,l=!1;function a(){i.length!==0&&(n.push({text:i.length===1?i[0]:i.join(""),start:o}),i=[],s=!1,r=!1,l=!1)}function u(d,h,p){i=[d],o=h,s=p,r=AA(d),l=N4.has(d)}function c(d,h){i.push(d),s=s||h;const p=AA(d);r=d.length===1&&rp.has(d)&&r||p,l=!1}for(const d of Ex().segment(e)){const h=d.segment,p=Xu(h);i.length!==0?l||_x.has(h)||rp.has(h)||t.carryCJKAfterClosingQuote&&p&&r?c(h,p):s||p?(a(),u(h,d.index,p)):c(h,p):u(h,d.index,p)}return a(),n}function Ibe(e,t,n){if(t.length<=1)return t;const i=[];let o=-1,s=!1;function r(l){if(!(o<0)){if(s)o+1===l?i.push(t[o]):(function(a,u){const c=t[a].start,d=u=0&&!cq(t[l-1].text,n)&&r(l),o<0&&(o=l),s=s||Xu(a.text)}return r(t.length),i}function sD(e,t){if(t==="zero-width-break"||t==="soft-hyphen"||t==="hard-break")return 0;if(t==="tab")return 1;let n=0;const i=Ex();for(const o of i.segment(e))n++;return n}function Mbe(e){return e==="-"||e==="֊"||e==="‐"||e==="‒"||e==="–"||e==="—"}function Tbe(e,t,n,i,o){const s=nb(),{cache:r,emojiCorrection:l}=(function(E,I){xA().font=E;const R=(function(F){let O=XN.get(F);return O||(O=new Map,XN.set(F,O)),O})(E),W=(function(F){const O=F.match(/(\d+(?:\.\d+)?)\s*px/);return O?parseFloat(O[1]):16})(E),z=I?(function(F,O){let B=eD.get(F);if(B!==void 0)return B;const j=xA();j.font=F;const $=j.measureText("😀").width;if(B=0,$>O+.5&&typeof document<"u"&&document.body!==null){const V=document.createElement("span");V.style.font=F,V.style.display="inline-block",V.style.visibility="hidden",V.style.position="absolute",V.textContent="😀",document.body.appendChild(V);const ne=V.getBoundingClientRect().width;document.body.removeChild(V),$-ne>.5&&(B=$-ne)}return eD.set(F,B),B})(E,W):0;return{cache:R,fontSize:W,emojiCorrection:z}})(t,(a=e.normalized,vbe.test(a)));var a;const u=oh("-",Ad("-",r),l)+(o===0?0:2*o),c=8*oh(" ",Ad(" ",r),l),d=o!==0;if(e.len===0)return{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],breakablePreferredBreaks:[],letterSpacing:0,spacingGraphemeCounts:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[]};const h=[],p=[],m=[],g=[];let y=e.chunks.length<=1&&!d;const b=null,v=[],C=[],w=[],M=null,N=Array.from({length:e.len});function T(E,I,R,W,z,F,O,B,j){z!=="text"&&z!=="space"&&z!=="zero-width-break"&&(y=!1),h.push(I),p.push(R),m.push(W),g.push(z),v.push(O),C.push(B),d&&w.push(j)}function S(E,I,R,W,z){const F=Ad(E,r),O=d?sD(E,I):0,B=(function(ne,K,ee){return K>1?ne+(K-1)*ee:ne})(oh(E,F,l),O,o),j=I==="space"||I==="preserved-space"||I==="zero-width-break"?0:B,$=j===0?0:j+(O>0?o:0),V=I==="space"||I==="zero-width-break"?0:B;if(z&&W&&E.length>1){let ne="sum-graphemes";o!==0?ne="segment-prefixes":T9(E)?ne="pair-context":s.preferPrefixWidthsForBreakableRuns&&(ne="segment-prefixes");const K=(function(ue,ie,ye,Te,Ee){if(ie.breakableFitAdvances!==void 0&&ie.breakableFitMode===Ee)return ie.breakableFitAdvances;ie.breakableFitMode=Ee;const Me=fq(),G=[];for(const fe of Me.segment(ue))G.push(fe.segment);if(G.length<=1)return ie.breakableFitAdvances=null,ie.breakableFitAdvances;if(Ee==="sum-graphemes"){const fe=[];for(const de of G){const pe=Ad(de,ye);fe.push(oh(de,pe,Te))}return ie.breakableFitAdvances=fe,ie.breakableFitAdvances}if(Ee==="pair-context"||G.length>96){const fe=[];let de=null,pe=0;for(const X of G){const re=oh(X,Ad(X,ye),Te);if(de===null)fe.push(re);else{const ke=de+X,le=Ad(ke,ye);fe.push(oh(ke,le,Te)-pe)}de=X,pe=re}return ie.breakableFitAdvances=fe,ie.breakableFitAdvances}const oe=[];let Z="",Q=0;for(const fe of G){Z+=fe;const de=oh(Z,Ad(Z,ye),Te);oe.push(de-Q),Q=de}return ie.breakableFitAdvances=oe,ie.breakableFitAdvances})(E,F,r,l,ne),ee=K===null||i==="keep-all"?null:(function(ue){if(!/[-\u058A\u2010\u2012\u2013\u2014]/u.test(ue))return null;const ie=[];let ye=0;for(const Te of Ex().segment(ue))ye++,Mbe(Te.segment)&&ie.push(ye);return ie.length===0?null:ie})(E);return void T(E,B,$,V,I,R,K,ee,O)}T(E,B,$,V,I,R,null,null,O)}for(let E=0;E=55296&&ue<=56319&&ee+1=56320&&Ee<=57343&&(ie=Ee-56320+(ue-55296<<10)+65536,ye=2)}const Te=$ke(ie);Te!=="R"&&Te!=="AL"&&Te!=="AN"||(B=!0);for(let Ee=0;Ee=0&&O[ue]==="ET";ue--)O[ue]="EN";for(ue=ee+1;ue0?O[ee-1]:ne)!=="L"?"R":"L";if(ie===((ue{const e=globalThis;if(e[lw])return e[lw];const t={configs:{},controllers:{},revision:_u(0),preparedCache:new Map,blockEstimateCache:new Map};return e[lw]=t,t})();let Tg=null;const aw=ir.revision;function rD(e){var t;return e&&(t=ir.configs[e])!=null?t:null}function lD(e,t){const n=Number.parseFloat(String(e??""));return Number.isFinite(n)&&n>0?n:t}function Lbe(e){return e?.type==="text"||e?.type==="emoji"||e?.type==="hardbreak"}function uw(e){var t,n,i;if(!Array.isArray(e)||e.length===0)return null;let o="";for(const s of e){if(!Lbe(s))return null;s.type==="text"?o+=String((t=s.content)!=null?t:""):s.type==="emoji"?o+=String((i=(n=s.name)!=null?n:s.raw)!=null?i:""):s.type==="hardbreak"&&(o+=` -`)}return o.length>0?o:null}function cw(e,t,n){var i,o;if(!e||!Number.isFinite(t)||t<=0||!(function(){var s;if(Tg!=null)return Tg;if(typeof document>"u")return!1;try{const r=document.createElement("canvas");return Tg=!!((s=r.getContext)!=null&&s.call(r,"2d")),Tg}catch{return Tg=!1,!1}})())return null;try{const s=Math.round(100*t)/100,r=[(i=n.whiteSpace)!=null?i:"pre-wrap",n.font,n.lineHeight,n.wrapperOverhead,n.widthAdjustment,s,e].join("\0"),l=ir.blockEstimateCache.get(r);if(l)return ir.blockEstimateCache.delete(r),ir.blockEstimateCache.set(r,l),{kind:"simple-text",height:l.height,contentHeight:l.contentHeight};const a=(o=n.whiteSpace)!=null?o:"pre-wrap",u=(function(p,m,g){const y=`${g}\0${m}\0${p}`,b=ir.preparedCache.get(y);if(b)return ir.preparedCache.delete(y),ir.preparedCache.set(y,b),b.prepared;const v=(function(C,w,M){return(function(N,T,S,x){var A,E;const I=(A=x?.wordBreak)!=null?A:"normal",R=(E=x?.letterSpacing)!=null?E:0;return Tbe(mbe(N,nb(),x?.whiteSpace,I),T,!1,I,R)})(C,w,0,M)})(p,m,{whiteSpace:g});for(ir.preparedCache.set(y,{prepared:v});ir.preparedCache.size>240;){const C=ir.preparedCache.keys().next().value;if(!C)break;ir.preparedCache.delete(C)}return v})(e,n.font,a),c=(function(p,m,g){const y=Sbe(p,m);return{lineCount:y,height:y*g}})(u,Math.max(24,s-n.widthAdjustment),n.lineHeight),d=Math.max(n.lineHeight,c.height),h=Math.max(n.lineHeight,Math.round(d+n.wrapperOverhead));for(ir.blockEstimateCache.set(r,{height:h,contentHeight:Math.round(d)});ir.blockEstimateCache.size>4e3;){const p=ir.blockEstimateCache.keys().next().value;if(!p)break;ir.blockEstimateCache.delete(p)}return{kind:"simple-text",height:h,contentHeight:Math.round(d)}}catch{return null}}function hq(e,t,n){var i,o;if(!n||!e||!Number.isFinite(t)||t<=0)return null;if(e.type==="paragraph"){const s=uw(e.children);return s&&n.paragraph?cw(s,t,n.paragraph):null}if(e.type==="heading"){const s=Number(e.level||0),r=uw(e.children),l=n.headings[s];return r&&l?cw(r,t,l):null}if(e.type==="list_item"){const s=Array.isArray(e.children)?e.children:[];if(s.length!==1||((i=s[0])==null?void 0:i.type)!=="paragraph"||!n.listItem)return null;const r=uw((o=s[0])==null?void 0:o.children);return r?cw(r,t,n.listItem):null}if(e.type==="list"){const s=Array.isArray(e.items)?e.items:[];if(!s.length)return null;let r=Math.max(0,n.listWrapperOverhead);for(const l of s){const a=hq(l,t,n);if(!a)return null;r+=a.height}return{kind:"simple-text",height:Math.max(1,Math.round(r)),contentHeight:Math.max(1,Math.round(r))}}return null}function Eg(e){if(!e)return 1;const t=String(e).split(/\r?\n/);return Math.max(1,t.length)}function sh(e,t){const n=String(e??"");return t?n:n.replace(/\r\n$|\n$|\r$/,"")}function dw(e,t,n=0){return e.diff?xx(t??{},n)?(function(i){const o=sh(i.raw);if(o){const s=o.split(/\r?\n/);return i.originalCode!=null||i.updatedCode!=null?Math.max(1,s.filter(r=>!Ebe.some(l=>r.startsWith(l))).length):Math.max(1,s.length)}return Eg(sh(i.originalCode))+Eg(sh(i.updatedCode))})(e):(function(i){const o=i.originalCode,s=i.updatedCode;if(o!=null||s!=null)return Math.max(Eg(sh(o)),Eg(sh(s)));const r=sh(i.code).split(/\r?\n/);let l=0,a=0;for(const u of r)u.startsWith("+")&&!u.startsWith("+++")?a++:u.startsWith("-")&&!u.startsWith("---")?l++:(l++,a++);return Math.max(1,l,a)})(e):Eg(sh(e.code,e.loading===!0))}function Nbe(e){return e?`${e.fontStyle||"normal"} ${e.fontWeight||"400"} ${e.fontSize||"16px"} ${e.fontFamily||"sans-serif"}`:""}function fw(e,t,n="pre-wrap"){if(!e||!t||typeof window>"u")return null;const i=window.getComputedStyle(t),o=e.offsetHeight,s=lD(i.lineHeight,1.5*lD(i.fontSize,16)),r=e.getBoundingClientRect().width,l=t.getBoundingClientRect().width;return{font:Nbe(i),lineHeight:s,wrapperOverhead:Math.max(0,o-s),widthAdjustment:Math.max(0,r-l),whiteSpace:n}}const Dbe=new Set(["node","key","ref","ctx","renderNode","indexKey","__proto__","prototype","constructor"]);function aD(e,t={}){var n;const i={},o=new Set((n=t.omit)!=null?n:[]);if(!e||typeof e!="object")return i;const s=Object.getOwnPropertyDescriptors(e);for(const[r,l]of Object.entries(s))Dbe.has(r)||o.has(r)||l.enumerable&&"value"in l&&(i[r]=l.value);return i}function uD(e,t,n,i){var o;const s=(function(h){return Math.max(0,Math.ceil(h.scrollHeight||0)-Math.ceil(h.clientHeight||0))})(e),r=(function(h,p){return Number.isFinite(h)?Math.min(Math.max(0,h),p):0})(n,s);if(!i.isReverseFlexScrollRoot(e))return void(e.scrollTop=r);const l=Math.max(0,s-r),a=[-l,l];let u=a[0],c=Number.POSITIVE_INFINITY;for(const h of a){e.scrollTop=h;const p=i.getNormalizedScrollTop(e,t,!1),m=Math.abs(p-r);md&&(e.scrollTop=u)}function cD(e,t){let n=0,i=null,o=null;const s=()=>{const r=o;o=null,i=null,r&&(n=Date.now(),e(...r))};return function(...r){const l=Date.now(),a=t-(l-n);o=r,a<=0?(i&&(clearTimeout(i),i=null),n=l,o=null,e(...r)):i||(i=setTimeout(s,a))}}function dD(e){return e==="simple"?"simple":e===!0||e==="true"||e==="precise"?"precise":"off"}const pq=Symbol("MarkstreamMathBlockMinHeightCache");function m8t(){return rn(pq,null)}const Fbe=new Set(["text","inline_code","emoji","footnote_reference"]),Rbe=new Set(["strong","emphasis","strikethrough","highlight","insert","subscript","superscript","link"]);function Lg(e){const t=Number(e);return!Number.isFinite(t)||t<=0?-1:Math.round(t/32)}function rh(e,t,n,i=22){const o=String(e??"");if(!o)return n;const s=Math.max(18,Math.floor(Math.max(320,t)/8)),r=o.split(/\r?\n/).length,l=Math.ceil(o.length/s),a=Math.max(1,r,l);return Math.max(n,Math.ceil(a*i+12))}function mq(e){var t;if(!e||typeof e!="object")return!1;const n=e,i=String((t=n.type)!=null?t:"");if(Fbe.has(i))return!0;if(!Rbe.has(i))return!1;const o=n.children;return!Array.isArray(o)||!o.length||o.every(mq)}function SA(e){var t,n,i,o,s,r,l,a;if(!e||typeof e!="object")return"";const u=e,c=String((t=u.type)!=null?t:"");if(c==="text")return String((i=(n=u.content)!=null?n:u.raw)!=null?i:"");if(c==="inline_code")return String((r=(s=(o=u.code)!=null?o:u.content)!=null?s:u.raw)!=null?r:"");if(c==="emoji")return String((a=(l=u.name)!=null?l:u.raw)!=null?a:"");if(typeof u.text=="string")return u.text;const d=[];for(const h of["children","items","cells","rows"]){const p=u[h];if(Array.isArray(p)){const m=p.map(SA).filter(Boolean).join(" ");m&&d.push(m)}}return d.join(" ").replace(/\s+/g," ").trim()}function gq(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="inline_code"||["children","items","cells","rows"].some(n=>{const i=t[n];return Array.isArray(i)&&i.some(gq)})}function Obe(e,t){if(!e)return 30;const n=Math.max(18,Math.floor(Math.max(320,t)/8)),i=e.split(/\r?\n/).length,o=Math.ceil(e.length/n),s=Math.max(1,i,o);return 30+26*Math.max(0,s-1)}function Pbe(e,t){var n,i,o,s,r,l,a,u,c,d,h,p,m,g;if(!e||typeof e!="object")return 32;const y=e,b=String((n=y.type)!=null?n:""),v=Number.isFinite(t)&&t>0?t:640;switch(b){case"heading":return(function(C){var w;const M=Number((w=C.level)!=null?w:C.depth);return M>=4?20:M===3?30:M===2?32:44})(y);case"paragraph":return(function(C,w){const M=String(C??"");if(!M)return 28;const N=Math.max(18,Math.floor(Math.max(320,w)/8)),T=M.split(/\r?\n/).length,S=Math.ceil(M.length/N);return Math.max(1,T,S)<=1?28:rh(M,w,34)})(String((o=(i=y.raw)!=null?i:y.content)!=null?o:""),v);case"list":return(function(C,w){var M;const N=Array.isArray(C.items)?C.items:[];if(!N.length)return 48;const T=Math.max(48,30*N.length+12);let S=12;for(const E of N)S+=Obe(SA(E)||String((M=E.raw)!=null?M:""),w);const x=Math.max(0,S-T);if(N.length>20){const E=Math.round(2.4*N.length);return Math.round(T+Math.max(E,Math.min(x,3*N.length)))}if(x<=0)return T;const A=N.length>8?8*N.length:x;return Math.round(T+Math.min(x,A))})(y,v);case"list_item":return rh(String((r=(s=y.raw)!=null?s:y.content)!=null?r:""),v,34);case"blockquote":return rh(String((a=(l=y.raw)!=null?l:y.content)!=null?a:""),v,56);case"table":return(function(C,w){const M=[...C.header?[C.header]:[],...Array.isArray(C.rows)?C.rows:[]];if(!M.length){const N=Array.isArray(C.children)?C.children.length:3;return Math.max(120,38*N+48)}return Math.max(120,Math.round(4+M.reduce((N,T)=>N+(function(S,x){const A=Math.max(1,S.length),E=Math.max(80,(x-32)/A),I=Math.max(10,Math.floor(E/8)),R=Math.max(1,...S.map(W=>{var z;const F=SA(W)||String((z=W?.raw)!=null?z:"");return Math.ceil(F.length/I)||1}));return 54+34*Math.max(0,R-1)+(A<=3&&S.some(gq)?14:0)})((function(S){var x;return Array.isArray(S?.cells)&&(x=S.cells)!=null?x:[]})(T),w),0)))})(y,v);case"code_block":{const C=String((u=y.language)!=null?u:"").trim().toLowerCase(),w=String((d=(c=y.code)!=null?c:y.raw)!=null?d:"");return C==="mermaid"?Zk(Vk(w)):C==="infographic"?Gk(Kk(w)):rh(w,v,96,20)}case"math_block":return 72;case"image":return 220;case"admonition":case"vmr_container":case"html_block":return(function(C,w){var M,N,T;const S=C.match(/^\s*]*)>/i);return S&&!/(?:^|\s)open(?:\s|=|$)/i.test((M=S[1])!=null?M:"")?rh(((T=(N=C.match(/]*>([\s\S]*?)<\/summary>/i))==null?void 0:N[1])==null?void 0:T.replace(/<[^>]*>/g,"").trim())||"Details",w,28,28):rh(C,w,96)})(String((p=(h=y.raw)!=null?h:y.content)!=null?p:""),v);case"thematic_break":return 24;default:return rh(String((g=(m=y.raw)!=null?m:y.content)!=null?g:""),v,40)}}function fD(e,t,n){return Math.min(Math.max(e,t),n)}const $be=["total","cacheHits","appendHits","tailHits","fullParses","chunkedParses"],Bbe=["tokenCloneMs","processTokensInputTokens","processTokensReusedTopLevelNodes","processTokensMs","safeMarkdownMs","tokenizeMs","htmlBlockPassesMs","parseMarkdownToStructureTotalMs"],zbe=new Set(["attrs","data","items","header","payload","props","rows","cells","term","definition","sourceMap"]),vq=["raw","content","code","originalCode","updatedCode"],hD=new WeakMap,pD=new WeakMap;let jbe=1;function su(){return typeof performance<"u"?performance.now():Date.now()}function mD(e){const t=e.stream;return t&&typeof t.stats=="function"?t.stats():null}function ua(e){if(typeof e!="object"&&typeof e!="function"||e===null)return"";const t=e;let n=hD.get(t);return n||(n=jbe++,hD.set(t,n)),String(n)}function gD(e,t,n,i={}){var o,s;const r=i.includeFinal!==!1,l={md:ua(t),customMarkdownIt:ua(n),requireClosingStrong:e.requireClosingStrong===!0,customHtmlTags:(o=e.customHtmlTags)!=null?o:[],includeSourceMap:e.includeSourceMap===!0,streamParse:(s=e.streamParse)!=null?s:"auto",validateLink:ua(e.validateLink),preTransformTokens:ua(e.preTransformTokens),postTransformTokens:ua(e.postTransformTokens),postTransformNodes:ua(e.postTransformNodes)};return r&&(l.final=e.final===!0),JSON.stringify(l)}function vD(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===10;)t-=1;const n=e.lastIndexOf(` -`,t-1)+1;return e.slice(n,t).trim()}function yD(e){const t=yq(e);return t.length>=2&&t.every(n=>{const i=n.trim();return i.length>=1&&i.replace(/^:/,"").replace(/:$/,"").split("").every(o=>o==="-")})}function yq(e){return e.includes("|")?e.replace(/^\|/,"").replace(/\|$/,"").split("|"):[]}function kq(e){let t=2166136261;for(let n=0;n>>0).toString(36)}function Lx(e){const t=String(e??"");return`${t.length}:${kq(t)}`}function _A(e,t=new WeakMap,n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return String(e);if(typeof e=="string")return`s:${(function(r){return r.length<=8192?Lx(r):`${r.length}:${kq(r.slice(0,8192))}:truncated`})(e)}`;if(typeof e=="function")return`fn:${ua(e)}`;if(typeof e!="object")return typeof e;const i=e,o=t.get(i);if(o)return`cycle:${o}`;if(n>=6)return`object:${ua(i)}`;const s=ua(i);if(t.set(i,s),Array.isArray(e)){const r=e.slice(0,200);return`a:${e.length}:${r.map(l=>_A(l,t,n+1)).join(",")}`}if(typeof e=="object"){const r=e,l=Object.keys(r).sort(),a=l.slice(0,80);return`o:${l.length}:${a.sort().map(u=>`${u}:${_A(r[u],t,n+1)}`).join(";")}`}return typeof e}function ib(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.raw=="string"}function bq(e,t=new WeakMap,n=0){return Array.isArray(e)?`a:${e.length}:${e.slice(0,200).map(i=>ib(i)?kf(i,t,n+1):bq(i,t,n+1)).join(",")}`:ib(e)?kf(e,t,n):_A(e,t,n)}function Hbe(e,t,n){return Object.keys(e).sort().filter(i=>i!=="children"&&!vq.includes(i)).map(i=>{const o=e[i];return typeof o=="string"?`${i}=s:${Lx(o)}`:typeof o=="number"||typeof o=="boolean"||o==null?`${i}=${String(o)}`:typeof o=="function"?`${i}=fn:${ua(o)}`:zbe.has(i)&&(Array.isArray(o)||typeof o=="object")?`${i}=${bq(o,t,n+1)}`:o&&typeof o=="object"?`${i}=object:${ua(o)}`:""}).filter(Boolean).join(";")}function Wbe(e){return vq.map(t=>{const n=e[t];return typeof n=="string"?`${t}=s:${Lx(n)}`:""}).filter(Boolean).join(";")}function kf(e,t=new WeakMap,n=0){const i=pD.get(e);if(i)return i;const o=e,s=t.get(o);if(s)return`node-cycle:${s}`;if(n>=6)return`node:${e.type}:${ua(o)}`;const r=ua(o);t.set(o,r);const l=(function(a,u,c){const d=a,h=Array.isArray(d.children)?d.children:[],p=h.length?h.slice(0,200).map(m=>kf(m,u,c+1)).join("|"):"";return[a.type,Wbe(d),Hbe(d,u,c),h.length,p].join(":")})(e,t,n);return pD.set(o,l),l}function wq(e,t){return kf(e)===kf(t)}function Nx(e,t,n){const i=su(),o=t==="stabilizeSignatureMs"?"stabilizeSignatureCallCount":"primeSignatureCallCount";try{return n()}finally{e[t]+=su()-i,e[o]+=1,e.signatureMs=e.stabilizeSignatureMs+e.primeSignatureMs,e.signatureCallCount=e.stabilizeSignatureCallCount+e.primeSignatureCallCount}}function kD(e,t,n){return Nx(t,n,()=>kf(e))}function Cq(e,t,n){return kD(e,n,"stabilizeSignatureMs")===kD(t,n,"stabilizeSignatureMs")}function Ay(e){return{reusedNodeCount:0,dirtyStartIndex:e>0?0:-1,stablePrefixNodeCount:0,dirtyTailNodeCount:e}}function bD(e,t,n){return e<0?0:Math.max(t.length,n.length)-e}function wD(e){return e.__markstreamHasCustomParserExtensions===!0||(function(t){var n;return Number((n=t.__markstreamRegisteredPluginCount)!=null?n:0)>0})(e)}function qbe(e,t){return e.length===t.length&&e===t}function Dx(e,t,n=0){if(n>=4)return null;if(e.type!==t.type)return!1;const i=e,o=t,s=Object.keys(i).filter(c=>c!=="type"&&c!=="children").sort(),r=Object.keys(o).filter(c=>c!=="type"&&c!=="children").sort();if(s.length!==r.length)return!1;for(let c=0;c{i=Dx(e,t)}),i??Cq(e,t,n)}function Kbe(e,t){const n={};for(const i of $be){const o=e[i],s=t?.[i];typeof o=="number"&&(n[i]=o-(typeof s=="number"?s:0))}return n}function Zbe(e,t){var n;const i=vN(t.instanceMsgId),o=new Map,s=(n=t.smoothStreamingEnabled)!=null?n:D(()=>!1),r=q(t.renderContent.value);let l=[],a="",u="",c="",d=!1;const h=(function(){let W="",z=0,F=!1,O=!1,B=!1,j=!1;function $(){W="",z=0,F=!1,O=!1,B=!1,j=!1}function V(ne){let K=!1;for(let ee=0;ee{if(!ne||!K.startsWith(ne)||K.length<=ne.length)return $(),[!0,0];let ee=0;W!==ne&&($(),V(ne),ee=ne.length);const ue=K.slice(ne.length),ie=V(ue);return W=K,[ie,ee+ue.length]}})();let p,m=0,g=0,y=su(),b=-1,v=0;function C(W){b=Number.isInteger(W)?W:0,v+=1}function w(){p&&(clearTimeout(p),p=void 0)}function M(){w();const W=t.renderContent.value;r.value!==W&&(r.value=W),y=su()}qe([t.renderContent,t.effectiveFinal,s],([W,z,F])=>{r.value!==W&&(!F||z||(function(O,B){if(!O&&B||B.length<=80||B.length\s*|`{3,}|~{3,})/.test(j))||j.endsWith(` -`)&&!(function($){const V=vD($);if(yD(V))return!1;const ne=yq(V);return ne.length>=2&&ne.some(K=>K.trim())})(B))})(r.value,W)?M():(function(){if(g+=1,p)return;const O=Math.max(0,(function(B){const j=B.parseCoalesceMs;return typeof j=="number"&&Number.isFinite(j)&&j>=0?j:80})(e)-(su()-y));O<=0?M():p=setTimeout(M,O)})())},{flush:"sync",immediate:!0}),ad(w);const N=D(()=>{var W,z,F,O;return V1e(e.customHtmlTags,(W=e.parseOptions)==null?void 0:W.customHtmlTags,(O=(F=(z=t.customComponentsMap)==null?void 0:z.value)!=null?F:{},Object.entries(O).map(([B,j])=>{const $=Ga(B);return j==null||!$||a2($)||MH.has($)||i2.has($)?"":$}).filter(Boolean)))}),T=D(()=>{const{key:W,tags:z}=K1e(N.value);if(!W)return i;const F=o.get(W);if(F)return F;const O=vN(t.instanceMsgId,{customHtmlTags:z});return o.set(W,O),O}),S=D(()=>{const W=T.value;if(!e.customMarkdownIt)return W;const z=e.customMarkdownIt(W);return W.__markstreamHasCustomParserExtensions=!0,z.__markstreamHasCustomParserExtensions=!0,z}),x=D(()=>{var W,z;const F=(W=e.parseOptions)!=null?W:{},O=t.effectiveFinal.value,B=N.value,j=O!=null,$=B.length>0;return j||$||F.streamParse==null?Ht(Ht(Hn(Ht({},F),{streamParse:(z=F.streamParse)==null||z}),j?{final:O}:{}),$?{customHtmlTags:B}:{}):F}),A=D(()=>{var W;return new Set(((W=x.value.customHtmlTags)!=null?W:[]).map(z=>String(z).trim().toLowerCase()).filter(Boolean))}),E=D(()=>gD(x.value,S.value,e.customMarkdownIt,{includeFinal:!0})),I=D(()=>gD(x.value,S.value,e.customMarkdownIt,{includeFinal:!1}));qe([E,I],([W,z],[F,O])=>{F&&(W===F&&z===O||(M(),z!==O&&(l=[],c="")))},{flush:"sync"});const R=D(()=>{var W,z,F,O,B,j,$,V,ne,K,ee;if((W=e.nodes)!=null&&W.length)return l=[],c="",C(0),Ot(e.nodes.slice());const ue=r.value;if(!ue)return l=[],c="",C(-1),[];const ie=t.debugPerformanceEnabled.value,ye=ie?su():0,Te=S.value,Ee=E.value,Me=I.value;a&&Ee!==a&&(function(xe){var Oe,Ze;(Ze=(Oe=xe.stream)==null?void 0:Oe.reset)==null||Ze.call(Oe)})(Te),u&&Me!==u&&(l=[],c="");const G=Object.keys((F=(z=t.customComponentsMap)==null?void 0:z.value)!=null?F:{}).length>0||typeof x.value.postTransformNodes=="function";G!==d&&(l=[],c="");const oe=!G&&l.length>0&&ue.startsWith(c)&&Me===u,Z=ie?mD(Te):null,Q=ie?{}:void 0,fe=wD(Te),de=!fe&&!G,pe=Ht(Ht(Hn(Ht({},x.value),{__reuseStableTopLevelNodes:de}),fe?{__disableStreamParse:!0}:{}),Q?{__timing:Q}:{}),X=NW(ue,Te,pe),re=ie?su():0,ke=ie?{signatureMs:0,stabilizeSignatureMs:0,primeSignatureMs:0,signatureCallCount:0,stabilizeSignatureCallCount:0,primeSignatureCallCount:0}:void 0;let le,se=ie?Ay(X.length):void 0,_e=0,ge=0,Le=0;if(oe){const xe=ie?su():0,[Oe,Ze]=(function(yt){var Wt,Gt;const[Be,$e]=yt.scanGlobalReferenceAppend(yt.previousContent,yt.content),Ke=yt.parseOptions;return[yt.previousDirtyStartIndex>0&&Ke.final!==!0&&!yt.customMarkdownIt&&!wD(yt.md)&&!Be&&typeof Ke.preTransformTokens!="function"&&typeof Ke.postTransformTokens!="function"&&typeof Ke.postTransformNodes!="function"&&((Gt=(Wt=Ke.customHtmlTags)==null?void 0:Wt.length)!=null?Gt:0)===0?yt.previousDirtyStartIndex:0,$e]})({content:ue,previousContent:c,previousDirtyStartIndex:b,parseOptions:x.value,customMarkdownIt:e.customMarkdownIt,md:Te,scanGlobalReferenceAppend:h});Le=Ze;const ct=Oe<=0;if(ke){const yt=(function(Wt,Gt,Be,$e={}){var Ke;if(!Gt.length)return{nodes:Wt,metrics:Ay(Wt.length)};const ft=(Ke=$e.scanStartIndex)!=null?Ke:0,Ct=$e.reuseDirtyTail!==!1,Mt=(function(it,ot,zt,cn=0){const gt=Math.min(it.length,ot.length);for(let st=Math.min(gt,Math.max(0,cn));stkf(xe[ct]))})(le,ke,ge):(function(xe,Oe=0){for(let Ze=Math.max(0,Oe);Ze((B=Z?.total)!=null?B:0);t.logPerf(Oe?"parse(stream)":"parse(sync)",Ht(Ht(Ht({rendererId:t.instanceMsgId,ms:Math.round(su()-ye),nodes:le.length,contentLength:ue.length,parseCommitCount:m,parseCoalescedCount:g,nodeReuseMs:be,referenceDefinitionScanChars:Le,signatureMs:(j=ke?.signatureMs)!=null?j:0,stabilizeSignatureMs:($=ke?.stabilizeSignatureMs)!=null?$:0,primeSignatureMs:(V=ke?.primeSignatureMs)!=null?V:0,signatureCallCount:(ne=ke?.signatureCallCount)!=null?ne:0,stabilizeSignatureCallCount:(K=ke?.stabilizeSignatureCallCount)!=null?K:0,primeSignatureCallCount:(ee=ke?.primeSignatureCallCount)!=null?ee:0,stabilizeMs:_e},se??{}),Q?Object.fromEntries(Bbe.map(Ze=>{var ct;return[Ze,(ct=Q[Ze])!=null?ct:0]})):{}),xe?{streamMode:xe.lastMode,streamDelta:Kbe(xe,Z),streamStats:xe}:{}))}return Ot(le)});return{effectiveCustomHtmlTags:N,effectiveCustomHtmlTagsSet:A,mdBase:T,mdInstance:S,mergedParseOptions:x,getParsedNodesDirtyStartIndex:()=>b,getParsedNodesRevision:()=>v,parsedNodes:R}}function Gbe(e){const{isClient:t}=e,n=q(new Set),i=new Map,o=new Map,s=new Map;function r(u){if(!t)return;const c=s.get(u);c!=null&&(window.clearTimeout(c),s.delete(u))}function l(){if(t)for(const u of s.values())window.clearTimeout(u);s.clear()}function a(){n.value=new Set}return{visibleNodeIndices:n,nodeVisibilityHandles:i,nodeVisibilityWatchStops:o,nodeVisibilityFallbackTimers:s,clearVisibilityFallback:r,clearAllVisibilityFallbacks:l,markNodeVisible:function(u,c=!0){var d;c&&r(u),(function(h,p){if((g=(m=e.shouldTrackVisibleNodeIndices)==null?void 0:m.call(e))!=null&&!g)return;var m,g;const y=n.value,b=y.has(h);if(p){if(b)return;const C=new Set(y);return C.add(h),void(n.value=C)}if(!b)return;const v=new Set(y);v.delete(h),n.value=v})(u,c),c&&((d=e.onNodeMarkedVisible)==null||d.call(e,u))},resetNodeVisibleState:a,cleanupNodeVisibility:function(u){var c;if(e.shouldCleanupNodeVisibility&&!e.shouldCleanupNodeVisibility())return;for(const[h,p]of o.entries())h{const c=o.getSnapshot();t.value=c.source,n.value=c.visible,i.value=c.done},r=o.subscribe(s);s();const l=D(()=>Math.max(0,t.value.length-n.value.length)),a=D(()=>l.value===0),u=D(()=>i.value&&a.value);return Tm()&&ad(()=>{r(),o.destroy()}),{source:t,visible:n,done:i,final:u,caughtUp:a,pendingChars:l,enqueue:c=>o.enqueue(c),finish:c=>o.finish(c),flush:()=>o.flush(),reset:c=>o.reset(c),pause:()=>o.pause(),resume:()=>o.resume()}}const Ybe={maxCharsPerSecond:3e3,maxCommitFps:20,maxCharsPerCommit:160,catchUpLatencyMs:220,catchUpThreshold:400},CD=/auto|scroll|overlay/i;function Jbe(e){if(!e)return!1;const t=(e.overflowY||"").toLowerCase(),n=(e.overflow||"").toLowerCase();return CD.test(t)||CD.test(n)}function Xbe(e){const t=Math.ceil(e.scrollHeight)>Math.ceil(e.clientHeight)+1,n=Math.ceil(e.scrollWidth)>Math.ceil(e.clientWidth)+1;return t||n}const e4e={class:"m-0 p-0"},t4e=["data-probe"],n4e=Hi(dt(Hn(Ht({},{name:"HeightEstimationProbes"}),{__name:"HeightEstimationProbes",props:{width:{},flowRoot:{type:Boolean},paragraphNode:{},listItemNode:{},listNode:{},headingNodes:{},setParagraphWrapper:{type:Function},setListItemWrapper:{type:Function},setListWrapper:{type:Function},setHeadingWrapper:{type:Function}},setup(e){const t=e;function n(i){var o,s;return(s=(o=t.headingNodes)==null?void 0:o[i])!=null?s:null}return(i,o)=>(k(),L("div",{class:"height-estimation-probes",style:an({width:`${e.width}px`}),"aria-hidden":"true"},[_("div",{ref:s=>e.setParagraphWrapper(s),class:Pe(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":"paragraph"},[U(f(Vh),{node:e.paragraphNode,"index-key":"probe-paragraph"},null,8,["node"])],2),_("div",{ref:s=>e.setListItemWrapper(s),class:Pe(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":"list-item"},[_("ul",e4e,[U(f(Z1),{node:e.listItemNode,"index-key":"probe-list-item"},null,8,["node"])])],2),_("div",{ref:s=>e.setListWrapper(s),class:Pe(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":"list"},[U(f(G1),{node:e.listNode,"index-key":"probe-list"},null,8,["node"])],2),(k(),L(Fe,null,xt(6,s=>_("div",{key:`probe-heading-${s}`,ref_for:!0,ref:r=>e.setHeadingWrapper(s,r),class:Pe(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":`heading-${s}`},[U(f(L4),{node:n(s),"index-key":`probe-heading-${s}`},null,8,["node","index-key"])],10,t4e)),64))],4))}})),[["__scopeId","data-v-3e0766e2"]]),AD=dt({name:"InfographicBlockNodeLoading",props:{node:{type:Object,required:!0},showHeader:{type:Boolean,default:!0},estimatedPreviewHeightPx:{type:Number,default:void 0}},setup(e){const t=D(()=>{var n,i;return Gk((i=A1(e.estimatedPreviewHeightPx))!=null?i:Kk(String((n=e.node.code)!=null?n:"")))});return()=>{var n;return jn("div",{class:"infographic-block-container rounded-lg border overflow-hidden",style:{margin:"var(--ms-flow-diagram-y) 0",background:"var(--diagram-bg)",borderColor:"var(--diagram-border)",color:"hsl(var(--ms-foreground))"},"data-markstream-infographic":"1","data-markstream-mode":"pending"},[e.showHeader?jn("div",{class:"infographic-block-header flex justify-between items-center border-b",style:{padding:"var(--ms-inset-panel-y) var(--ms-inset-panel-x)",background:"var(--diagram-header-bg)",borderColor:"var(--diagram-border)",minHeight:"calc(var(--ms-action-btn-icon) + var(--ms-action-btn-padding) + var(--ms-action-btn-padding) + var(--ms-inset-panel-y) + var(--ms-inset-panel-y) + 1px)"}},[jn("div",{class:"flex items-center gap-x-2 overflow-hidden"},[jn("span",{class:"icon-slot action-icon shrink-0",style:{display:"inline-flex",width:"var(--ms-action-btn-icon)",height:"var(--ms-action-btn-icon)"}}),jn("span",{class:"infographic-label font-medium font-mono truncate",style:{fontSize:"var(--ms-text-label)",color:"hsl(var(--ms-muted-foreground))"}},"Infographic")]),jn("div",{class:"infographic-header-actions flex items-center opacity-0 pointer-events-none",style:{gap:"var(--ms-gap-header-actions)"},"aria-hidden":"true"},Array.from({length:4},()=>jn("span",{class:"infographic-action-btn inline-flex items-center justify-center p-[var(--ms-action-btn-padding)] rounded",style:{width:"calc(var(--ms-action-btn-icon) + var(--ms-action-btn-padding) + var(--ms-action-btn-padding))",height:"calc(var(--ms-action-btn-icon) + var(--ms-action-btn-padding) + var(--ms-action-btn-padding))"}})))]):null,jn("div",{class:"infographic-preview relative overflow-hidden block",style:{height:`${t.value}px`,minHeight:"var(--ms-size-diagram-min-height)",background:"var(--diagram-bg)"}},[jn("pre",{class:"infographic-pending-source text-sm font-mono whitespace-pre-wrap",style:{position:"absolute",inset:"0",zIndex:"1",margin:"0",padding:"var(--ms-inset-panel-body)",overflow:"auto",textAlign:"left"}},String((n=e.node.code)!=null?n:"")),jn("div",{class:"absolute inset-0"},[jn("div",{class:"w-full text-center flex items-center justify-center min-h-full"})])])])}}}),xD=dt({name:"MermaidBlockNodeLoading",props:{node:{type:Object,required:!0},showHeader:{type:Boolean,default:!0},estimatedPreviewHeightPx:{type:Number,default:void 0}},setup(e){const t=D(()=>{var n,i;return Zk((i=A1(e.estimatedPreviewHeightPx))!=null?i:Vk(String((n=e.node.code)!=null?n:"")))});return()=>{var n;return jn("div",{class:"mermaid-block-container rounded-lg border overflow-hidden",style:{margin:"var(--ms-flow-diagram-y) 0",borderColor:"var(--diagram-border)"},"data-markstream-mermaid":"1","data-markstream-mode":"pending"},[e.showHeader?jn("div",{class:"mermaid-block-header flex justify-between items-center border-b px-[var(--ms-inset-panel-x)] py-[var(--ms-inset-panel-y)]",style:{background:"var(--diagram-header-bg)",borderColor:"var(--diagram-border)"}},[jn("div",{class:"flex items-center gap-x-2 overflow-hidden"},[jn("span",{class:"mermaid-label-text text-[length:var(--ms-text-label)] font-medium font-mono truncate",style:{color:"var(--code-action-fg)"}},"Mermaid")]),jn("div",{class:"mermaid-header-actions flex items-center gap-[var(--ms-gap-header-actions)] opacity-0 pointer-events-none","aria-hidden":"true"},Array.from({length:4},()=>jn("span",{class:"mermaid-action-btn inline-flex items-center justify-center p-[var(--ms-action-btn-padding)] rounded"},[jn("span",{class:"action-icon block"})])))]):null,jn("div",{class:"mermaid-preview-area relative overflow-hidden block",style:{height:`${t.value}px`,minHeight:"var(--ms-size-diagram-min-height)",background:"var(--diagram-bg)"}},[jn("pre",{class:"mermaid-source-code text-sm font-mono whitespace-pre-wrap",style:{position:"absolute",inset:"0",margin:"0",padding:"var(--ms-inset-panel-body)",overflow:"auto",textAlign:"left"}},String((n=e.node.code)!=null?n:"")),jn("div",{class:"_mermaid w-full text-center flex items-center justify-center min-h-full",style:{fontFamily:"inherit",contentVisibility:"auto",contain:"content",containIntrinsicSize:"var(--ms-size-diagram-min-height) 240px"}})])])}}}),i4e={docs:{showTooltips:!0,fade:!0,batchRendering:!0,initialRenderBatchSize:40,renderBatchSize:80,renderBatchDelay:16,renderBatchBudgetMs:6,renderBatchIdleTimeoutMs:120,deferNodesUntilVisible:!0,maxLiveNodes:220,liveNodeBuffer:60,nodeVirtual:"auto"},chat:{showTooltips:!1,fade:!1,batchRendering:!0,initialRenderBatchSize:32,renderBatchSize:48,renderBatchDelay:6,renderBatchBudgetMs:8,renderBatchIdleTimeoutMs:60,deferNodesUntilVisible:!0,maxLiveNodes:0,liveNodeBuffer:0,nodeVirtual:"auto"},minimal:{showTooltips:!1,fade:!1,batchRendering:!0,initialRenderBatchSize:32,renderBatchSize:48,renderBatchDelay:6,renderBatchBudgetMs:8,renderBatchIdleTimeoutMs:60,deferNodesUntilVisible:!0,maxLiveNodes:0,liveNodeBuffer:0,nodeVirtual:"auto"}};function br(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}const o4e=["data-custom-id"],s4e=["data-node-index","data-node-type"],SD="typewriter-simple-cursor-target",Aq=Hi(dt(Hn(Ht({},{name:"NodeRenderer"}),{__name:"NodeRenderer",props:{content:{},nodes:{},final:{type:Boolean},parseOptions:{},customMarkdownIt:{},debugPerformance:{type:Boolean,default:!1},customHtmlTags:{},mode:{},domMode:{},htmlPolicy:{},viewportPriority:{type:Boolean,default:void 0},viewportPriorityOptions:{},codeBlockStream:{type:Boolean,default:!0},codeBlockDarkTheme:{},codeBlockLightTheme:{},codeBlockMonacoOptions:{},codeRenderer:{},renderCodeBlocksAsPre:{type:Boolean,default:void 0},codeBlockMinWidth:{},codeBlockMaxWidth:{},codeBlockProps:{},mermaidProps:{},d2Props:{},infographicProps:{},showTooltips:{type:Boolean,default:void 0},themes:{},langs:{},isDark:{type:Boolean},customId:{},indexKey:{},typewriter:{type:[Boolean,String],default:!1},smoothStreaming:{type:[Boolean,String],default:"auto"},smoothStreamingOptions:{},parseCoalesceMs:{},fade:{type:Boolean,default:void 0},batchRendering:{type:Boolean,default:void 0},initialRenderBatchSize:{},renderBatchSize:{},renderBatchDelay:{},renderBatchBudgetMs:{},renderBatchIdleTimeoutMs:{},deferNodesUntilVisible:{type:Boolean,default:void 0},maxLiveNodes:{},liveNodeBuffer:{},nodeVirtual:{type:[Boolean,String],default:void 0},virtualScroll:{},renderAsFragment:{type:Boolean}},emits:["copy","copy-code","handleArtifactClick","click","mouseover","mouseout","virtual-state-change","height-change","render-settled","render-final","anchor-change"],setup(e,{expose:t,emit:n}){const i=e,o=n;function s(H){if(!(typeof Event<"u"&&H instanceof Event))return typeof H=="string"&&o("copy-code",H),void o("copy",H)}const r=Vs(),l=rn("markstreamNestedRendererProps",void 0);function a(H){const te=r?.vnode.props;return!!te&&(Object.prototype.hasOwnProperty.call(te,H)||Object.prototype.hasOwnProperty.call(te,String(H).replace(/[A-Z]/g,he=>`-${he.toLowerCase()}`)))}function u(H){var te,he;const ve=i[H];return a(H)?ve:(he=(te=l?.value)==null?void 0:te[H])!=null?he:ve}const c=D(()=>{return(H=u("mode"))==="chat"||H==="minimal"||H==="docs"?H:"docs";var H}),d=D(()=>dD(u("typewriter"))),h=D(()=>d.value!=="off"),p=D(()=>u("domMode")==="minimal"?"minimal":"full"),m=D(()=>{return(H={mode:c.value,codeRenderer:u("codeRenderer"),renderCodeBlocksAsPre:u("renderCodeBlocksAsPre")}).renderCodeBlocksAsPre===!0?"pre":H.codeRenderer==="pre"||H.codeRenderer==="shiki"||H.codeRenderer==="monaco"?H.codeRenderer:H.renderCodeBlocksAsPre===!1||H.mode==="docs"?"monaco":"pre";var H}),g=D(()=>i4e[c.value]),y=D(()=>{var H;return(H=u("showTooltips"))!=null?H:g.value.showTooltips}),b=D(()=>{var H;return(H=u("fade"))!=null?H:g.value.fade}),v=D(()=>{var H;return(H=u("batchRendering"))!=null?H:g.value.batchRendering}),C=D(()=>{var H;return(H=u("initialRenderBatchSize"))!=null?H:g.value.initialRenderBatchSize}),w=D(()=>{var H;return(H=u("renderBatchSize"))!=null?H:g.value.renderBatchSize}),M=D(()=>{var H;return(H=u("renderBatchDelay"))!=null?H:g.value.renderBatchDelay}),N=D(()=>{var H;return(H=u("renderBatchBudgetMs"))!=null?H:g.value.renderBatchBudgetMs}),T=D(()=>{var H;return(H=u("renderBatchIdleTimeoutMs"))!=null?H:g.value.renderBatchIdleTimeoutMs}),S=D(()=>{var H;return(H=u("deferNodesUntilVisible"))!=null?H:g.value.deferNodesUntilVisible}),x=D(()=>{var H;return(H=u("maxLiveNodes"))!=null?H:g.value.maxLiveNodes}),A=D(()=>{var H;return(H=u("liveNodeBuffer"))!=null?H:g.value.liveNodeBuffer}),E=D(()=>{var H;return(H=u("nodeVirtual"))!=null?H:g.value.nodeVirtual}),I={get content(){return i.content},get nodes(){return i.nodes},get final(){return i.final},get parseOptions(){return u("parseOptions")},get customMarkdownIt(){return u("customMarkdownIt")},get debugPerformance(){return i.debugPerformance},get customHtmlTags(){return u("customHtmlTags")},get mode(){return u("mode")},get domMode(){return p.value},get htmlPolicy(){return u("htmlPolicy")},get viewportPriority(){return u("viewportPriority")},get viewportPriorityOptions(){return u("viewportPriorityOptions")},get codeBlockStream(){return u("codeBlockStream")},get codeBlockDarkTheme(){return u("codeBlockDarkTheme")},get codeBlockLightTheme(){return u("codeBlockLightTheme")},get codeBlockMonacoOptions(){return u("codeBlockMonacoOptions")},get codeRenderer(){return u("codeRenderer")},get renderCodeBlocksAsPre(){return u("renderCodeBlocksAsPre")},get codeBlockMinWidth(){return u("codeBlockMinWidth")},get codeBlockMaxWidth(){return u("codeBlockMaxWidth")},get codeBlockProps(){return u("codeBlockProps")},get mermaidProps(){return u("mermaidProps")},get d2Props(){return u("d2Props")},get infographicProps(){return u("infographicProps")},get showTooltips(){return y.value},get themes(){return u("themes")},get langs(){return u("langs")},get isDark(){return u("isDark")},get customId(){return u("customId")},get indexKey(){return i.indexKey},get typewriter(){return u("typewriter")},get smoothStreaming(){return i.smoothStreaming},get smoothStreamingOptions(){return u("smoothStreamingOptions")},get parseCoalesceMs(){return u("parseCoalesceMs")},get fade(){return b.value},get batchRendering(){return v.value},get initialRenderBatchSize(){return C.value},get renderBatchSize(){return w.value},get renderBatchDelay(){return M.value},get renderBatchBudgetMs(){return N.value},get renderBatchIdleTimeoutMs(){return T.value},get deferNodesUntilVisible(){return S.value},get maxLiveNodes(){return x.value},get liveNodeBuffer(){return A.value},get nodeVirtual(){return E.value},get virtualScroll(){return i.virtualScroll},get renderAsFragment(){return i.renderAsFragment}};function R(H){o("height-change",H)}function W(H){o("virtual-state-change",H)}function z(H){o("anchor-change",H)}const F=q(),O=q(null),B=q(null),j=q(null),$=Ki({1:null,2:null,3:null,4:null,5:null,6:null}),V=q(!1),ne=new Map,K=q(0),ee=q(0),ue=q({paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}});function ie(H,te){return typeof H!="string"?te:H.trim()||te}function ye(H){const te=Number(H);return Number.isFinite(te)&&te>0?Math.max(1,Math.trunc(te)):640}const Te=D(()=>{var H;const te=(H=I.viewportPriorityOptions)!=null?H:{},he=ie(te.rootMargin,op);return{rootMargin:he,heavyBlockMargin:ie(te.heavyBlockMargin,he),maxTargets:ye(te.maxTargets)}}),Ee=D(()=>{var H;return(H=Te.value.rootMargin)!=null?H:op}),Me=D(()=>{var H;return(H=Te.value.maxTargets)!=null?H:640});function G(){var H,te;if(((H=i.virtualScroll)==null?void 0:H.enabled)!==!0)return null;const he=(te=i.virtualScroll)==null?void 0:te.scrollRoot;return oe(typeof he=="function"?he():he)}function oe(H){return H?typeof HTMLElement<"u"&&H instanceof HTMLElement?H:typeof H=="object"&&"value"in H?oe(H.value):typeof H=="object"&&"$el"in H?oe(H.$el):null:null}ui(rq,Te);const{isClient:Z,renderAsFragment:Q,debugPerformanceEnabled:fe,resolvedShowTooltips:de,resolvedHtmlPolicy:pe,inheritedSmoothStreaming:X,ownsTypewriterCursor:re}=(function(H){const te=typeof window<"u",he=Nm(),ve=rn("markstreamHtmlPolicy",void 0),Ne=rn("markstreamTypewriterCursor",void 0),Ue=rn("markstreamSmoothStreaming",void 0),Ye=D(()=>H.renderAsFragment===!0),tt=D(()=>!!(H.debugPerformance&&te&&typeof console<"u")),bt=D(()=>{var kt;if(typeof H.showTooltips=="boolean")return H.showTooltips;const Je=(kt=he.showTooltips)!=null?kt:he["show-tooltips"];return Je===""||Je===!0||Je==="true"||Je!==!1&&Je!=="false"&&void 0}),nt=D(()=>{var kt,Je;return(Je=(kt=H.htmlPolicy)!=null?kt:ve?.value)!=null?Je:"safe"}),ht=D(()=>Ne?.value!==!0);return{isClient:te,renderAsFragment:Ye,debugPerformanceEnabled:tt,resolvedShowTooltips:bt,resolvedHtmlPolicy:nt,inheritedSmoothStreaming:Ue,inheritedTypewriterCursor:Ne,ownsTypewriterCursor:ht}})(I),{resolveViewportRoot:ke,resolveScrollContainer:le,isReverseFlexScrollRoot:se,getNormalizedScrollTop:_e,getOffsetTopWithinRoot:ge}=(function(H,te){function he(){var tt,bt;return(bt=(tt=te.scrollRoot)==null?void 0:tt.call(te))!=null?bt:null}function ve(tt){if(typeof window>"u")return null;const bt=he();if(bt)return bt;const nt=tt??H.value;if(!nt)return null;const ht=nt.ownerDocument||document,kt=ht.scrollingElement||ht.documentElement;let Je=nt;for(;Je&&Je!==ht.body&&Je!==kt;){if(Jbe(window.getComputedStyle(Je))&&Xbe(Je))return Je;Je=Je.parentElement}return null}function Ne(tt){if(!te.isClient)return!1;try{const bt=window.getComputedStyle(tt);return!!(bt.display||"").toLowerCase().includes("flex")&&(bt.flexDirection||"").toLowerCase().endsWith("reverse")}catch{return!1}}function Ue(tt,bt,nt){var ht,kt;if(nt)return Ye(bt);const Je=tt.scrollTop;if(!Ne(tt))return Je;const pt=Je<0?-Je:Je;return Math.max(0,((ht=tt.scrollHeight)!=null?ht:0)-((kt=tt.clientHeight)!=null?kt:0))-pt}function Ye(tt){var bt,nt,ht,kt,Je;const pt=Number((bt=tt.scrollingElement)==null?void 0:bt.scrollTop),Nt=Number((ht=(nt=tt.documentElement)==null?void 0:nt.scrollTop)!=null?ht:0),_t=Number((Je=(kt=tt.body)==null?void 0:kt.scrollTop)!=null?Je:0);return Math.max(0,Number.isFinite(pt)?pt:0,Number.isFinite(Nt)?Nt:0,Number.isFinite(_t)?_t:0)}return{resolveViewportRoot:ve,resolveScrollContainer:function(tt){var bt,nt,ht,kt;const Je=he();if(Je)return Je;const pt=ve((bt=tt??H.value)!=null?bt:null);if(pt)return pt;const Nt=(kt=(ht=tt?.ownerDocument)!=null?ht:(nt=H.value)==null?void 0:nt.ownerDocument)!=null?kt:typeof document<"u"?document:null;return Nt?.scrollingElement||Nt?.documentElement||null},isReverseFlexScrollRoot:Ne,getNormalizedScrollTop:Ue,getOffsetTopWithinRoot:function(tt,bt){const nt=bt.ownerDocument||tt.ownerDocument||document;if((function(pt,Nt){return pt===Nt.documentElement||pt===Nt.body||pt===Nt.scrollingElement})(bt,nt))return tt.getBoundingClientRect().top+Ye(nt);const ht=bt.getBoundingClientRect(),kt=tt.getBoundingClientRect(),Je=Ue(bt,nt,!1);return kt.top-ht.top+Je}}})(F,{isClient:Z,scrollRoot:G});ui("markstreamShowTooltips",de),ui("markstreamHtmlPolicy",pe),ui("markstreamTypewriter",h),ui("markstreamFade",D(()=>I.fade!==!1)),ui("markstreamTypewriterCursor",D(()=>!0)),ui("markstreamTextStreamState",ne),ui("markstreamStreamVersion",K),ui("markstreamParseOptions",D(()=>I.parseOptions)),ui("markstreamCustomMarkdownIt",D(()=>I.customMarkdownIt));const{smoothStreamingEnabled:Le,renderContent:be,requestedFinal:xe,effectiveFinal:Oe}=(function(H,te){const he=Qbe(Ht(Ht({},Ybe),H.smoothStreamingOptions)),ve=D(()=>{var Je,pt,Nt;return H.smoothStreaming!==!1&&!((Je=H.nodes)!=null&&Je.length)&&(H.smoothStreaming===!0||!((pt=te.inheritedSmoothStreaming)!=null&&pt.value))&&(H.smoothStreaming===!0||dD(H.typewriter)!=="off"||((Nt=H.maxLiveNodes)!=null?Nt:0)<=0)}),Ne=q(!te.isClient||H.smoothStreaming===!0);xn(()=>{Ne.value=!0});const Ue=D(()=>Ne.value&&ve.value),Ye=D(()=>{var Je;return Ue.value?he.visible.value:(Je=H.content)!=null?Je:""}),tt=D(()=>{var Je,pt;const Nt=(Je=H.parseOptions)!=null?Je:{};return(pt=H.final)!=null?pt:Nt.final}),bt=D(()=>{const Je=tt.value;return Ue.value&&Je!=null?!!Je&&he.caughtUp.value:Je});let nt=0,ht=!1;function kt(){nt=0,ht=!1}return qe([()=>H.content,()=>H.nodes,Ue,tt],([Je,pt,Nt,_t])=>{if(pt?.length)return kt(),void he.reset("");const Yt=Je??"";if(!Nt)return kt(),he.reset(Yt),void(_t&&he.finish({flush:!0}));const $t=he.source.value;if(Yt){if(Yt!==$t)if(Yt.startsWith($t)){const pn=Yt.slice($t.length),vn=he.pendingChars.value;pn.length<=8?(nt++,ht||nt>=2&&vn<=8?(ht=!0,he.reset(Yt)):he.enqueue(pn)):(kt(),he.enqueue(pn))}else kt(),he.reset(Yt)}else kt(),he.reset("");_t&&he.finish()},{immediate:!0}),{smoothStream:he,smoothStreamingEligible:ve,smoothStreamingEnabled:Ue,renderContent:Ye,requestedFinal:tt,effectiveFinal:bt}})(I,{isClient:Z,inheritedSmoothStreaming:X}),Ze=xe.value===!0;ui("markstreamSmoothStreaming",Le);const ct=q(!1),yt=q(!1),Wt=q(!1);let Gt="",Be=!1,$e=null;function Ke(){Z&&$e!=null&&(window.clearTimeout($e),$e=null)}function ft(){ct.value=!1,Ke()}function Ct(H,te){if(!fe.value)return;const he=(function(){if(!fe.value)return null;const ve=ot(Mt),Ne=ot(qt),Ue=Math.max(it,Ne);if(ve<=0&&Ue<=0)return null;const Ye={total:ve,maxPerFrame:Ue,byLabel:(tt=Mt,Object.fromEntries(Array.from(tt.entries()).sort((bt,nt)=>nt[1]-bt[1]||bt[0].localeCompare(nt[0]))))};var tt;return Mt.clear(),qt.clear(),it=0,Ye})();console.info(`[markstream-vue][perf] ${H}`,he?Hn(Ht({},te),{layoutReads:he}):te)}qe([()=>I.indexKey,()=>I.customId],()=>{var H,te;ft(),yt.value=!1,Wt.value=!((H=i.nodes)!=null&&H.length)&&xe.value!==!0&&!!i.content,Gt=(te=be.value)!=null?te:"",Be=Gt.length>0},{flush:"sync"}),qe([()=>i.content,()=>i.nodes,xe],([H,te,he])=>{!te?.length&&he!==!0&&H&&(Wt.value=!0)},{flush:"sync",immediate:!0}),qe([be,()=>i.nodes,xe],([H,te,he])=>{const ve=H??"";return te?.length||he===!0?(ft(),yt.value=!1,Gt=ve,void(Be=!0)):(ve.length>0&&(Wt.value=!0),Be?(Gt&&ve.length>Gt.length&&ve.startsWith(Gt)?(ct.value=!0,yt.value=!0,Z&&(Ke(),$e=window.setTimeout(()=>{var Ne;$e=null,Oe.value===!0||(Ne=i.nodes)!=null&&Ne.length||(Op(),ct.value=!1,Ac())},1200))):(ve.length"u")return null;const Ue=window;if(Ue.__markstreamLayoutReadPerformance)return Ue.__markstreamLayoutReadPerformance;const Ye={total:0,maxPerFrame:0,byLabel:{}};return Ue.__markstreamLayoutReadPerformance=Ye,Ye})();Ne&&(Ne.total=Number(Ne.total||0)+1,Ne.byLabel[ve]=Number(Ne.byLabel[ve]||0)+1,Ne.currentFrameTotal=Number(Ne.currentFrameTotal||0)+1,Ne.frameScheduled||(Ne.frameScheduled=!0,typeof window.requestAnimationFrame!="function"?typeof queueMicrotask!="function"?setTimeout(()=>cn(Ne),0):queueMicrotask(()=>cn(Ne)):window.requestAnimationFrame(()=>cn(Ne))))})(H),De||(De=!0,Z&&typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(zt):typeof queueMicrotask!="function"?setTimeout(zt,0):queueMicrotask(zt)))}function st(H,te){return gt(H),te()}const Tt=I.customId?`renderer-${I.customId}`:`renderer-${Date.now()}-${Math.random().toString(36).slice(2)}`,sn=(function(H){const te=new Map;return{scope:H,cache:te,clear:()=>te.clear()}})(Tt),ki=Tt;ui(pq,sn);const In=Ks(()=>I.customId),{effectiveCustomHtmlTagsSet:Zo,mergedParseOptions:Go,parsedNodes:ze,getParsedNodesDirtyStartIndex:At,getParsedNodesRevision:lt}=Zbe(I,{instanceMsgId:Tt,renderContent:be,effectiveFinal:Oe,smoothStreamingEnabled:Le,debugPerformanceEnabled:fe,customComponentsMap:In,logPerf:Ct});qe(ze,()=>{ct.value||sn.clear(),K.value+=1},{immediate:!0});const kn=D(()=>({customId:I.customId,customHtmlTags:Go.value.customHtmlTags,parseOptions:I.parseOptions,customMarkdownIt:I.customMarkdownIt,htmlPolicy:pe.value,viewportPriority:I.viewportPriority,viewportPriorityOptions:Te.value,mode:c.value,domMode:I.domMode,codeRenderer:m.value,codeBlockStream:I.codeBlockStream,codeBlockDarkTheme:I.codeBlockDarkTheme,codeBlockLightTheme:I.codeBlockLightTheme,codeBlockMonacoOptions:I.codeBlockMonacoOptions,renderCodeBlocksAsPre:I.renderCodeBlocksAsPre,codeBlockMinWidth:I.codeBlockMinWidth,codeBlockMaxWidth:I.codeBlockMaxWidth,codeBlockProps:I.codeBlockProps,mermaidProps:I.mermaidProps,d2Props:I.d2Props,infographicProps:I.infographicProps,showTooltips:de.value,themes:I.themes,langs:I.langs,isDark:I.isDark,typewriter:h.value,smoothStreamingOptions:I.smoothStreamingOptions,parseCoalesceMs:I.parseCoalesceMs,fade:I.fade}));ui("markstreamNestedRendererProps",kn);const Dt=D(()=>ze.value),wi=D(()=>ze.value.length),vo=q(null),Io=q(null),Wr=q(null),Mo=q(null),Bo=i.indexKey!=null&&String(i.indexKey).startsWith("list-item-"),yo=!Bo&&I.customId?rD(I.customId):null,Zs=D(()=>yo?(aw.value,rD(I.customId)):null),ni=D(()=>{var H;return!!(!Q.value&&I.customId&&!Bo&&((H=Zs.value)!=null&&H.enabled))}),Li=D(()=>!!(Z&&ni.value)),Sn=D(()=>{var H;return!!(!Q.value&&((H=i.virtualScroll)!=null&&H.enabled))}),To=D(()=>Sn.value),Gs=q(!1);xn(()=>{Gs.value=!0});const Bn=D(()=>!!(Z&&Sn.value));ui("markstreamHostScrollManaged",Bn);const io=D(()=>!!(Gs.value&&Bn.value)),oo=D(()=>Li.value||Bn.value),ks=D(()=>Li.value||io.value),ri=D(()=>{var H;return oo.value&&((H=Zs.value)==null?void 0:H.textEstimation)!==!1});function hi(){const H=ee.value||st("getMeasuredContainerWidth.clientWidth",()=>{var te;return((te=F.value)==null?void 0:te.clientWidth)||0});return Number.isFinite(H)&&H>0?H:0}const _r=D(()=>{const H=hi();return H>0?Math.max(1,Math.round(H)):640}),Eo=D(()=>{var H,te;return!(Oe.value!==!0||Sn.value||c.value!=="chat"&&c.value!=="minimal"||a("maxLiveNodes")||a("liveNodeBuffer")||(H=i.nodes)!=null&&H.length||Wt.value||!(((te=I.maxLiveNodes)!=null?te:0)<=0))}),qr=D(()=>{var H;return Eo.value?50:Math.max(1,(H=I.maxLiveNodes)!=null?H:320)}),Lo=D(()=>{var H;return Eo.value?16:Math.max(0,(H=I.liveNodeBuffer)!=null?H:60)}),An=D(()=>{var H;return!Q.value&&I.nodeVirtual!==!1&&!(((H=I.maxLiveNodes)!=null?H:0)<=0&&!Eo.value)&&(I.nodeVirtual===!0?ze.value.length>0:ze.value.length>qr.value)}),Qs=D(()=>An.value||Li.value||Bn.value),fr=D(()=>I.viewportPriority!==!1),ta=D(()=>!!fr.value&&!V.value);var Ys;Ys=D(()=>fr.value),ui(lq,Ys);const ll=D(()=>{var H;return!(Q.value||I.deferNodesUntilVisible===!1||((H=I.maxLiveNodes)!=null?H:0)<=0||An.value||ze.value.length>900||I.viewportPriority===!1)}),so=T9e(H=>{var te;return ke((te=H??F.value)!=null?te:null)},fr),{requestFrame:Wi,cancelFrame:Ni,hasIdleCallback:Qo,isTestEnv:No}=(function(H){const te=H.isClient&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame.bind(window):null,he=H.isClient&&typeof window.cancelAnimationFrame=="function"?window.cancelAnimationFrame.bind(window):null,ve=H.isClient&&typeof window.requestIdleCallback=="function",Ne=(function(){var Ue;if(typeof globalThis>"u"||!("process"in globalThis))return;const Ye=(Ue=Object.getOwnPropertyDescriptor(globalThis,"process"))==null?void 0:Ue.value;return Ye?.env})();return{requestFrame:te,cancelFrame:he,hasIdleCallback:ve,isTestEnv:Ne?.NODE_ENV==="test"}})({isClient:Z}),hr=D(()=>Oe.value===!0&&!Sn.value),{resolvedBatchSize:Ir,resolvedInitialBatch:Js,batchingEnabled:na,incrementalRenderingActive:pr,renderedCount:us,previousRenderContext:Di,adaptiveBatchSize:Pi,previousBatchConfig:qi}=(function(H,te){var he;const ve=D(()=>{var kt;const Je=Math.trunc((kt=H.renderBatchSize)!=null?kt:80);return Number.isFinite(Je)?Math.max(0,Je):0}),Ne=D(()=>{var kt;const Je=Math.trunc((kt=H.initialRenderBatchSize)!=null?kt:ve.value);return Number.isFinite(Je)?Math.max(0,Je):ve.value}),Ue=D(()=>!te.renderAsFragment.value&&H.batchRendering!==!1&&ve.value>0&&te.isClient&&!te.isTestEnv),Ye=q(0),tt=q({key:H.indexKey,total:0}),bt=q(Math.max(1,ve.value||1)),nt=D(()=>{var kt,Je,pt;return Ue.value&&!((kt=te.continuousStreaming)!=null&&kt.value)&&!((Je=te.forceFullRenderFinalContent)!=null&&Je.value)&&((pt=H.maxLiveNodes)!=null?pt:0)<=0}),ht=q({batchSize:ve.value,initial:Ne.value,delay:(he=H.renderBatchDelay)!=null?he:16,enabled:nt.value});return{resolvedBatchSize:ve,resolvedInitialBatch:Ne,batchingEnabled:Ue,incrementalRenderingActive:nt,renderedCount:Ye,previousRenderContext:tt,adaptiveBatchSize:bt,previousBatchConfig:ht}})(I,{isClient:Z,isTestEnv:No,renderAsFragment:Q,forceFullRenderFinalContent:hr,continuousStreaming:D(()=>yt.value&&Oe.value!==!0)}),Fi=D(()=>{var H;return!Q.value&&I.batchRendering!==!1&&Ir.value>0&&!No&&((H=I.maxLiveNodes)!=null?H:0)<=0&&!hr.value}),pi=D(()=>Fi.value),Gi=D(()=>oo.value||pi.value),ro=D(()=>{var H;return Gi.value&&((H=Zs.value)==null?void 0:H.codeBlockEstimation)!==!1}),Qi=new Map,Ur=new Map,al=new WeakMap;let po=null;const Vr=new WeakMap,Yi=new Map,bs=[];let at=[],et=[],wt=-1;const Et=_u(bs),bn=new Set,Do=q(0);let Ji=0;const Kr=q(0),zo=D(()=>(Kr.value,Array.from(Qi.entries()).sort((H,te)=>H[0]-te[0]))),ko=q(null),Ci=q(null);let bo,Xs=null,wo=0,Fo=null;function Ro(){bo.markFallbackHeightPrefixDirty()}function Is(H){return bo.getFallbackNodeHeight(H)}function er(H,te){return bo.estimateHeightRange(H,te)}function Zr(H){return bo.estimateIndexForOffset(H)}const{activeRestoreAnchor:ws,getRelativeScrollTopWithinContainer:Mr,setRelativeScrollTopWithinContainer:_l,resolveAnchorOffset:Eu,clearRestoreReconcile:Il,scheduleRestoreReconcile:jo,captureRestoreAnchor:Gr,restoreAnchor:Tr,getAnchorDrift:Ml}=(function(H){const{isClient:te,containerRef:he,parsedNodeCount:ve,requestFrame:Ne,cancelFrame:Ue,resolveScrollContainer:Ye,getNormalizedScrollTop:tt,getOffsetTopWithinRoot:bt,isReverseFlexScrollRoot:nt,estimateIndexForOffset:ht,estimateHeightRange:kt,getFallbackNodeHeight:Je,clamp:pt}=H,Nt=q(null);let _t=null,Yt=[];function $t(){const Nn=Ye(),Qn=he.value;if(!Nn||!Qn)return null;const Jn=Nn.ownerDocument||Qn.ownerDocument||document;if(Nn===Jn.documentElement||Nn===Jn.body||Nn===Jn.scrollingElement){const Xi=Qn.getBoundingClientRect();return Math.max(0,-Xi.top)}return Math.max(0,tt(Nn,Jn,!1)-bt(Qn,Nn))}function pn(Nn){var Qn;const Jn=Ye(),Xi=he.value;if(!Jn||!Xi)return;const Nr=Math.max(0,Nn),kr=Jn.ownerDocument||Xi.ownerDocument||document,iu=kr.defaultView||(typeof window<"u"?window:null);if(Jn===kr.documentElement||Jn===kr.body||Jn===kr.scrollingElement){const Du=tt(Jn,kr,!0)+Xi.getBoundingClientRect().top;return void((Qn=iu?.scrollTo)==null||Qn.call(iu,0,Math.max(0,Du+Nr)))}uD(Jn,kr,bt(Xi,Jn)+Nr,{isReverseFlexScrollRoot:Du=>{var vg;return(vg=nt?.(Du))!=null&&vg},getNormalizedScrollTop:tt})}function vn(Nn){const Qn=ve.value,Jn=pt(Nn.nodeIndex,0,Math.max(0,Qn-1));return kt(0,Jn)+Math.max(0,Nn.offsetWithinNodePx)}function Ln(){if(_t!=null&&(Ue?.(_t),_t=null),te)for(const Nn of Yt)window.clearTimeout(Nn);Yt=[]}function Mn(Nn){const Qn=vn(Nn),Jn=$t();Jn!=null&&Math.abs(Jn-Qn)<=.5||pn(Qn)}return{activeRestoreAnchor:Nt,getRelativeScrollTopWithinContainer:$t,setRelativeScrollTopWithinContainer:pn,resolveAnchorOffset:vn,clearRestoreReconcile:Ln,applyRestoreAnchor:Mn,scheduleRestoreReconcile:function(){Nt.value&&te&&_t==null&&(_t=Ne?Ne(()=>{_t=null,Nt.value&&Mn(Nt.value)}):null,_t==null&&Nt.value&&Mn(Nt.value))},captureRestoreAnchor:function(){const Nn=$t(),Qn=ve.value;if(Nn==null||Qn<=0)return null;const Jn=pt(ht(Nn+1),0,Qn-1),Xi=kt(0,Jn),Nr=Je(Jn);return{nodeIndex:Jn,offsetWithinNodePx:pt(Nn-Xi,0,Math.max(0,Nr-1))}},restoreAnchor:function(Nn){const Qn=ve.value;if(Nt.value={nodeIndex:pt(Nn.nodeIndex,0,Math.max(0,Qn-1)),offsetWithinNodePx:Math.max(0,Nn.offsetWithinNodePx)},Ln(),Mn(Nt.value),te)for(const Jn of[0,120,280,480])Yt.push(window.setTimeout(()=>{Nt.value&&Mn(Nt.value)},Jn))},getAnchorDrift:function(Nn){const Qn=$t();return Qn==null?null:Qn-vn(Nn)}}})({isClient:Z,containerRef:F,parsedNodeCount:wi,requestFrame:Wi,cancelFrame:Ni,resolveScrollContainer:()=>ko.value||le(),getNormalizedScrollTop:_e,getOffsetTopWithinRoot:ge,isReverseFlexScrollRoot:se,estimateIndexForOffset:Zr,estimateHeightRange:er,getFallbackNodeHeight:Is,clamp:Wo}),{nodeHeights:Ho,heightStats:Cs,heightTreeSize:cs,heightSumTree:Yo,heightKnownTree:vc,averageNodeHeight:Xa,resetHeightMeasurements:mr,pruneHeightMeasurements:Er,rebuildHeightTrees:ia,recordNodeHeight:yc,removeNodeHeights:Y,exportHeightCache:we,importHeightCache:Re,fenwickRangeSum:Ve}=(function(H={}){const te=Ki({}),he=Ki({total:0,count:0}),ve=q(0),Ne=q([]),Ue=q([]);function Ye(){for(const Je of Object.keys(te))delete te[Number(Je)];he.total=0,he.count=0,ve.value=0,Ne.value=[],Ue.value=[]}function tt(Je,pt,Nt){for(let _t=pt+1;_t0;_t-=_t&-_t)Nt+=Je[_t];return Nt}function nt(Je){ve.value=Je;const pt=new Array(Je+1).fill(0),Nt=new Array(Je+1).fill(0);for(const[_t,Yt]of Object.entries(te)){const $t=Number(_t),pn=Number(Yt);!Number.isFinite($t)||$t<0||$t>=Je||!Number.isFinite(pn)||pn<=0||(tt(pt,$t,pn),tt(Nt,$t,1))}Ne.value=pt,Ue.value=Nt}function ht(Je){if(!Number.isInteger(Je)||Je<0)return!1;const pt=te[Je];if(!Number.isFinite(pt)||pt<=0)return!1;if(delete te[Je],he.total=Math.max(0,he.total-pt),he.count=Math.max(0,he.count-1),ve.value>Je){const Nt=Ne.value,_t=Ue.value;Nt.length&&_t.length&&(tt(Nt,Je,-pt),tt(_t,Je,-1))}return!0}const kt=D(()=>he.count>0?Math.max(12,he.total/he.count):32);return{nodeHeights:te,heightStats:he,heightTreeSize:ve,heightSumTree:Ne,heightKnownTree:Ue,averageNodeHeight:kt,resetHeightMeasurements:Ye,pruneHeightMeasurements:function(Je){if(Je<=0)return void Ye();let pt=0,Nt=0;for(const[_t,Yt]of Object.entries(te)){const $t=Number(_t),pn=Number(Yt);!Number.isFinite($t)||$t<0||$t>=Je||!Number.isFinite(pn)||pn<=0?delete te[$t]:(pt+=pn,Nt++)}he.total=pt,he.count=Nt},rebuildHeightTrees:nt,recordNodeHeight:function(Je,pt,Nt={}){(function(_t,Yt,$t={}){var pn;if(!Number.isFinite(Yt)||Yt<=0)return!1;const vn=te[_t];if(vn&&($t.allowShrink===!1&&Yt_t){const Ln=Ne.value,Mn=Ue.value;if(Ln.length&&Mn.length)if(vn){const Nn=Yt-vn;Nn!==0&&tt(Ln,_t,Nn)}else tt(Ln,_t,Yt),tt(Mn,_t,1)}$t.notify!==!1&&((pn=H.onHeightRecorded)==null||pn.call(H))})(Je,pt,Hn(Ht({},Nt),{notify:!0}))},removeNodeHeight:function(Je,pt={}){var Nt;const _t=ht(Je);return _t&&pt.notify!==!1&&((Nt=H.onHeightRecorded)==null||Nt.call(H)),_t},removeNodeHeights:function(Je,pt={}){var Nt;let _t=0;for(const Yt of Je)ht(Number(Yt))&&_t++;return _t>0&&pt.notify!==!1&&((Nt=H.onHeightRecorded)==null||Nt.call(H)),_t},exportHeightCache:function(){return Object.entries(te).map(([Je,pt])=>({index:Number(Je),height:Number(pt)})).filter(Je=>Number.isFinite(Je.index)&&Je.index>=0&&Number.isFinite(Je.height)&&Je.height>0).sort((Je,pt)=>Je.index-pt.index)},importHeightCache:function(Je,pt={}){var Nt;if(!Array.isArray(Je))return;const _t=ve.value;let Yt=!1;if(pt.mode!=="merge"){const $t=Object.keys(te);if($t.length>0){for(const pn of $t)delete te[Number(pn)];Yt=!0}}for(const $t of Je){const pn=Number($t.index),vn=Number($t.height);if(!Number.isInteger(pn)||pn<0||_t>0&&pn>=_t||!Number.isFinite(vn)||vn<=0)continue;const Ln=te[pn];Ln&&Math.abs(Ln-vn)<=1||(te[pn]=vn,Yt=!0)}Yt&&((function(){let $t=0,pn=0;const vn=ve.value;for(const[Ln,Mn]of Object.entries(te)){const Nn=Number(Ln),Qn=Number(Mn);!Number.isFinite(Nn)||Nn<0||vn>0&&Nn>=vn||!Number.isFinite(Qn)||Qn<=0?delete te[Nn]:($t+=Qn,pn++)}he.total=$t,he.count=pn})(),_t>0&&nt(_t),(Nt=H.onHeightRecorded)==null||Nt.call(H))},fenwickRangeSum:function(Je,pt,Nt){if(Nt<=pt)return 0;const _t=bt(Je,Nt-1);return pt<=0?_t:_t-bt(Je,pt-1)}}})({onHeightRecorded:()=>{Ro(),Bn.value&&dg(),ws.value&&jo(),Ci.value&&Dp(),Co("node-resize")}});function Qe(H){Number.isInteger(H)&&H>=0&&bn.add(H)}function rt(H){for(const te of H)Qe(Number(te))}function me(H){Ji++;let te=!0;try{const he=H();return te=he!==!1,he}finally{Ji--,Ji===0&&te&&Do.value++}}function Ce(){at=[],et=[],wt=-1,bn.clear(),Et.value=bs}function Ge(){Ce(),me(()=>mr()),Yi.clear()}function Ft(H){!Number.isInteger(H)||H<0||H>=ze.value.length||Yi.set(H,eg(H))}function Bt(H,te,he={}){const ve=Ho[H];Qe(H),yc(H,te,he);const Ne=Ho[H];return Object.is(ve,Ne)?(bn.delete(H),!1):(Ne&&Ne>0?Ft(H):ve&&Yi.delete(H),!0)}function Qt(H,te){const he=st("getNodeLayoutHeight.slot.offsetHeight",()=>{var ve,Ne;return(Ne=(ve=Qi.get(H))==null?void 0:ve.offsetHeight)!=null?Ne:0});return he>0?he:st("getNodeLayoutHeight.content.offsetHeight",()=>te.offsetHeight)}function mn(H,te={}){te.mode!=="merge"?Ce():rt(H.map(he=>he.index)),me(()=>Re(H,te)),S3()}const on=D(()=>ll.value&&ta.value),Dn=D(()=>{var H;return!Q.value&&I.batchRendering!==!1&&Ir.value>0&&((H=I.maxLiveNodes)!=null?H:0)<=0}),gi=D(()=>!Q.value&&Ze&&Oe.value===!0&&!An.value&&!Sn.value&&!ni.value&&!on.value&&!Dn.value),ii=D(()=>!!so&&on.value),Jo=D(()=>An.value||Bn.value),{focusIndex:Xo,liveRange:lo,updateLiveRange:Oo}=(function(H,te){const{parsedNodeCount:he,virtualizationEnabled:ve,maxLiveNodesResolved:Ne,liveNodeBufferResolved:Ue,clamp:Ye}=te,tt=Ue??D(()=>{var ht;return Math.max(0,(ht=H.liveNodeBuffer)!=null?ht:60)}),bt=q(0),nt=Ki({start:0,end:0});return{liveNodeBufferResolved:tt,focusIndex:bt,liveRange:nt,updateLiveRange:function(){const ht=he.value;if(!ve.value||ht===0)return nt.start=0,void(nt.end=ht);const kt=Math.min(Ne.value,ht),Je=tt.value,pt=Ye(bt.value-Je,0,Math.max(0,ht-kt));nt.start=pt,nt.end=Math.min(ht,pt+kt)}}})(I,{parsedNodeCount:wi,virtualizationEnabled:An,maxLiveNodesResolved:qr,liveNodeBufferResolved:Lo,clamp:Wo}),ao=new Map,Lr=new Map,tr=new Map,eu=[],es=new Map,vi=new Set,xa=q(0);let gr=!1;const Sa=D(()=>(xa.value,vi.size)),vr=new Map,ul=new Map,Wf=q(0),Lu=D(()=>{Wf.value;let H=0;for(const te of vr.values())H+=Math.max(0,te);return H});let nr=null;const hd=D(()=>{if(!An.value)return ze.value.length;const H=Lo.value,te=Math.max(lo.end+H,Js.value),he=Math.min(ze.value.length,te);return Math.max(us.value,he)});function kc(){gr||(gr=!0,queueMicrotask(()=>{gr=!1,xa.value+=1}))}function Se(H,te,he="node-resize"){if(!Z||typeof window>"u")return null;const ve=window.setTimeout(()=>{vi.delete(ve)&&kc();try{te()}finally{Co(he)}},Math.max(0,H));return vi.add(ve),kc(),ve}function We(H){Z&&H!=null&&(vi.delete(H)&&kc(),window.clearTimeout(H))}function vt(){if(Z&&typeof window<"u")for(const H of vi)window.clearTimeout(H);vi.size&&(vi.clear(),kc()),eu.length=0,tr.clear()}function Kt(H){O.value=H}function _n(H){B.value=H}function Un(H){j.value=H}const{cancelScheduledFocusSync:li,scheduleFocusSync:ai}=(function(H){const{isClient:te,containerRef:he,virtualizationEnabled:ve,requestFrame:Ne,cancelFrame:Ue,syncFocusToScroll:Ye}=H;let tt=null;function bt(){var ht,kt,Je;return(Je=(kt=(ht=he.value)==null?void 0:ht.ownerDocument)==null?void 0:kt.defaultView)!=null?Je:typeof window<"u"?window:null}function nt(){if(!tt)return;const ht=bt();tt.viaTimeout?ht?ht.clearTimeout(tt.id):clearTimeout(tt.id):Ue?.(tt.id),tt=null}return{cancelScheduledFocusSync:nt,scheduleFocusSync:function(ht={}){if(!ve.value)return;if(!te)return void Ye(!0);if(ht.immediate)return nt(),void Ye(!0);if(tt)return;const kt=()=>{tt=null,Ye()};if(Ne)return void(tt={id:Ne(kt),viaTimeout:!1});const Je=bt();tt={id:Je?Je.setTimeout(kt,16):setTimeout(kt,16),viaTimeout:!0}}}})({isClient:Z,containerRef:F,virtualizationEnabled:An,requestFrame:Wi,cancelFrame:Ni,syncFocusToScroll:function(H=!1){var te;if(!An.value)return;const he=ko.value||le();if(!he)return;const ve=he.ownerDocument||((te=F.value)==null?void 0:te.ownerDocument)||document,Ne=ve?.defaultView||(typeof window<"u"?window:null),Ue=he===ve?.documentElement||he===ve?.body,Ye=ze.value.length;if(Ye<=0)return;if(!Ue&&Ye>0&&se(he)){const _t=st("syncFocusToScroll.clientHeight",()=>he.clientHeight||0),Yt=st("syncFocusToScroll.scrollTop",()=>he.scrollTop),$t=Yt<0?-Yt:Yt;return void _p(Wo((tt=Math.max(0,$t)+.5*Math.max(0,_t),bo.estimateIndexForOffsetFromEnd(tt)),0,Math.max(0,Ye-1)),H)}var tt;const bt=(function(_t,Yt,$t,pn){const vn=F.value;if(!vn)return null;const Ln=pn?0:st("syncFocusToScroll.model.root.getBoundingClientRect",()=>_t.getBoundingClientRect().top),Mn=st("syncFocusToScroll.model.container.getBoundingClientRect",()=>vn.getBoundingClientRect().top),Nn=Math.max(0,Ln-Mn),Qn=pn?st("syncFocusToScroll.model.viewport.clientHeight",()=>{var Jn,Xi,Nr,kr;return(kr=(Nr=(Xi=$t?.innerHeight)!=null?Xi:(Jn=Yt.documentElement)==null?void 0:Jn.clientHeight)!=null?Nr:_t.clientHeight)!=null?kr:0}):st("syncFocusToScroll.model.root.clientHeight",()=>_t.clientHeight);return Wo(Zr(Nn+.5*Math.max(0,Qn)),0,Math.max(0,ze.value.length-1))})(he,ve,Ne,Ue);if(bt!=null)return void _p(bt,H);const nt=Ue?null:st("syncFocusToScroll.root.getBoundingClientRect",()=>he.getBoundingClientRect()),ht=Ue?0:nt.top,kt=Ue?st("syncFocusToScroll.viewport.clientHeight",()=>{var _t,Yt;return(Yt=(_t=Ne?.innerHeight)!=null?_t:he.clientHeight)!=null?Yt:0}):nt.bottom,Je=zo.value;let pt=null,Nt=null;for(const[_t,Yt]of Je){if(!Yt)continue;const $t=st("syncFocusToScroll.slot.getBoundingClientRect",()=>Yt.getBoundingClientRect());$t.bottom<=ht||$t.top>=kt||(pt==null&&(pt=_t),Nt=_t)}if(pt==null||Nt==null){const _t=F.value;if(!_t)return;const Yt=Ue?{top:0}:st("syncFocusToScroll.fallback.root.getBoundingClientRect",()=>he.getBoundingClientRect()),$t=st("syncFocusToScroll.fallback.scrollTop",()=>_e(he,ve,Ue)),pn=Ue?(()=>{const Ln=st("syncFocusToScroll.fallback.container.getBoundingClientRect",()=>_t.getBoundingClientRect()),Mn=(Ue?0:Yt.top)-Ln.top;return Math.max(0,Mn)})():(()=>{const Ln=ge(_t,he);return Math.max(0,$t-Ln)})(),vn=Ue?st("syncFocusToScroll.fallback.viewport.clientHeight",()=>{var Ln,Mn,Nn,Qn;return(Qn=(Nn=(Mn=Ne?.innerHeight)!=null?Mn:(Ln=ve?.documentElement)==null?void 0:Ln.clientHeight)!=null?Nn:he.clientHeight)!=null?Qn:0}):st("syncFocusToScroll.fallback.root.clientHeight",()=>he.clientHeight);return void _p(Wo(Zr(pn+.5*Math.max(0,vn)),0,Math.max(0,ze.value.length-1)),!0)}_p(Math.round((pt+Nt)/2),H)}}),{visibleNodeIndices:Ms,nodeVisibilityHandles:oa,nodeVisibilityWatchStops:Nu,nodeVisibilityFallbackTimers:x2,clearVisibilityFallback:Ap,markNodeVisible:tu,cleanupNodeVisibility:Gm,destroyNodeVisibilityState:xp}=Gbe({isClient:Z,shouldTrackVisibleNodeIndices:()=>on.value,shouldCleanupNodeVisibility:()=>An.value,onNodeMarkedVisible:H=>{An.value?ai():Xo.value=Wo(H,0,Math.max(0,ze.value.length-1))},onNodeVisibilityCleaned:H=>{Qi.delete(H)&&oI()}}),{cleanupScrollListener:Qm,setupScrollListener:Sp}=(function(H){const{isClient:te,virtualizationEnabled:he,listenerEnabled:ve,scrollRootElement:Ne,resolveScrollContainer:Ue,scheduleFocusSync:Ye,onScroll:tt}=H;let bt=null,nt=null;function ht(){bt&&(bt(),bt=null),nt=null,Ne.value=null}function kt(Je){const pt=H.getScrollTop?H.getScrollTop(Je):Je.scrollTop;return Math.max(0,Number.isFinite(pt)?Math.abs(pt):0)}return{cleanupScrollListener:ht,setupScrollListener:function(){if(!te)return;if(!((Je=ve?.value)!=null?Je:he.value))return void ht();var Je;const pt=Ue();if(!pt)return void ht();if(Ne.value===pt&&bt)return;ht(),nt=kt(pt);const Nt=()=>{if(tt?.(),he.value){const _t=(function(Yt){const $t=kt(Yt),pn=nt;nt=$t;const vn=Math.max(480,.75*(Yt.clientHeight||0));return pn==null?$t>vn?{immediate:!0}:void 0:Math.abs($t-pn)>vn?{immediate:!0}:void 0})(pt);_t?Ye(_t):Ye()}};pt.addEventListener("scroll",Nt,{passive:!0}),Ne.value=pt,bt=()=>{pt.removeEventListener("scroll",Nt)}}}})({isClient:Z,virtualizationEnabled:An,listenerEnabled:Jo,scrollRootElement:ko,resolveScrollContainer:le,scheduleFocusSync:ai,onScroll:function(){const H=Ci.value;if(!H)return;const te=Xm();if(!te||(function(ve){if(sg()>=wo)return Fo=null,!1;const Ne=Fo;if(Ne==null)return!0;const Ue=Math.abs(ve.scrollTop-Ne)<=2;return Ue||(Fo=null),Ue})(te))return;const he=V_(te);he!=null?(he<-32||Math.abs(Math.max(0,he)-Math.max(0,H.distanceFromBottomPx))>32)&&Np("restore"):Np("restore")},getScrollTop:H=>{var te;const he=H.ownerDocument||((te=F.value)==null?void 0:te.ownerDocument)||document,ve=H===he.documentElement||H===he.body||H===he.scrollingElement;return st("scrollListener.getScrollTop",()=>_e(H,he,ve))}});function _p(H,te=!1){const he=Wo(H,0,Math.max(0,ze.value.length-1));!te&&Math.abs(he-Xo.value)<=1||(Xo.value=he,Oo())}function Wo(H,te,he){return Math.min(Math.max(H,te),he)}function Ym(H=ze.value.length){const te=At();return!Number.isInteger(te)||te<0?H:Wo(te,0,H)}function Ip(H){return H?.firstElementChild}function S2(H,te){var he;return H?(he=H.matches)!=null&&he.call(H,te)?H:H.querySelector(te):null}function Jm(H,te){H<1||H>6||($[H]=te)}function Ie(){if(!oo.value)return void(ee.value=0);const H=st("updateExperimentContainerWidth.clientWidth",()=>{var te,he;return(he=(te=F.value)==null?void 0:te.clientWidth)!=null?he:0});ee.value=H>0?H:0}let ut=null;function Xe(){ut?.disconnect(),ut=null}const It=n0("ViewportDeferredMarkdownCodeBlockNode",Yu({loader:()=>xo(null,null,function*(){return(yield _s(()=>import("./index5-DEKGWcGw.js"),__vite__mapDeps([6,4,5]))).default}),loadingComponent:Jk,delay:0,suspensible:!1}),Jk);function wn(H){return H===It}const Wn=D(()=>m.value==="pre"?Ol:m.value==="shiki"?It:nw);function Rn(){var H;return((H=I.codeBlockProps)==null?void 0:H.showHeader)!==!1}function zn(H,te,he){const ve=Ho[te],Ne=typeof ve=="number"&&ve>0;if(ri.value&&!Ne&&!(function(Ue){return!!In.value.paragraph&&(Ue.type==="paragraph"||Ue.type==="list_item"||Ue.type==="list")})(H)){const Ue=hq(H,he,ue.value);if(Ue)return Ue}if(ro.value&&H.type==="code_block"){const Ue=(function(Ye){if(Ye.type!=="code_block")return null;const tt=gI(Ye,R2(Ye));return wn(tt)?"markdown":tt===Ol?"pre":tt===Wn.value||tt===nw?"monaco":null})(H);if(Ue==="monaco"||Ue==="markdown"||Ue==="pre")return(function(Ye,tt){var bt,nt,ht;if(!Ye||Ye.type!=="code_block")return null;const kt=tt.rendererKind,Je=kt!=="pre"&&tt.showHeader!==!1,pt=!!Ye.diff;let Nt=0,_t=500;if(kt==="monaco"){const $t=(bt=tt.monacoOptions)!=null?bt:{},pn=dw(Ye,$t,tt.width),vn=(function(Mn){const Nn=typeof Mn?.fontSize=="number"&&Mn.fontSize>0?Mn.fontSize:12;return typeof Mn?.lineHeight=="number"&&Mn.lineHeight>0?Mn.lineHeight:Math.round(1.5*Nn)})($t),Ln=(function(Mn,Nn){var Qn,Jn;const Xi=typeof((Qn=Mn?.padding)==null?void 0:Qn.top)=="number"?Mn.padding.top:Nn?0:8,Nr=typeof((Jn=Mn?.padding)==null?void 0:Jn.bottom)=="number"?Mn.padding.bottom:Nn?0:8;return Math.max(0,Xi)+Math.max(0,Nr)})($t,pt);_t=typeof $t.MAX_HEIGHT=="number"&&$t.MAX_HEIGHT>0?$t.MAX_HEIGHT:500,Nt=Math.round(pn*vn+Ln)}else if(kt==="markdown"){const $t=dw(Ye);Nt=Math.round(21*$t+32)}else{const $t=dw(Ye);Nt=Math.round(28*$t),_t=Number.POSITIVE_INFINITY}const Yt=Math.max(1,Math.min(Nt,_t));return Ht({kind:"code-block",height:Math.round(Yt+(Je?40:0)),contentHeight:Yt,rendererKind:kt},pt&&kt==="monaco"?{diffInline:xx((nt=tt.monacoOptions)!=null?nt:{},(ht=tt.width)!=null?ht:0)}:{})})(H,{rendererKind:Ue,monacoOptions:I.codeBlockMonacoOptions,showHeader:Rn(),width:he})}return null}P1(()=>{if(Do.value,Ji>0)return;const H=ze.value,te=lt();if(!H.length||!Gi.value)return at=[],et=[],wt=-1,bn.clear(),void(Et.value=bs);const he=ee.value||st("estimatedNodeHeights.clientWidth",()=>{var nt;return((nt=F.value)==null?void 0:nt.clientWidth)||0});if(!Number.isFinite(he)||he<=0)return at=[],et=[],wt=-1,bn.clear(),void(Et.value=bs);const ve=(function(nt){return[Math.round(nt),ri.value,ro.value,ue.value,I.codeBlockMonacoOptions,Rn(),m.value,In.value,aw.value]})(he),Ne=at.length<=H.length&&(Ye=ve,(Ue=et).length===Ye.length&&Ue.every((nt,ht)=>Object.is(nt,Ye[ht])));var Ue,Ye;const tt=Ne&&wt===te?H.length:Ne?Ym(H.length):0,bt=Ne?Array.from(bn):[];at.length=H.length;for(let nt=tt;nt=0&&ntEt.value);bo=(function(H){let te=!0,he=[0],ve="";function Ne(ht){var kt;const Je=H.nodeHeights[ht];if(Number.isFinite(Je)&&Je>0)return Je;const pt=H.parsedNodes.value[ht],Nt=pt?.type,_t=!!((kt=H.hasCustomParagraphComponent)!=null&&kt.call(H)),Yt=H.estimatedNodeHeights.value[ht],$t=Yt?.height;if(!(function(vn,Ln,Mn){return!!(Mn&&Ln?.kind==="simple-text"&&(vn==="paragraph"||vn==="list_item"||vn==="list"))})(Nt,Yt,_t)&&Number.isFinite($t)&&$t>0)return $t;const pn=Pbe(pt,H.getContainerWidth()||640);return Nt==="heading"||Nt==="paragraph"&&pn<=28&&(function(vn,Ln){if(Ln)return!1;const Mn=vn.children;return!Array.isArray(Mn)||!Mn.length||Mn.every(mq)})(pt,_t)?pn:Math.max(H.averageNodeHeight.value,pn)}function Ue(){var ht;const kt=H.parsedNodes.value.length,Je=H.getPrefixCacheKeyParts().join(":");if(!te&&ve===Je)return he;const pt=new Array(kt+1);pt[0]=0;for(let Nt=0;Nt=((kt=Nt[pt])!=null?kt:0))return pt-1;let _t=0,Yt=pt-1,$t=pt-1;for(;_t<=Yt;){const pn=_t+Yt>>1;((Je=Nt[pn+1])!=null?Je:0)>=ht?($t=pn,Yt=pn-1):_t=pn+1}return $t}function tt(ht,kt){var Je,pt;if(ht>=kt)return 0;if(H.heightEstimationActive.value)return(function(Yt,$t){var pn,vn;const Ln=H.parsedNodes.value.length,Mn=fD(Math.trunc(Yt),0,Ln),Nn=fD(Math.trunc($t),Mn,Ln);if(Mn>=Nn)return 0;const Qn=Ue();return((pn=Qn[Nn])!=null?pn:0)-((vn=Qn[Mn])!=null?vn:0)})(ht,kt);if(H.heightTreeSize.value!==H.parsedNodes.value.length){let Yt=0;for(let $t=ht;$tMn<=0?0:H.fenwickRangeSum(_t,0,Mn)+(Mn-H.fenwickRangeSum(Yt,0,Mn))*Nt;let pn=0,vn=Je.length-1,Ln=Je.length-1;for(;pn<=vn;){const Mn=pn+vn>>1;$t(Mn+1)>=ht?(Ln=Mn,vn=Mn-1):pn=Mn+1}return Ln}let pt=ht;for(let Nt=0;Nt0||ht++}return ht}return{markFallbackHeightPrefixDirty:function(){te=!0},getFallbackNodeHeight:Ne,estimateHeightRange:tt,estimateIndexForOffset:bt,estimateIndexForOffsetFromEnd:function(ht){var kt,Je;const pt=H.parsedNodes.value;if(!pt.length)return 0;if(ht<=0)return Math.max(0,pt.length-1);if(H.heightEstimationActive.value){const _t=(kt=Ue()[pt.length])!=null?kt:0;return Ye(Math.max(0,_t-ht))}if(H.heightTreeSize.value===pt.length){const _t=tt(0,pt.length);return bt(Math.max(0,_t-ht))}let Nt=ht;for(let _t=pt.length-1;_t>=0;_t--){const Yt=(Je=H.nodeHeights[_t])!=null?Je:H.averageNodeHeight.value;if(Nt<=Yt)return _t;Nt-=Yt}return 0},getEstimatedNodeHeightCount:nt,buildVirtualHeightSummary:function(ht){var kt;const Je=H.parsedNodes.value.length;return{totalNodes:Je,measuredCount:H.heightStats.count,estimatedCount:nt(),averageNodeHeight:H.averageNodeHeight.value,topSpacerHeight:ht.topSpacerHeight,bottomSpacerHeight:ht.bottomSpacerHeight,estimatedTotalHeight:tt(0,Je),width:(kt=ht.width)!=null?kt:H.getContainerWidth()}}}})({parsedNodes:ze,nodeHeights:Ho,heightStats:Cs,heightTreeSize:cs,heightSumTree:Yo,heightKnownTree:vc,averageNodeHeight:Xa,heightEstimationActive:oo,estimatedNodeHeights:Fn,getContainerWidth:hi,hasCustomParagraphComponent:()=>!!In.value.paragraph,getPrefixCacheKeyParts:()=>{var H;const te=Lg(ee.value||st("getFallbackHeightPrefix.clientWidth",()=>{var ve;return((ve=F.value)==null?void 0:ve.clientWidth)||0})),he=((H=i.virtualScroll)==null?void 0:H.measurementKey)==null?"":String(i.virtualScroll.measurementKey);return[ze.value.length,Cs.count,Math.round(Cs.total),Math.round(100*Xa.value),he,te,oo.value?1:0,aw.value,K.value,In.value.paragraph?1:0]},fenwickRangeSum:Ve}),qe(()=>ze.value.length,H=>{var te;Ro(),H<=0?Ge():(HEr(te))),H!==cs.value&&ia(H))},{immediate:!0});const uo=D(()=>{if(!An.value)return ze.value.map((ve,Ne)=>({node:ve,index:Ne}));const H=ze.value.length,te=Wo(lo.start,0,H),he=Wo(lo.end,te,H);return ze.value.slice(te,he).map((ve,Ne)=>({node:ve,index:te+Ne}))}),yr=D(()=>An.value?er(0,Math.min(lo.start,ze.value.length)):0),Tl=D(()=>{if(!An.value)return 0;const H=ze.value.length;return er(Math.min(lo.end,H),H)});function nu(){return bo.buildVirtualHeightSummary({topSpacerHeight:yr.value,bottomSpacerHeight:Tl.value,width:qf()})}function bc(){const H=ze.value,te=nu();return Hn(Ht({},te),{probe:{paragraphReady:!!ue.value.paragraph,listItemReady:!!ue.value.listItem,listWrapperOverhead:ue.value.listWrapperOverhead,headingReadyLevels:Object.entries(ue.value.headings).filter(([,he])=>!!he).map(([he])=>Number(he))},nodes:H.map((he,ve)=>{var Ne,Ue,Ye,tt,bt,nt,ht,kt,Je;return{index:ve,type:he.type,estimateKind:(Ue=(Ne=Fn.value[ve])==null?void 0:Ne.kind)!=null?Ue:null,rendererKind:(tt=(Ye=Fn.value[ve])==null?void 0:Ye.rendererKind)!=null?tt:null,estimatedHeight:(nt=(bt=Fn.value[ve])==null?void 0:bt.height)!=null?nt:null,estimatedContentHeight:(kt=(ht=Fn.value[ve])==null?void 0:ht.contentHeight)!=null?kt:null,measuredHeight:(Je=Ho[ve])!=null?Je:null}})})}function wc(){return i.indexKey!=null?String(i.indexKey):Sn.value?`virtual-${qo()}`:"markdown-renderer"}function z_(H){const te=String(H),he=`${wc()}-`;if(!te.startsWith(he))return null;const ve=te.slice(he.length).match(/^(\d+)(?:$|-)/);if(!ve)return null;const Ne=Number(ve[1]);return!Number.isInteger(Ne)||Ne<0||Ne>=ze.value.length?null:Ne}function qo(){var H,te,he;const ve=(H=i.virtualScroll)==null?void 0:H.sessionKey;return String(ve!=null&&ve!==""?ve:(he=(te=i.indexKey)!=null?te:I.customId)!=null?he:Tt)}function Ts(){var H;const te=(H=i.virtualScroll)==null?void 0:H.threadKey;return te==null||te===""?void 0:String(te)}const UQ=D(()=>{var H,te,he;return(he=Ts())!=null?he:String((te=(H=i.indexKey)!=null?H:I.customId)!=null?te:Tt)});function u3(H){var te;return(H??"")===((te=Ts())!=null?te:"")}function Cc(){var H,te,he;return te=(H=i.virtualScroll)==null?void 0:H.measurementKey,he=(function(){const ve=m.value;return(function(Ne){var Ue,Ye;const tt=Ne.renderer,bt=tt==="monaco"?Ne.codeBlockMonacoOptions:void 0,nt=Ne.codeBlockProps,ht=tt==="shiki";return[Ne.isDark?"dark":"light",tt==="monaco"?"code-rich":tt==="pre"?"code-pre":"code-shiki",Ne.codeBlockStream===!1?"code-static":"code-stream",br(Ne.codeBlockMinWidth),br(Ne.codeBlockMaxWidth),...ht?[Mye((Ue=nt?.themes)!=null?Ue:Ne.themes,(Ye=nt?.langs)!=null?Ye:Ne.langs)]:[],br(bt?.fontSize),br(bt?.lineHeight),br(bt?.fontFamily),br(bt?.tabSize),br(bt?.MAX_HEIGHT),br(bt?.wordWrap),br(bt?.wrappingIndent),br(bt?.padding),br(nt?.showHeader),br(nt?.showCopyButton),br(nt?.showExpandButton),br(nt?.showPreviewButton),br(nt?.showCollapseButton),br(nt?.showFontSizeButtons)].join("\0")})({renderer:ve,isDark:I.isDark,codeBlockStream:I.codeBlockStream,codeBlockMinWidth:I.codeBlockMinWidth,codeBlockMaxWidth:I.codeBlockMaxWidth,codeBlockMonacoOptions:ve==="monaco"?I.codeBlockMonacoOptions:void 0,codeBlockProps:I.codeBlockProps,themes:ve==="shiki"?I.themes:void 0,langs:ve==="shiki"?I.langs:void 0})})(),[te==null?"":String(te),he].join("\0")}function qf(){return hi()}const _2=D(()=>Lg(qf())),sa=D(()=>[Cc(),_2.value].join("\0")),VQ=D(()=>{var H;return Sn.value?["virtual",(H=Ts())!=null?H:"",qo(),sa.value].join("\0"):i.indexKey});function Mp(){Wf.value+=1}function c3(H){return!(!H||!Number.isInteger(H.index)||H.index<0||H.index>=ze.value.length||H.sessionKey!==qo()||H.threadKey!==Ts()||H.layoutEpochKey!==sa.value)}function j_(H){const te=String(H),he=ul.get(te);return he?c3(he)?he.index:null:z_(te)}function H_(H="async-node"){(vr.size||ul.size)&&(vr.clear(),ul.clear(),Mp(),Co(H))}const Tp=rn(cA,null),d3={reportHeight(H,te){if(!Bn.value)return;const he=j_(H);if(he==null)return;const ve=ao.get(he);if(!ve)return;const Ne=Number(te),Ue=Qt(he,ve);(function(Ye,tt,bt={}){me(()=>Bt(Ye,tt,bt))})(he,Number.isFinite(Ne)&&Ne>0?Math.max(Ne,Ue||0):Ue)},markPending(H){if(!Bn.value)return;const te=z_(H);te!=null&&(function(he,ve){var Ne;const Ue=ul.get(he);if(Ue&&c3(Ue))return vr.set(he,Math.max(0,(Ne=vr.get(he))!=null?Ne:0)+1),Mp(),void Co("async-node");vr.set(he,1),ul.set(he,(function(Ye){return{index:Ye,sessionKey:qo(),threadKey:Ts(),layoutEpochKey:sa.value}})(ve)),Mp(),Co("async-node")})(String(H),te)},markSettled(H){if(!Bn.value)return;const te=String(H),he=j_(H);(he!=null||(function(ve){return vr.has(String(ve))})(te))&&(function(ve){var Ne;const Ue=(Ne=vr.get(ve))!=null?Ne:0;return!(Ue<=0||(Ue<=1?(vr.delete(ve),ul.delete(ve)):vr.set(ve,Ue-1),Mp(),Ue===1&&Co("async-node"),0))})(te)&&he!=null&&Ac()}};function KQ(){let H=0;for(const te of ao.values())H+=st("getVisibleDomHeight.offsetHeight",()=>{var he;return(he=te?.offsetHeight)!=null?he:0});return Math.ceil(Math.max(0,H))}ui(cA,{reportHeight(H,te){d3.reportHeight(H,te),Tp?.reportHeight(H,te)},markPending(H){d3.markPending(H),Tp?.markPending(H)},markSettled(H){d3.markSettled(H),Tp?.markSettled(H)}});let f3,h3=null,Ep=null;function I2(H){return H!==!1&&H!=null&&H!==""}function W_(){return An.value?(function(){if(!An.value)return!0;const H=ze.value.length,te=Wo(lo.start,0,H),he=Wo(lo.end,te,H);if(te>=he)return!0;for(let ve=te;ve=hd.value}function p3(){return Oe.value===!0&&!ct.value&&Lu.value===0&&vi.size===0&&es.size===0&&nr==null&&W_()}function q_(){var H,te;if(((H=i.virtualScroll)==null?void 0:H.settleMode)!=="manual"||h3===qo()&&f3===Ts())return!0;const he=(te=i.virtualScroll)==null?void 0:te.settledToken;return!!I2(he)&&Ep===fg(he)}function m3(){return p3()&&q_()}function ZQ(H,te){return te.totalNodes<=0?H==="final"?"final":"estimate":te.measuredCount>=te.totalNodes?H==="final"?"final":"measured":te.measuredCount>0||te.estimatedCount>0?"mixed":"estimate"}function Uf(H="manual",te){const he=nu(),ve=(function(Ne){return Ne||(Oe.value!==!0?ze.value.length>0?"streaming":"estimating":!W_()||es.size>0||nr!=null?"measuring":m3()?"settled":"settling")})(te);return{sessionKey:qo(),threadKey:Ts(),phase:ve,nodeCount:he.totalNodes,liveRange:{start:lo.start,end:lo.end},renderedCount:us.value,measuredCount:he.measuredCount,estimatedCount:he.estimatedCount,averageNodeHeight:he.averageNodeHeight,topSpacerHeight:he.topSpacerHeight,bottomSpacerHeight:he.bottomSpacerHeight,visibleDomHeight:KQ(),totalHeight:U_(),width:he.width,final:Oe.value===!0,stable:m3(),confidence:ZQ(ve,he),reason:H}}function Xm(){const H=ko.value||le(),te=F.value;if(!H||!te)return null;const he=H.ownerDocument||te.ownerDocument||document,ve=H===he.documentElement||H===he.body||H===he.scrollingElement,Ne=st("getScrollBox.scrollTop",()=>_e(H,he,ve)),Ue=st("getScrollBox.scrollHeight",()=>{var tt,bt,nt,ht,kt;return ve?Math.max((bt=(tt=he.documentElement)==null?void 0:tt.scrollHeight)!=null?bt:0,(ht=(nt=he.body)==null?void 0:nt.scrollHeight)!=null?ht:0,(kt=H.scrollHeight)!=null?kt:0):H.scrollHeight}),Ye=st("getScrollBox.clientHeight",()=>{var tt;return ve?((tt=he.documentElement)==null?void 0:tt.clientHeight)||H.clientHeight||0:H.clientHeight});return{root:H,doc:he,isViewportRoot:ve,scrollTop:Ne,scrollHeight:Ue,clientHeight:Ye}}function U_(){const H=ze.value.length,te=Math.max(0,er(0,H)),he=st("getRendererLogicalHeight.offsetHeight",()=>{var Ne,Ue;return(Ue=(Ne=F.value)==null?void 0:Ne.offsetHeight)!=null?Ue:0}),ve=Math.max(0,he>0?he:st("getRendererLogicalHeight.scrollHeight",()=>{var Ne,Ue;return(Ue=(Ne=F.value)==null?void 0:Ne.scrollHeight)!=null?Ue:0}));return H<=0?Math.ceil(he):An.value?te>0?Math.max(1,Math.ceil(te),(function(){let Ne=yr.value+Tl.value;for(const Ue of Qi.values())Ue&&(Ne+=Math.max(0,st("getVirtualizedDomLogicalHeight.offsetHeight",()=>Ue.offsetHeight||0)));return Math.ceil(Math.max(0,Ne))})(),(function(Ne,Ue){return Ne<=0||Ue<=0?0:Ue<=Ne+Math.max(512,.05*Ne)?Math.ceil(Ue):0})(te,ve)):Math.max(1,Math.ceil(ve)):Bn.value?te>0||Cs.count>0||bo.getEstimatedNodeHeightCount()>0?(pr.value&&us.value,Math.max(1,Math.ceil(ve),Math.ceil(te))):Math.ceil(ve):Math.max(1,Math.ceil(ve),Math.ceil(te))}function V_(H){const te=F.value;if(!te)return null;const he=st("getRendererBottomDistanceFromViewport.getBoundingClientRect",()=>te.getBoundingClientRect());return(function(Ne){return Ne.isViewportRoot?Ne.clientHeight:st("getViewportBottomInRoot.getBoundingClientRect",()=>Ne.root.getBoundingClientRect().bottom)})(H)-he.bottom}function GQ(H={}){const te=H.requireViewport!==!1,he=(function(Ue=64){const Ye=Xm(),tt=F.value;if(!Ye||!tt)return!1;const bt=(function(ht){if(ht.isViewportRoot)return{top:0,bottom:ht.clientHeight};const kt=st("getVirtualViewportRect.getBoundingClientRect",()=>ht.root.getBoundingClientRect());return{top:kt.top,bottom:kt.bottom}})(Ye),nt=st("isRendererNearVirtualViewport.getBoundingClientRect",()=>tt.getBoundingClientRect());return nt.bottom>=bt.top-Ue&&nt.top<=bt.bottom+Ue})();if(te&&!he)return null;const ve=(function(){const Ue=Xm(),Ye=F.value;if(!Ue||!Ye||Math.max(0,Ue.scrollHeight-Ue.scrollTop-Ue.clientHeight)>64)return null;const tt=V_(Ue);return tt==null?null:tt>=-8&&tt<=160?{type:"bottom",distanceFromBottomPx:Math.max(0,tt)}:null})();if(ve)return{anchor:ve,captured:!0};const Ne=Gr();if(Ne)return{anchor:{type:"node",nodeIndex:Ne.nodeIndex,offsetWithinNodePx:Ne.offsetWithinNodePx},captured:he};if(H.allowFallback===!0){const Ue=(function(){const Ye=ze.value.length;return Ye<=0?null:{type:"node",nodeIndex:Wo(Xo.value,0,Math.max(0,Ye-1)),offsetWithinNodePx:0}})();return Ue?{anchor:Ue,captured:!1}:null}return null}function g3(H){let te=2166136261;for(let he=0;he>>0).toString(36)}function QQ(H,te){let he=H;for(let ve=0;ve8192?`${ve.slice(0,8192)}...${ve.length}`:ve;return`${ve.length}:${g3(Ne)}`})(H)}`;if(typeof H=="function")return"fn";if(typeof H!="object")return typeof H;if(te.has(H))return"cycle";if(he>=6)return"max-depth";te.add(H);try{if(Array.isArray(H)){if(H.length<=160){const nt=[];for(let ht=0;ht=tt&&Ye.push(ht)}return[`a:${H.length}`,`h=${Ue.join(",")}`,`t=${Ye.join(",")}`,`all=${(bt>>>0).toString(36)}`].join(":")}const ve=H,Ne=Object.keys(ve).filter(Ue=>{const Ye=ve[Ue];return Ue!=="parent"&&Ue!=="el"&&Ue!=="component"&&(Ye==null||typeof Ye=="string"||typeof Ye=="number"||typeof Ye=="boolean"||YQ.has(Ue))}).sort();return`o:${Ne.length}:${Ne.map(Ue=>`${Ue}=${M2(ve[Ue],te,he+1)}`).join(";")}`}finally{te.delete(H)}}let v3=-1,y3="",Vf=[2166136261];function eg(H){const te=ze.value[H];return te?g3(M2(te)):""}function JQ(H,te){let he=H;for(let ve=0;ve>>0}function k3(){var H,te;const he=K.value;if(v3===he)return y3;const ve=ze.value.length;let Ne=Ym(ve);(v3!==he-1||Ne>ve||Vf.length>>0).toString(36),v3=he,y3}function Lp(H,te={}){var he;const ve=te.includeHeightCache===!0,Ne=(he=te.includeContentHash)!=null?he:ve,Ue=ve?(function(tt){const bt=(function(){var _t,Yt;const $t=Number((Yt=(_t=i.virtualScroll)==null?void 0:_t.heightCacheLimit)!=null?Yt:5e3);return!Number.isFinite($t)||$t<=0?Number.POSITIVE_INFINITY:Math.max(1,Math.trunc($t))})();if(!Number.isFinite(bt)||tt.length<=bt)return tt;const nt=new Map,ht=_t=>{!_t||nt.size>=bt||nt.set(_t.index,_t)},kt=ze.value.length,Je=Wo(lo.start-2*Lo.value,0,kt),pt=Wo(lo.end+2*Lo.value,Je,kt);for(const _t of tt)_t.index>=Je&&_t.index=0&&nt.size_t.index-Yt.index).slice(0,bt)})(we().map(tt=>{var bt;const nt=ze.value[tt.index];return nt?Hn(Ht({},tt),{nodeType:String((bt=nt.type)!=null?bt:""),signature:eg(tt.index)}):null}).filter(tt=>!!tt)):[],Ye=GQ({allowFallback:te.allowAnchorFallback===!0,requireViewport:te.requireViewport});return Ye||Ue.length||te.includeEmptyState===!0?Hn(Ht({sessionKey:H.sessionKey,threadKey:H.threadKey},Ye?{anchor:Ye.anchor,anchorCaptured:Ye.captured}:{anchorCaptured:!1}),{metrics:H,width:H.width,contentHash:Ne?k3():void 0,measurementKey:Cc()||void 0,heightCache:Ue.length?Ue:void 0}):null}function b3(H){var te,he;const ve=Xm();if(!ve)return;const Ne=(function(tt){const bt=F.value;if(!bt)return null;const nt=ge(bt,tt.root),ht=ze.value.length,kt=st("getRendererBottomOffsetWithinRoot.offsetHeight",()=>bt.offsetHeight||0),Je=Math.max(0,kt>0?kt:ht>0?st("getRendererBottomOffsetWithinRoot.scrollHeight",()=>bt.scrollHeight||0):0),pt=U_();return nt+Math.max(Je,pt)})(ve);if(Ne==null)return;const Ue=Math.max(0,H.distanceFromBottomPx),Ye=Math.max(0,Ne-ve.clientHeight-Ue);(function(tt){wo=sg()+120,Fo=tt})(Ye),ve.isViewportRoot?(he=(te=ve.doc.defaultView)==null?void 0:te.scrollTo)==null||he.call(te,0,Ye):uD(ve.root,ve.doc,Ye,{isReverseFlexScrollRoot:se,getNormalizedScrollTop:_e})}const w3=[];function K_(){if(Z)for(Xs!=null&&(Ni?.(Xs),Xs=null);w3.length;){const H=w3.pop();H!=null&&window.clearTimeout(H)}}function Np(H){const te=!!Ci.value;Ci.value=null,wo=0,Fo=null,K_(),te&&H&&Co(H)}function Dp(){if(!Ci.value||!Z||Xs!=null)return;const H=()=>{Xs=null;const te=Ci.value;te&&b3(te)};Xs=Wi?Wi(H):null,Xs==null&&H()}function Z_(H,te={}){const he=ze.value.length;return he<=0?[]:H.filter(ve=>!(!Number.isInteger(ve.index)||ve.index<0||ve.index>=he)&&!(!Number.isFinite(ve.height)||ve.height<=0)&&!(te.requireSignature&&!ve.signature)&&!(te.requireCompatibilityMetadata&&!ve.nodeType&&!ve.signature)&&(function(Ne){var Ue;const Ye=ze.value[Ne.index];return!(!Ye||Ne.nodeType&&Ne.nodeType!==String((Ue=Ye.type)!=null?Ue:"")||Ne.signature&&Ne.signature!==eg(Ne.index))})(ve))}function G_(H){const te=Lg(qf()),he=Lg(H);return te!==-1&&he!==-1&&te===he}function C3(H){var te;const he=Number(H?.width);if(Number.isFinite(he)&&he>0)return he;const ve=Number((te=H?.metrics)==null?void 0:te.width);return Number.isFinite(ve)&&ve>0?ve:null}function Q_(H){var te;return H.sessionKey===qo()&&!!u3(H.threadKey)&&((te=H.measurementKey)!=null?te:"")===Cc()&&!!G_(C3(H))&&!!(function(he){const ve=he.heightCache;return!!ve?.length&&(Y_(he)?ve.some(Ne=>!!(Ne.nodeType||Ne.signature)):ve.some(Ne=>!!Ne.signature))})(H)}function Y_(H){return!!(H.contentHash&&H.contentHash===k3())}function XQ(H){return!Y_(H)}let Kf=null,Zf=null,T2=null,tg=null,ng=null;function A3(H){var te;const he=H.map(Ne=>{var Ue,Ye;return[Ne.index,Math.round(10*Ne.height),(Ue=Ne.nodeType)!=null?Ue:"",(Ye=Ne.signature)!=null?Ye:""].join("")}).join(""),ve=Lg(qf());return[(te=Ts())!=null?te:"",qo(),Cc(),ze.value.length,ve,H.length,g3(he)].join(":")}function J_(H=(te=>(te=i.virtualScroll)==null?void 0:te.heightCache)()){if(!Bn.value||!H?.length||ze.value.length<=0||!G_((te=i.virtualScroll)==null?void 0:te.heightCacheWidth))return!1;var te;const he=Z_(H,{requireSignature:!0});if(!he.length)return!1;const ve=A3(he);return ve===Kf?(Zf="standalone",!0):(mn(he,{mode:"merge"}),Ro(),Kf=ve,Zf="standalone",lg(),Co("restore"),!0)}function x3(H,te={}){var he,ve,Ne;if(!Bn.value||!H||H.sessionKey!==qo()||!u3(H.threadKey)||ze.value.length<=0)return!1;const Ue=!!((he=H.heightCache)!=null&&he.length)&&!E2(),Ye=!H.anchor||H.anchorCaptured===!1&&te.allowUncapturedAnchor!==!0?null:H.anchor,tt=te.restoreAnchor===!0&&!!Ye&&!E2()&&Number(C3(H))>0;let bt=!1;if((ve=H.heightCache)!=null&&ve.length&&Q_(H)){const ht=Z_(H.heightCache,{requireCompatibilityMetadata:!H.contentHash,requireSignature:XQ(H)});ht.length&&(mn(ht,{mode:"merge"}),Ro(),Kf=A3(ht),Zf="restore",lg(),bt=!0)}if(Ue||tt)return!1;if(!te.restoreAnchor||!Ye)return bt&&Co("restore"),!0;const nt=(function(ht,kt){var Je;const pt=ht.anchor,Nt=pt?pt.type==="bottom"?`bottom:${Math.round(pt.distanceFromBottomPx)}`:`node:${pt.nodeIndex}:${Math.round(pt.offsetWithinNodePx)}`:"none";return[(Je=Ts())!=null?Je:"",qo(),Cc(),_2.value,kt,Nt].join(":")})(H,(Ne=te.restoreToken)!=null?Ne:"imperative");return T2===nt?(bt&&Co("restore"),!0):(T2=nt,(function(ht){const kt=()=>{if(ht.type==="node")return Np(),void Tr({nodeIndex:ht.nodeIndex,offsetWithinNodePx:ht.offsetWithinNodePx});if(Il(),ws.value=null,Ci.value=ht,K_(),b3(ht),Z)for(const Je of[0,120,280,480])w3.push(window.setTimeout(()=>{const pt=Ci.value;pt&&b3(pt)},Je))};(function(Je){if(!An.value)return!1;const pt=ze.value.length;return!(pt<=0||(Xo.value=Je.type==="node"?Wo(Je.nodeIndex,0,pt-1):pt-1,Oo(),0))})(ht)?mt(kt):kt()})(Ye),Co("restore"),!0)}function E2(){const H=qf();return Number.isFinite(H)&&H>0}function X_(H){var te;return H.sessionKey===qo()&&!!u3(H.threadKey)&&(ze.value.length<=0||!(!((te=H.heightCache)!=null&&te.length)||E2())||!(!(H.anchor&&Number(C3(H))>0)||E2()))}function S3(){Yi.clear();for(const H of Object.keys(Ho)){const te=Number(H);Number.isInteger(te)&&te>=0&&te{let te=!1,he=null;const ve=()=>{te||(te=!0,he!=null&&window.clearTimeout(he),H())};if(Wi)return Wi(ve),void(he=window.setTimeout(ve,50));he=window.setTimeout(ve,0)})}function _3(H,te=Ts(),he=sa.value){return qo()===H&&Ts()===te&&sa.value===he}function I3(){return xo(this,arguments,function*(H={}){var te,he,ve,Ne,Ue;const Ye=qo(),tt=Ts(),bt=sa.value,nt=(te=H.frames)!=null?te:2,ht=(he=H.timeoutMs)!=null?he:120,kt=(ve=H.reason)!=null?ve:"manual",Je=H.expectedSettledTokenKey,pt=H.flushPendingTimers===!0,Nt=Uf(kt),_t=()=>Hn(Ht({},Nt),{phase:Nt.final?"settling":Nt.phase,stable:!1,confidence:Nt.confidence==="final"?"mixed":Nt.confidence,reason:kt}),Yt=()=>_3(Ye,tt,bt)&&(Je==null||rg()===Je);for(let Ln=0;Lnwindow.setTimeout(Mn,Ln))})(ht),!Yt()||(pt&&vt(),Ac(),ig(),!Yt()))return _t();const $t=p3();$t&&(h3=Ye,f3=tt,((Ne=i.virtualScroll)==null?void 0:Ne.settleMode)==="manual"&&Je!=null&&I2((Ue=i.virtualScroll)==null?void 0:Ue.settledToken)&&rg()===Je&&(Ep=fg(i.virtualScroll.settledToken)));const pn=Yt()&&$t&&q_(),vn=Uf(kt,pn?"final":void 0);return N3(vn,!0),vn})}let M3="content",Gf=null,Qf=null,T3=0,og=null,Fp=null,E3=null,L3=null;function sg(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function tI(H){var te,he;const ve=og;if(!ve)return!0;const Ne=(he=(te=i.virtualScroll)==null?void 0:te.heightDiffThresholdPx)!=null?he:1;return Math.abs(H.totalHeight-ve.totalHeight)>Ne||H.sessionKey!==ve.sessionKey||H.phase!==ve.phase||H.stable!==ve.stable||H.final!==ve.final||H.threadKey!==ve.threadKey||H.nodeCount!==ve.nodeCount||H.measuredCount!==ve.measuredCount||H.width!==ve.width}function rg(H=(te=>(te=i.virtualScroll)==null?void 0:te.settledToken)()){return br(H)}function nI(H,te){var he,ve;return[H,te.sessionKey,(he=te.threadKey)!=null?he:"",Cc(),k3(),br((ve=i.virtualScroll)==null?void 0:ve.settledToken),Math.round(te.totalHeight),Math.round(te.width)].join("\0")}function lg(){E3=null,L3=null,Fp=null}function eY(H){const te=H.heightCache;return te?.length?A3(te):""}function ag(H){var te,he,ve;const Ne=H.metrics,Ue=H.anchor?(Ye=H.anchor).type==="bottom"?`bottom:${Math.round(Ye.distanceFromBottomPx)}`:`node:${Ye.nodeIndex}:${Math.round(Ye.offsetWithinNodePx)}`:"none";var Ye;return[H.sessionKey,(te=H.threadKey)!=null?te:"",(he=H.measurementKey)!=null?he:Cc(),(ve=H.contentHash)!=null?ve:"",eY(H),Ue,H.anchorCaptured?1:0,Ne.liveRange.start,Ne.liveRange.end,Ne.renderedCount,Ne.nodeCount,Math.round(Ne.totalHeight),Math.round(Ne.width),Ne.phase,Ne.stable?1:0].join("\0")}function N3(H,te=!1){if(!Bn.value||(function(Ye=!1){return!Ye&&Sn.value&&!io.value})(te))return;const he=te||tI(H),ve=(function(Ye,tt=!1){return tt||Ye.stable||Ye.phase==="final"?{state:Lp(Ye,{includeHeightCache:!0})}:{state:Lp(Ye)}})(H,te),Ne=ve.state,Ue=!!(Ne&&(he||(function(Ye,tt=!1){return!!tt||ag(Ye)!==Fp})(Ne,te)));if(he&&(R(H),og=H,T3=sg()),Ne&&Ue&&(W(Ne),Ne.anchor&&z(Ne.anchor),Fp=ag(Ne)),H.stable){const Ye=nI("settled",H);if(Ye!==E3){E3=Ye;const tt=Lp(H,{includeHeightCache:!0});tt&&(W(tt),Fp=ag(tt)),(function(bt){o("render-settled",bt)})(H)}}if(H.phase==="final"){const Ye=nI("final",H);if(Ye!==L3){L3=Ye;const tt=Lp(H,{includeHeightCache:!0});tt&&(W(tt),Fp=ag(tt)),(function(bt){o("render-final",bt)})(H)}}}function D3(){Gf!=null&&(Ni?.(Gf),Gf=null),Qf!=null&&Z&&(window.clearTimeout(Qf),Qf=null)}function iI(){Gf=null,Qf=null,(function(H){if(es.size>0||nr!=null)return!0;switch(H){case"node-resize":case"async-node":case"resize":case"restore":case"final":case"manual":return!0;default:return!1}})(M3)&&(Ac(),ig()),N3(Uf(M3))}function Co(H){var te,he;if(!Bn.value||(M3=H,Gf!=null||Qf!=null))return;const ve=Math.max(0,(he=(te=i.virtualScroll)==null?void 0:te.emitIntervalMs)!=null?he:32),Ne=Math.max(0,ve-(sg()-T3)),Ue=()=>{Qf=null,Gf=Wi?Wi(iI):null,Gf==null&&iI()};Z&&Ne>0?Qf=window.setTimeout(Ue,Ne):Ue()}function oI(){Kr.value+=1}function L2(H){if(pr.value&&H>=us.value){const te=ze.value[H],he=xe.value===!0&&Oe.value!==!0&&H>=ze.value.length-2,ve=te?.type==="code_block"||te?.type==="image"||te?.type==="mermaid"||te?.type==="infographic";if(!he||ve)return!1}return!on.value||H=Me.value&&(V.value||(V.value=!0,xp()),!ii.value||!so))return Rp(H),void(te&&tu(H,!0));if(H{if(x2.delete(Ue),!on.value||Ms.value.has(Ue))return;const bt=Qi.get(Ue);if(!bt)return;const nt=le(bt),ht=bt.ownerDocument||document,kt=ht.defaultView||window,Je=!nt||nt===ht.documentElement||nt===ht.body,pt=!Je&&nt?st("nodeVisibilityFallback.root.getBoundingClientRect",()=>nt.getBoundingClientRect()):null,Nt=Je?0:pt.top,_t=Je?st("nodeVisibilityFallback.clientHeight",()=>{var $t,pn;return(pn=($t=kt.innerHeight)!=null?$t:nt?.clientHeight)!=null?pn:0}):pt.bottom,Yt=st("nodeVisibilityFallback.node.getBoundingClientRect",()=>bt.getBoundingClientRect());Yt.bottom>=Nt-500&&Yt.top<=_t+500&&tu(Ue,!0)},1800+Ye);x2.set(Ue,tt)})(H);let Ne=null;Ne=qe(()=>ve.isVisible.value,Ue=>{if(Ue){Ap(H),tu(H,!0),Ne?.(),Nu.delete(H),oa.get(H)===ve&&oa.delete(H);try{ve.destroy()}catch{}}},{immediate:!0}),Nu.set(H,Ne),An.value&&ai()}function F3(){nr=null,me(()=>{let H=!1;for(const[te,he]of es)es.delete(te),ao.get(te)===he.el&&Lr.get(te)===he.version&&(H=Bt(te,he.height,{allowShrink:he.allowShrink})||H);return H})}function Op(){nr!=null&&(Ni?.(nr),nr=null),es.clear()}function D2(H,te){(function(he,ve,Ne){var Ue;if(!Number.isFinite(Ne)||Ne<=0||ao.get(he)!==ve)return;const Ye=Lr.get(he);if(Ye==null)return;const tt=ze.value[he],bt=ct.value&&Oe.value!==!0&&!((Ue=i.nodes)!=null&&Ue.length)&&he>=ze.value.length-2,nt=!(tt?.loading===!0||bt),ht=es.get(he),kt=ht?ht.allowShrink&&nt:nt,Je=ht&&!kt?Math.max(ht.height,Ne):Ne;es.set(he,{height:Je,allowShrink:kt,version:Ye,el:ve}),nr==null&&(nr=Wi?Wi(F3):null,nr==null&&F3())})(H,te,Qt(H,te))}function Ac(){for(const[H,te]of ao)te&&D2(H,te)}function sI(){po?.disconnect(),po=null,Ur.clear()}function R3(){for(;eu.length;)We(eu.pop())}qe(io,H=>{H&&Co("content")},{flush:"post"}),t({getVirtualMetrics:Uf,captureVirtualState:function(H={}){var te;return Lp(Uf("manual"),{includeHeightCache:!0,includeContentHash:!0,allowAnchorFallback:H.allowFallbackAnchor===!0,requireViewport:H.requireViewport===!0,includeEmptyState:(te=H.includeEmptyState)==null||te})},restoreVirtualState:function(H,te={}){const he=te.restoreAnchor===!0,ve=te.restoreToken==null?"imperative":String(te.restoreToken);tg=H,ng={restoreAnchor:he,restoreToken:ve,allowUncapturedAnchor:te.allowUncapturedAnchor===!0},!x3(H,{restoreAnchor:he,restoreToken:ve,allowUncapturedAnchor:te.allowUncapturedAnchor===!0})&&X_(H)||(tg=null,ng=null)},forceMeasure:function(H="manual"){return xo(this,null,function*(){yield mt(),yield eI(),Ac(),ig(),yield mt();const te=Uf(H);return N3(te,!0),te})},settle:I3,scrollToNode:function(H,te="start"){Np(),Il();const he=ze.value.length;if(he<=0)return;const ve=Wo(H,0,he-1),Ne=()=>{var Ue;const Ye=Eu({nodeIndex:ve,offsetWithinNodePx:0}),tt=Is(ve),bt=Xm(),nt=(Ue=bt?.clientHeight)!=null?Ue:0,ht=Mr();let kt=Ye;if(te==="center")kt=Ye-nt/2+tt/2;else if(te==="end")kt=Ye-nt+tt;else if(te==="nearest"&&ht!=null){if(Ye>=ht&&Ye+tt<=ht+nt)return;kt=YeQs.value,H=>{if(!H){sI();for(const te of tr.values())for(const he of te)We(he);tr.clear(),Lr.clear(),R3(),Op()}},{immediate:!0}),qe(Oe,H=>{H&&(function(){if(Z&&Oe.value&&ao.size){R3();for(const te of[80,240,640]){const he=Se(te,()=>{for(const[ve,Ne]of ao)Ne&&D2(ve,Ne)},"final");he!=null&&eu.push(he)}}})(),Co(H?"final":"content")});const tY=cD(()=>Co("content"),16),nY=cD(()=>Co("batch"),16);qe([()=>ze.value.length,()=>us.value],()=>{Ci.value&&Dp(),tY()},{flush:"post",immediate:!0}),qe([()=>lo.start,()=>lo.end],()=>{nY()},{flush:"post"});const{cleanupBatchScheduler:iY}=(function(H){const{props:te,isClient:he,isTestEnv:ve,parsedNodesIdentity:Ne,parsedNodeCount:Ue,desiredRenderedCount:Ye,datasetKey:tt,batchingEnabled:bt,incrementalRenderingActive:nt,resolvedBatchSize:ht,resolvedInitialBatch:kt,renderedCount:Je,adaptiveBatchSize:pt,previousRenderContext:Nt,previousBatchConfig:_t,requestFrame:Yt,cancelFrame:$t,hasIdleCallback:pn,cleanupNodeVisibility:vn,onDatasetKeyChanged:Ln,onDatasetChanged:Mn}=H;let Nn=null,Qn="raf",Jn=null,Xi=0,Nr=!1,kr=!1;const iu=new Set,Du=new Set;function vg(){if(he){Nn!=null&&(Qn==="raf"&&$t?$t(Nn):Qn==="idle"&&typeof window.cancelIdleCallback=="function"?window.cancelIdleCallback(Nn):Qn==="timeout"&&window.clearTimeout(Nn),Nn=null),Xi+=1;for(const Qr of iu)$t&&$t(Qr);for(const Qr of Du)window.clearTimeout(Qr);iu.clear(),Du.clear(),Jn=null,Nr=!1,kr=!1}}function H2(){return typeof performance<"u"?performance.now():Date.now()}function AI(Qr){(function(xc){var md;if(!nt.value)return;const Sc=Math.max(2,(md=te.renderBatchBudgetMs)!=null?md:6),_c=Math.max(1,ht.value||1),ou=Math.max(1,Math.floor(_c/4));xc>1.5*Sc?pt.value=Math.max(ou,Math.floor(.8*pt.value)):xc<.6*Sc&&pt.value<_c&&(pt.value=Math.min(_c,Math.ceil(1.2*pt.value)))})(Qr),Nr=!1;const Ll=kr||Je.value=Sc)return;const _c=Math.max(1,Qr),ou=()=>{const Bp=H2();Nn=null;const yg=Jn??_c;Jn=null;const zp=H2();Je.value=Math.min(Sc,Je.value+yg),vn(Je.value),(function(H3,W2){if(!he)return void AI(W2);Nr=!0;const II=++Xi;mt().then(()=>{var MI;if(II!==Xi)return;const xY=H2(),SY=Math.max(W2,xY-H3),TI=()=>{II===Xi&&AI(SY)};if(Yt){let Jf=null,jp=null,LI=!1;const NI=()=>{LI||(LI=!0,Jf!==null&&(iu.delete(Jf),Jf=null),jp!==null&&(Du.delete(jp),window.clearTimeout(jp),jp=null),TI())};return Jf=Yt(()=>{NI()}),iu.add(Jf),jp=window.setTimeout(()=>{Jf!==null&&$t&&$t(Jf),NI()},Math.max(32,(MI=te.renderBatchIdleTimeoutMs)!=null?MI:120)),void Du.add(jp)}const EI=window.setTimeout(()=>{Du.delete(EI),TI()},0);Du.add(EI)})})(Bp,H2()-zp)};if(!he||Ll.immediate)return void ou();const gd=Math.max(0,(xc=te.renderBatchDelay)!=null?xc:16);if(Jn=Jn!=null?Math.max(Jn,_c):_c,Nn==null){if(!ve&&pn&&window.requestIdleCallback){const Bp=Math.max(0,(md=te.renderBatchIdleTimeoutMs)!=null?md:120);return Qn="idle",void(Nn=window.requestIdleCallback(()=>ou(),{timeout:Bp}))}if(Yt&&!ve)return Qn="raf",void(Nn=Yt(()=>{gd===0?ou():(Qn="timeout",Nn=window.setTimeout(()=>ou(),gd))}));Qn="timeout",Nn=window.setTimeout(()=>ou(),gd)}}function SI(Qr,Ll={}){Nr?kr=!0:Qr==null?_I():xI(Qr,Ll)}function _I(){nt.value&&xI(bt.value?Math.max(1,Math.round(pt.value)):Math.max(1,ht.value))}return qe([Ne,Ue,tt,nt,ht,kt,()=>te.renderBatchDelay],()=>{var Qr;const Ll=Ue.value,xc=Nt.value,md=tt.value,Sc=!Object.is(md,xc.key),_c=Ll!==xc.total,ou=Sc||_c;Nt.value={key:md,total:Ll};const gd=_t.value,Bp=(Qr=te.renderBatchDelay)!=null?Qr:16,yg=gd.batchSize!==ht.value||gd.initial!==kt.value||gd.delay!==Bp||gd.enabled!==nt.value;_t.value={batchSize:ht.value,initial:kt.value,delay:Bp,enabled:nt.value},Sc&&Ln(Ll),(ou||yg||!nt.value)&&vg(),(ou||yg)&&(pt.value=Math.max(1,ht.value||1)),ou&&Mn();const zp=Ye.value;if(!Ll)return Je.value=0,void vn(0);if(!nt.value)return Je.value=zp,void vn(Je.value);const H3=Sc||xc.total===0;Je.value=H3||yg?Math.min(zp,kt.value):Math.min(Je.value,zp);const W2=Math.max(1,kt.value||ht.value||Ll);Je.value{nt.value&&(typeof Ll=="number"&&Qr<=Ll||Qr>Je.value&&SI())}),{cleanupBatchScheduler:vg}})({props:I,isClient:Z,isTestEnv:No,parsedNodesIdentity:Dt,parsedNodeCount:wi,desiredRenderedCount:hd,datasetKey:VQ,batchingEnabled:na,incrementalRenderingActive:pr,resolvedBatchSize:Ir,resolvedInitialBatch:Js,renderedCount:us,adaptiveBatchSize:Pi,previousRenderContext:Di,previousBatchConfig:qi,requestFrame:Wi,cancelFrame:Ni,hasIdleCallback:Qo,cleanupNodeVisibility:Gm,onDatasetKeyChanged:H=>{Op(),Ge(),Ro(),lg(),H>0&&ia(H)},onDatasetChanged:()=>{An.value&&ai({immediate:!0})}});qe([Jo,An,()=>F.value,()=>G()],([H,te])=>{if(!H)return Qm(),void li();Sp(),te?ai({immediate:!0}):li()},{flush:"post",immediate:!0}),qe([()=>ze.value.length,()=>An.value],H=>xo(null,[H],function*([te,he]){he&&te&&Z&&(yield mt(),ai({immediate:!0}))}),{flush:"post"}),qe(oo,H=>{H&&(function(){var te;if(vo.value&&Io.value&&Wr.value&&((te=Mo.value)!=null&&te[1]))return;const he=Ot({type:"paragraph",children:[{type:"text",content:"Probe paragraph text",raw:"Probe paragraph text"}],raw:"Probe paragraph text"}),ve=Ot({type:"list_item",children:[he],raw:"- Probe paragraph text"}),Ne=Ot({type:"list",ordered:!1,items:[ve],raw:"- Probe paragraph text"});vo.value=he,Io.value=ve,Wr.value=Ne;const Ue={1:null,2:null,3:null,4:null,5:null,6:null};for(let Ye=1;Ye<=6;Ye++)Ue[Ye]=Ot({type:"heading",level:Ye,text:"Probe heading",children:[{type:"text",content:"Probe heading",raw:"Probe heading"}],raw:`${"#".repeat(Ye)} Probe heading`});Mo.value=Ue})()},{immediate:!0}),qe([()=>F.value,oo],()=>{if(!oo.value)return Xe(),void(ee.value=0);Ie(),Xe(),oo.value&&F.value&&typeof ResizeObserver<"u"&&(ut=new ResizeObserver(()=>{Ie(),ws.value&&jo(),Ci.value&&Dp(),Co("resize")}),ut.observe(F.value))},{immediate:!0}),qe([oo,_r,sa],()=>xo(null,null,function*(){if(!oo.value)return ue.value={paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}},void Ro();yield mt(),(function(){if(!oo.value||typeof window>"u")return ue.value={paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}},void Ro();const H={paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}},te=S2(Ip(O.value),".paragraph-node");H.paragraph=fw(O.value,te,"pre-wrap");const he=Ip(B.value),ve=he?.querySelector(".paragraph-node");H.listItem=fw(B.value,ve,"pre-wrap");const Ne=st("readSimpleTextProbeProfile.list.offsetHeight",()=>{var Ye,tt;return(tt=(Ye=j.value)==null?void 0:Ye.offsetHeight)!=null?tt:0}),Ue=st("readSimpleTextProbeProfile.listItem.offsetHeight",()=>{var Ye,tt;return(tt=(Ye=B.value)==null?void 0:Ye.offsetHeight)!=null?tt:0});H.listWrapperOverhead=Math.max(0,Ne-Ue);for(let Ye=1;Ye<=6;Ye++){const tt=S2(Ip($[Ye]),`h${Ye}`);H.headings[Ye]=fw($[Ye],tt,"pre-wrap")}ue.value=H,Ro()})()}),{flush:"post",immediate:!0}),qe(()=>ze.value.length,()=>{An.value&&ai({immediate:!0})}),qe([oo,ee],()=>{Ro(),An.value&&ai({immediate:!0}),ws.value&&jo(),Ci.value&&Dp(),Co("resize")},{immediate:!1}),qe(()=>on.value,H=>{if(H)for(const[te,he]of Qi)N2(te,he);else if(xp(),An.value)ai({immediate:!0});else for(const[te,he]of Qi)he&&tu(te,!0)},{immediate:!1}),qe([Ee,Me,()=>G()],()=>{var H;(H=so.refresh)==null||H.call(so);for(const[te,he]of Qi)N2(te,he)},{immediate:!1}),qe([()=>I.viewportPriority,()=>ze.value.length,Me],([H,te,he])=>{if(H!==!1){if(V.value&&(te<=200||te<=he)){V.value=!1;for(const[ve,Ne]of Qi)N2(ve,Ne)}}else V.value=!1}),qe(()=>us.value,()=>{An.value&&ai({immediate:!0})}),qe([Xo,qr,Lo,()=>ze.value.length,An],()=>{Oo()},{immediate:!0});let ug=null,cg=!1,Pp=null;function dg(){ug=null,h3=null,f3=void 0,Ep=null,lg()}function O3(){Op(),Ge(),Ro(),Yi.clear();const H=ze.value.length;H>0&&ia(H),S3()}function P3(){D3(),vt(),og=null,Kf=null,Zf=null,T2=null,tg=null,ng=null,cg=!1,dg(),H_("restore"),Il(),Np()}function fg(H){var te;return[(te=Ts())!=null?te:"",qo(),Cc(),_2.value,rg(H),ze.value.length,Math.round(er(0,ze.value.length)),Math.round(qf()),Cs.count,Math.round(Cs.total)].join(":")}function rI(){return xo(this,null,function*(){var H,te,he,ve;const Ne=(H=i.virtualScroll)==null?void 0:H.settledToken,Ue=rg(Ne),Ye=qo(),tt=Ts(),bt=sa.value;if(Bn.value&&((te=i.virtualScroll)==null?void 0:te.settleMode)==="manual"&&I2(Ne))if(p3()){if(fg(Ne)!==Ep&&!cg){cg=!0;try{const nt=yield I3({reason:"manual",expectedSettledTokenKey:Ue}),ht=rg()===Ue;_3(Ye,tt,bt)&&nt.sessionKey===Ye&&nt.threadKey===tt&&ht&&nt.stable&&nt.phase==="final"&&(Ep=fg((he=i.virtualScroll)==null?void 0:he.settledToken))}finally{cg=!1,yield mt();const nt=(ve=i.virtualScroll)==null?void 0:ve.settledToken,ht=I2(nt)?fg(nt):"";_3(Ye,tt,bt)&&ht&&Ep!==ht&&rI()}}}else Co("manual")})}qe(Bn,(H,te)=>{if(H!==te){if(!H)return P3(),void D3();P3(),O3(),Pp=sa.value,Co("content")}},{flush:"post"}),qe([Bn,sa],([H,te])=>{H?Pp!=null?Pp!==te&&(Pp=te,(function(he="resize"){Op(),Ge(),Ro(),Yi.clear();const ve=ze.value.length;ve>0&&ia(ve),S3(),Kf=null,Zf=null,T2=null,og=null,cg=!1,dg(),J_(),mt(()=>{Ac(),ws.value&&jo(),Ci.value&&Dp(),Co(he)})})("resize")):Pp=te:Pp=null},{flush:"post",immediate:!0}),qe([Bn,()=>qo(),()=>Ts()],([H])=>{H&&(P3(),O3(),H_("content"),Co("content"))}),qe([Bn,()=>qo(),()=>Ts(),sa,()=>ze.value.length],([H])=>{H&&(function(te="async-node"){let he=!1;for(const[ve,Ne]of Array.from(ul.entries()))c3(Ne)||(ul.delete(ve),vr.delete(ve),he=!0);he&&(Mp(),Co(te))})("async-node")},{flush:"post"}),qe([Bn,()=>{var H;return(H=i.virtualScroll)==null?void 0:H.sessionKey},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.measurementKey},()=>i.indexKey,()=>K.value],([H])=>{H&&(lg(),(function(te="content"){if(!Bn.value)return;const he=[],ve=ze.value.length,Ne=Ym(ve);for(const Ue of Array.from(Yi.keys())){if(Ue>=ve){he.push(Ue);continue}if(Ue=ve&&Yi.delete(Ue);he.length&&((function(Ue,Ye={}){const tt=Array.from(Ue,Number);rt(tt);let bt=0;if(me(()=>(bt=Y(tt,Ye),bt>0)),bt>0)(function(nt){for(const ht of nt)Yi.delete(ht)})(tt);else for(const nt of tt)bn.delete(nt)})(he,{notify:!1}),Ro(),dg(),ws.value&&jo(),Ci.value&&Dp(),Co(te))})("content"))},{flush:"post",immediate:!0}),qe([Bn,()=>ze.value.length,()=>qo(),()=>Ts()],([H,te,he,ve],[Ne,Ue,Ye,tt])=>{H&&Ne&&he===Ye&&ve===tt&&te!==Ue&&dg()},{flush:"post"}),qe([Bn,()=>{var H;return(H=i.virtualScroll)==null?void 0:H.heightCache},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.heightCacheWidth},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.restoreState},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.measurementKey},()=>ze.value.length,()=>qo(),ee],()=>{J_()},{flush:"post",immediate:!0}),qe([Bn,()=>{var H;return(H=i.virtualScroll)==null?void 0:H.restoreState},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.restoreAnchor},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.measurementKey},()=>ze.value.length,()=>qo(),ee],H=>xo(null,[H],function*([te,he]){if(!te||!he)return;yield mt();const ve=(function(){var Ne;const Ue=(Ne=i.virtualScroll)==null?void 0:Ne.restoreAnchor;return Ue==null||Ue===!1?null:Ue===!0?"true":String(Ue)})();x3(he,{restoreAnchor:ve!=null,restoreToken:ve??void 0})}),{flush:"post",immediate:!0}),qe([Bn,ee,()=>{var H;return(H=i.virtualScroll)==null?void 0:H.restoreState},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.measurementKey}],([H])=>{var te;if(!H)return;const he=(te=i.virtualScroll)==null?void 0:te.restoreState;he&&Kf&&Zf==="restore"&&(Q_(he)||(O3(),Kf=null,Zf=null,Co("resize")))},{flush:"post"}),qe([Bn,()=>ze.value.length,()=>qo(),ee],H=>xo(null,[H],function*([te]){var he;const ve=tg,Ne=ng;te&&ve&&(yield mt(),!x3(ve,{restoreAnchor:Ne?.restoreAnchor===!0,restoreToken:(he=Ne?.restoreToken)!=null?he:"imperative",allowUncapturedAnchor:Ne?.allowUncapturedAnchor===!0})&&X_(ve)||(tg=null,ng=null))}),{flush:"post",immediate:!0}),qe([Bn,Oe,()=>{var H;return(H=i.virtualScroll)==null?void 0:H.settleMode},()=>qo(),()=>Ts(),sa,Lu,Sa,()=>us.value,hd,()=>Cs.count,()=>Cs.total],([H,te,he])=>{if(!H||te!==!0||he==="manual"||!m3())return;const ve=(function(){var Ne;const Ue=ze.value.length;return[(Ne=Ts())!=null?Ne:"",qo(),Cc(),_2.value,Ue,Math.round(er(0,Ue)),Math.round(qf()),Cs.count,Math.round(Cs.total)].join(":")})();ug!==ve&&(ug=ve,I3({reason:"final"}).then(Ne=>{Ne.stable||ug!==ve||(ug=null)}))},{flush:"post",immediate:!0}),qe([Bn,Oe,()=>{var H;return(H=i.virtualScroll)==null?void 0:H.settleMode},()=>{var H;return(H=i.virtualScroll)==null?void 0:H.settledToken},()=>qo(),()=>Ts(),sa,Lu,Sa,()=>us.value,hd,()=>ze.value.length,()=>Cs.count,()=>Cs.total],()=>{rI()},{flush:"post",immediate:!0}),qe([()=>ze.value.length,An,qr,Lo,()=>lo.start,()=>lo.end],([H,te,he,ve,Ne,Ue])=>{fe.value&&Ct("virtualization",{nodes:H,virtualization:te,maxLiveNodes:he,buffer:ve,focusIndex:Xo.value,scroll:te?(()=>{const Ye=ko.value||le();return Ye?{reverse:se(Ye),scrollTop:Math.round(Ye.scrollTop),scrollTopAbs:Math.round(Math.abs(Ye.scrollTop)),scrollHeight:Math.round(Ye.scrollHeight),clientHeight:Math.round(Ye.clientHeight)}:null})():null,liveRange:{start:Ne,end:Ue},rendered:us.value})}),qe([()=>I.customId],([H],te,he)=>{if(!H||Bo)return;const ve=(function(Ne,Ue){return Ne?(ir.controllers[Ne]=Ue,()=>{ir.controllers[Ne]===Ue&&delete ir.controllers[Ne]}):()=>{}})(H,{captureRestoreAnchor:Gr,restoreAnchor:Tr,getAnchorDrift:Ml,getReport:bc});he(()=>{ve()})},{immediate:!0}),si(()=>{(function(){if(Bn.value)try{Ac(),ig();const H=Uf("manual");tI(H)&&(R(H),og=H,T3=sg());const te=Lp(H,{includeHeightCache:!0,includeContentHash:!0,allowAnchorFallback:!1,requireViewport:!0,includeEmptyState:!0});te&&(W(te),te.anchor&&z(te.anchor),Fp=ag(te))}catch{}})(),iY(),xp(),Ke(),sI();for(const H of tr.values())for(const te of H)We(te);tr.clear(),Lr.clear(),Yi.clear(),R3(),Op(),Xe(),Il(),Np(),D3(),Qm(),li()});const oY=n0("ViewportDeferredMermaidBlockNode",Yu({loader:()=>xo(null,null,function*(){try{return(yield _s(()=>import("./index11-BuI7qYB6.js"),__vite__mapDeps([7,5]))).default}catch(H){return console.warn('[markstream-vue] Optional peer dependencies for MermaidBlockNode are missing. Falling back to preformatted code rendering. To enable Mermaid rendering, please install "mermaid".',H),Ol}}),loadingComponent:xD,delay:0}),xD),sY=n0("ViewportDeferredInfographicBlockNode",Yu({loader:()=>xo(null,null,function*(){try{return(yield _s(()=>import("./index10-BOfr-M0b.js"),[])).default}catch(H){return console.warn('[markstream-vue] Failed to load InfographicBlockNode. Falling back to preformatted code rendering. To enable Infographic rendering, install "@antv/infographic" and configure setInfographicLoader with a dynamic loader.',H),Ol}}),loadingComponent:AD,delay:0}),AD),rY=n0("ViewportDeferredD2BlockNode",Yu(()=>xo(null,null,function*(){try{return(yield _s(()=>import("./index8-DQP5_GpC.js"),[])).default}catch(H){return console.warn('[markstream-vue] Optional peer dependencies for D2BlockNode are missing. Falling back to preformatted code rendering. To enable D2 rendering, please install "@terrastruct/d2".',H),Ol}})),Ol),lI={text:vs,paragraph:Vh,heading:L4,code_block:nw,list:G1,list_item:Z1,blockquote:x9,table:B0,definition_list:S9,footnote:_9,footnote_reference:pa,footnote_anchor:P0,admonition:E9,vmr_container:M9,hardbreak:tf,link:wl,image:ef,thematic_break:I9,math_inline:Iu,math_block:uq,strong:kl,emphasis:Cl,strikethrough:bl,highlight:ga,insert:Kl,subscript:Vl,superscript:Ul,emoji:ql,checkbox:ha,checkbox_input:ha,inline_code:il,html_inline:ma,reference:yl,html_block:$0},lY=D(()=>wc()),aI=D(()=>aD(I.codeBlockProps)),aY=D(()=>aD(I.codeBlockProps,{omit:["langs"]})),uI=D(()=>Ht(Ht({stream:I.codeBlockStream,darkTheme:I.codeBlockDarkTheme,lightTheme:I.codeBlockLightTheme,monacoOptions:I.codeBlockMonacoOptions,themes:I.themes,langs:m.value==="shiki"?I.langs:void 0,minWidth:I.codeBlockMinWidth,maxWidth:I.codeBlockMaxWidth},typeof de.value=="boolean"?{showTooltips:de.value}:{}),aY.value)),cI=D(()=>Ht(Hn(Ht({},uI.value),{langs:I.langs}),aI.value));function dI(H){return typeof H=="boolean"?H:void 0}const uY=D(()=>{const H=I.codeBlockProps||{},te={},he=dI(H.showLineNumbers);he!==void 0&&(te.showLineNumbers=he);const ve=dI(H.diffInline);ve!==void 0&&(te.diffInline=ve);const Ne=(function(Ue){const Ye=Number(Ue);return Number.isFinite(Ye)&&Ye>0?Ye:void 0})(H.reservedHeightPx);return Ne!==void 0&&(te.reservedHeightPx=Ne),te}),cY=D(()=>Ht(Ht({stream:I.codeBlockStream,darkTheme:I.codeBlockDarkTheme,lightTheme:I.codeBlockLightTheme,themes:I.themes,langs:I.langs,minWidth:I.codeBlockMinWidth,maxWidth:I.codeBlockMaxWidth},typeof de.value=="boolean"?{showTooltips:de.value}:{}),aI.value)),dY=D(()=>Ht({},I.mermaidProps||{})),fI=D(()=>Ht({},I.d2Props||{})),fY=D(()=>Ht({},I.infographicProps||{})),hg=D(()=>({typewriter:h.value,fade:I.fade,customHtmlTags:Go.value.customHtmlTags})),hY=D(()=>Ht(Ht({},hg.value),typeof de.value=="boolean"?{showTooltip:de.value}:{})),pY=D(()=>Ht(Ht({},hg.value),typeof de.value=="boolean"?{showTooltips:de.value}:{})),mY=D(()=>Ht(Ht({},hg.value),typeof de.value=="boolean"?{showTooltips:de.value}:{})),gY=D(()=>Ht(Ht({},hg.value),typeof de.value=="boolean"?{showTooltips:de.value}:{}));function vY(H){return Array.isArray(H.children)&&H.children.length>0}const F2=D(()=>uo.value.map(H=>{var te,he,ve,Ne,Ue,Ye,tt,bt;let nt=(function($t){var pn,vn,Ln,Mn,Nn,Qn,Jn;if($t.type!=="code_block")return $t;const Xi=$t,Nr=[String((pn=Xi.language)!=null?pn:""),String((vn=Xi.loading)!=null?vn:""),String((Ln=Xi.diff)!=null?Ln:""),String((Mn=Xi.code)!=null?Mn:""),String((Nn=Xi.originalCode)!=null?Nn:""),String((Qn=Xi.updatedCode)!=null?Qn:""),String((Jn=Xi.raw)!=null?Jn:"")].join("\0"),kr=Vr.get(Xi);if(kr&&kr.signature===Nr)return kr.node;const iu=Ht({},Xi);return Vr.set(Xi,{signature:Nr,node:iu}),iu})(H.node);const ht=R2(nt);let kt=gI(nt,ht);if((nt.type==="html_block"||nt.type==="html_inline")&&kt===lI[nt.type]){const $t=nt,pn=String((te=$t.tag)!=null?te:"").trim().toLowerCase()||FH($t.content);if(pn){const vn=In.value[pn];if(Zo.value.has(pn)&&vn)kt=vn,nt=Hn(Ht({},$t),{type:pn,tag:pn,content:G1e($t.content,pn)});else if(RH((he=$t.content)!=null?he:$t.raw,pn)){const Ln=String((Ne=(ve=$t.content)!=null?ve:$t.raw)!=null?Ne:"");nt.type==="html_inline"?(kt=vs,nt={type:"text",content:Ln,raw:Ln}):(kt=Vh,nt={type:"paragraph",children:[{type:"text",content:Ln,raw:Ln}],raw:Ln})}}}const Je=nt.type==="code_block"&&m.value==="pre"&&kt===Ol&&!$3(In.value,ht);let pt=Ht({},(function($t,pn,vn){const Ln=pn??R2($t);if($t.type==="code_block"){const Mn=Ln?$3(In.value,Ln):void 0;if(vn&&m.value==="pre"&&!Mn&&vn===Ol)return uY.value;if(vn&&Ln&&vn===Mn)return Ln==="mermaid"?pI($t):Ln==="infographic"?mI($t):Ln==="d2"||Ln==="d2lang"?fI.value:cI.value;if(vn&&vn===In.value.code_block)return cI.value;if(wn(vn))return cY.value}return Ln==="mermaid"?pI($t):Ln==="infographic"?mI($t):Ln==="d2"||Ln==="d2lang"?fI.value:$t.type==="link"?hY.value:$t.type==="list"?pY.value:$t.type==="blockquote"?mY.value:$t.type==="table"?gY.value:$t.type==="code_block"?uI.value:hg.value})(nt,ht,kt));const Nt=oo.value?Fn.value[H.index]:null;nt.type==="code_block"&&Nt?.kind==="code-block"&&(pt=Hn(Ht({},pt),Je?{reservedHeightPx:(Ue=Nt.height)!=null?Ue:Nt.contentHeight}:{estimatedHeightPx:Nt.height,estimatedContentHeightPx:Nt.contentHeight,estimatedDiffInline:Nt.diffInline})),Je||nt.type!=="code_block"||ht!=="mermaid"||A1(pt.estimatedPreviewHeightPx)!=null||(pt=Hn(Ht({},pt),{estimatedPreviewHeightPx:Zk(Vk(String((Ye=nt.code)!=null?Ye:"")))})),Je||nt.type!=="code_block"||ht!=="infographic"||A1(pt.estimatedPreviewHeightPx)!=null||(pt=Hn(Ht({},pt),{estimatedPreviewHeightPx:Gk(Kk(String((tt=nt.code)!=null?tt:"")))})),nt.type==="math_block"&&(pt=Hn(Ht({},pt),{cacheScope:ki}));const _t=(function($t,pn){const vn=String($t.type);return!a2(vn)&&In.value[vn]===pn})(nt,kt),Yt=_t?bx(nt,pe.value):void 0;return Hn(Ht({},H),{node:nt,component:kt,bindings:pt,customBindings:Ht(Ht({},Yt??{}),pt),rendersCustomNode:_t,hasSlotChildren:vY(nt),slotContent:String((bt=nt.content)!=null?bt:""),isCodeBlock:nt.type==="code_block",indexKey:`${lY.value}-${H.index}`,vnodeKey:`${UQ.value}\0${H.index}\0${nt.type}`})}));function R2(H){var te;return H?.type==="code_block"?String((te=H.language)!=null?te:"").trim().toLowerCase():""}function $3(H,te){const he=te.trim().toLowerCase();if(he)for(const ve of[he,M4(he),UW(he)]){const Ne=ve&&H[ve];if(Ne)return Ne}}function hI(H,te,he,ve){var Ne,Ue;const Ye=Ht({},H.value);return A1(Ye.estimatedPreviewHeightPx)==null&&(Ye.estimatedPreviewHeightPx=ve(he(String((Ne=te?.code)!=null?Ne:"")),void 0,Ye.maxHeight==="none"?null:(Ue=A1(Ye.maxHeight))!=null?Ue:void 0)),Ye}function pI(H){return hI(dY,H,Vk,Zk)}function mI(H){return hI(fY,H,Kk,Gk)}function gI(H,te){if(!H)return CA;const he=In.value,ve=he[String(H.type)];if(H.type==="code_block"){const Ne=te??R2(H),Ue=Ne?$3(he,Ne):void 0;return Ue||(m.value==="pre"?he.code_block||Ol:Ne==="mermaid"?he.mermaid||oY:Ne==="infographic"?he.infographic||sY:Ne==="d2"||Ne==="d2lang"?he.d2||rY:ve||he.code_block||Wn.value)}return ve||lI[String(H.type)]||CA}function B3(H){o("click",H)}function yY(H){var te;(te=H.target)!=null&&te.closest("[data-node-index]")&&o("mouseover",H)}function kY(H){var te;(te=H.target)!=null&&te.closest("[data-node-index]")&&o("mouseout",H)}function vI(H){o("mouseover",H)}function yI(H){o("mouseout",H)}const Yf=q(null),El=q(!1),pg=q(null),bY=D(()=>!(I.domMode!=="minimal"||Q.value||I.fade!==!1||h.value||El.value||Fi.value||An.value||To.value||ni.value||ll.value||Object.keys(In.value).length!==0));let mg,$p=null,z3=0,O2=0,P2=0;const kI=["code_block","admonition","table","math_block","html_block","image","thematic_break"],wY=new Set(kI),bI=[".typewriter-cursor",".height-estimation-probes",...kI.map(H=>`[data-node-type="${H}"]`),"script","style"].join(",");function wI(H){if(!H||typeof H!="object")return!1;const te=H.type;return typeof te=="string"&&wY.has(te)}function $2(H){var te,he;if(!H||typeof H!="object")return 0;const ve=H,Ne=(he=(te=ve.raw)!=null?te:ve.content)!=null?he:ve.code;if(typeof Ne=="string")return Ne.length;const Ue=ve.children;if(Array.isArray(Ue))return Ue.reduce((tt,bt)=>tt+$2(bt),0);const Ye=ve.items;return Array.isArray(Ye)?Ye.reduce((tt,bt)=>tt+$2(bt),0):0}function B2(){mg&&(clearTimeout(mg),mg=void 0)}function j3(){z3+=1,$p!=null&&(Ni?.($p),$p=null)}function gg(){j3(),pd(),Yf.value&&(Yf.value.style.visibility="hidden")}function CY(H){var te;if(H.nodeType!==Node.TEXT_NODE||!((te=H.textContent)!=null?te:"").trim())return!1;const he=H.parentElement;return!!he&&!he.closest(bI)}function AY(H){let te=H.lastChild;for(;te;){if(CY(te))return te;if(te.nodeType===Node.ELEMENT_NODE){const he=te;if(!he.matches(bI)&&he.lastChild){te=he.lastChild;continue}}for(;te&&te!==H&&!te.previousSibling;)te=te.parentNode;if(!te||te===H)break;te=te.previousSibling}return null}function CI(){const H=F2.value;for(let te=H.length-1;te>=0;te--){const he=H[te];if(!he||wI(he.node)||!L2(he.index))continue;const ve=Qi.get(he.index);if(!ve)continue;const Ne=AY(ve);if(Ne)return Ne}return null}function pd(){pg.value&&(pg.value.classList.remove(SD),pg.value=null)}function z2(){if(d.value!=="simple"||!Z||!El.value||!F.value)return void pd();const H=CI(),te=H?(function(he){var ve;const Ne=(ve=he.parentElement)==null?void 0:ve.closest(".text-node");return Ne instanceof HTMLElement?Ne:he.parentElement})(H):null;te!==pg.value&&(pd(),te&&(te.classList.add(SD),pg.value=te))}function j2(){if(d.value!=="precise"||!Z||!El.value||$p!=null)return;const H=z3,te=()=>{$p=null,H===z3&&(function(){var he,ve;if(d.value!=="precise"||!(Z&&El.value&&F.value&&Yf.value))return;const Ne=F.value,Ue=Yf.value;Ue.style.visibility="hidden";const Ye=CI();if(!Ye)return;let tt=0,bt=0,nt=20,ht=!1;if(Ye?.textContent){const kt=Ye.textContent.length,Je=document.createRange();Je.setStart(Ye,Math.max(0,kt-1)),Je.setEnd(Ye,kt);const pt=typeof Je.getClientRects=="function"?Je.getClientRects():void 0,Nt=(ve=pt?.[pt.length-1])!=null?ve:(he=Ye.parentElement)==null?void 0:he.getBoundingClientRect();if(Nt){const _t=st("typewriterCursor.root.getBoundingClientRect",()=>Ne.getBoundingClientRect());tt=Nt.right-_t.left+Ne.scrollLeft,bt=Nt.top-_t.top+Ne.scrollTop,nt=Nt.height||nt,ht=!0}Je.detach()}ht&&(Ue.style.transform=`translate(${Math.max(0,tt)}px, ${Math.max(0,bt)}px)`,Ue.style.height=`${nt}px`,Ue.style.visibility="visible")})()};Wi?$p=Wi(te):te()}return qe([be,()=>i.content,()=>i.nodes,()=>I.typewriter,Oe],()=>xo(null,null,function*(){var H,te;if(!Z||Q.value||!re.value)return;if(Oe.value)return El.value=!1,B2(),void gg();if((H=i.nodes)!=null&&H.length)return El.value=!1,B2(),gg(),O2=((te=i.content)!=null?te:"").length,void(P2=be.value.length);const he=(function(){var tt,bt;return(tt=i.nodes)!=null&&tt.length?i.nodes.reduce((nt,ht)=>nt+$2(ht),0):((bt=i.content)!=null?bt:"").length})(),ve=(function(){var tt;return(tt=i.nodes)!=null&&tt.length?i.nodes.reduce((bt,nt)=>bt+$2(nt),0):be.value.length})(),Ne=!wI(ze.value[ze.value.length-1]),Ue=he>O2,Ye=ve>P2;if(!h.value||!Ne||!Ue&&!Ye)return h.value&&Ne||(El.value=!1,gg()),O2=he,void(P2=ve);O2=he,P2=ve,El.value=!0,d.value==="precise"&&Yf.value&&(Yf.value.style.visibility="hidden"),B2(),yield mt(),d.value==="simple"?z2():(pd(),j2()),mg=setTimeout(()=>{mg=void 0,El.value=!1},3e3)}),{flush:"post",immediate:!0}),qe(El,H=>xo(null,null,function*(){H?(yield mt(),d.value!=="simple"?(pd(),d.value==="precise"&&j2()):z2()):gg()}),{flush:"post"}),qe(d,()=>xo(null,null,function*(){if(Z&&!Q.value&&re.value&&El.value){if(yield mt(),d.value==="simple")return j3(),void z2();pd(),d.value!=="precise"?gg():j2()}}),{flush:"post"}),qe([()=>us.value,()=>lo.start,()=>lo.end],()=>xo(null,null,function*(){Z&&!Q.value&&re.value&&El.value&&(yield mt(),d.value!=="simple"?(pd(),d.value==="precise"&&j2()):z2())}),{flush:"post"}),si(()=>{B2(),j3(),pd(),sn.clear()}),(H,te)=>{const he=F$("NodeRenderer",!0);return f(Q)?(k(!0),L(Fe,{key:0},xt(F2.value,ve=>(k(),L(Fe,{key:ve.vnodeKey},[ve.rendersCustomNode?(k(),ce(fs(ve.component),yi({key:0,ref_for:!0},ve.customBindings,{node:ve.node,loading:ve.node.loading,"index-key":ve.indexKey,"custom-id":I.customId,"is-dark":I.isDark,onClick:B3,onMouseover:vI,onMouseout:yI,onCopy:te[0]||(te[0]=Ne=>s(Ne)),onHandleArtifactClick:te[1]||(te[1]=Ne=>o("handleArtifactClick",Ne))}),{default:ae(()=>[ve.hasSlotChildren?(k(),ce(he,yi({key:0,ref_for:!0},kn.value,{nodes:ve.node.children,"index-key":ve.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):ve.slotContent?(k(),ce(he,yi({key:1,ref_for:!0},kn.value,{content:ve.slotContent,final:!ve.node.loading,"index-key":`${ve.indexKey}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):J("",!0)]),_:2},1040,["node","loading","index-key","custom-id","is-dark"])):(k(),ce(fs(ve.component),yi({key:1,node:ve.node,loading:ve.node.loading,"index-key":ve.indexKey},{ref_for:!0},ve.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onClick:B3,onMouseover:vI,onMouseout:yI,onCopy:te[2]||(te[2]=Ne=>s(Ne)),onHandleArtifactClick:te[3]||(te[3]=Ne=>o("handleArtifactClick",Ne))}),null,16,["node","loading","index-key","custom-id","is-dark"]))],64))),128)):(k(),L("div",{key:1,ref_key:"containerRef",ref:F,class:Pe(["markstream-vue markdown-renderer",[{dark:I.isDark},{virtualized:An.value},{"virtual-scroll-coordinated":io.value},{"stable-layout":gi.value},{"typewriter-simple-cursor":El.value&&d.value==="simple"}]]),"data-custom-id":I.customId,onClick:B3,onMouseover:yY,onMouseout:kY},[ks.value||An.value?(k(),L(Fe,{key:0},[ks.value?(k(),ce(n4e,{key:0,width:_r.value,"flow-root":An.value||io.value,"paragraph-node":vo.value,"list-item-node":Io.value,"list-node":Wr.value,"heading-nodes":Mo.value,"set-paragraph-wrapper":Kt,"set-list-item-wrapper":_n,"set-list-wrapper":Un,"set-heading-wrapper":Jm},null,8,["width","flow-root","paragraph-node","list-item-node","list-node","heading-nodes"])):J("",!0),An.value?(k(),L("div",{key:1,class:"node-spacer",style:an({height:`${yr.value}px`}),"aria-hidden":"true"},null,4)):J("",!0)],64)):J("",!0),bY.value?(k(!0),L(Fe,{key:1},xt(F2.value,ve=>(k(),L(Fe,{key:ve.vnodeKey},[L2(ve.index)?(k(),ce(fs(ve.component),yi({key:0,node:ve.node,loading:ve.node.loading,"index-key":ve.indexKey},{ref_for:!0},ve.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onMouseover:te[4]||(te[4]=Ne=>o("mouseover",Ne)),onMouseout:te[5]||(te[5]=Ne=>o("mouseout",Ne)),onCopy:te[6]||(te[6]=Ne=>s(Ne)),onHandleArtifactClick:te[7]||(te[7]=Ne=>o("handleArtifactClick",Ne))}),null,16,["node","loading","index-key","custom-id","is-dark"])):J("",!0)],64))),128)):(k(!0),L(Fe,{key:2},xt(F2.value,ve=>(k(),L("div",{key:ve.vnodeKey,ref_for:!0,ref:Ne=>N2(ve.index,Ne),class:"node-slot","data-node-index":ve.index,"data-node-type":ve.node.type},[L2(ve.index)?(k(),L("div",{key:0,ref_for:!0,ref:Ne=>(function(Ue,Ye){var tt;Ye||(function(kt){const Je=`${wc()}-${kt}`;let pt=!1;for(const Nt of Array.from(vr.keys())){const _t=ul.get(Nt);(_t?.index===kt||Nt===Je||Nt.startsWith(`${Je}-`))&&(vr.delete(Nt),ul.delete(Nt),pt=!0)}pt&&(Mp(),Co("async-node"))})(Ue),es.delete(Ue),(function(kt){var Je;const pt=((Je=Lr.get(kt))!=null?Je:0)+1;Lr.set(kt,pt)})(Ue);const bt=tr.get(Ue);if(bt){for(const kt of bt)We(kt);tr.delete(Ue)}if((function(kt){const Je=Ur.get(kt);Je&&(po?.unobserve(Je),al.delete(Je),Ur.delete(kt))})(Ue),!Ye||!Qs.value)return ao.delete(Ue),void Lr.delete(Ue);ao.set(Ue,Ye);const nt=()=>{D2(Ue,Ye)};queueMicrotask(nt);const ht=(po||typeof ResizeObserver>"u"||(po=new ResizeObserver(kt=>{if(kt.length)for(const Je of kt){const pt=al.get(Je.target),Nt=Ur.get(pt??-1);pt!=null&&Nt&&D2(pt,Nt)}else Ac()})),po);if(ht&&(Ur.set(Ue,Ye),al.set(Ye,Ue),ht.observe(Ye)),typeof window<"u"){const kt=((tt=ze.value[Ue])==null?void 0:tt.type)==="code_block"?[16,80,240,800]:Oe.value?[80]:[];if(kt.length){const Je=kt.map(pt=>Se(pt,nt,"node-resize")).filter(pt=>pt!=null);Je.length&&tr.set(Ue,Je)}}})(ve.index,Ne),class:"node-content"},[ve.isCodeBlock?ve.rendersCustomNode?(k(),ce(fs(ve.component),yi({key:1,ref_for:!0},ve.customBindings,{node:ve.node,loading:ve.node.loading,"index-key":ve.indexKey,"custom-id":I.customId,"is-dark":I.isDark,onCopy:te[12]||(te[12]=Ne=>s(Ne)),onHandleArtifactClick:te[13]||(te[13]=Ne=>o("handleArtifactClick",Ne))}),{default:ae(()=>[ve.hasSlotChildren?(k(),ce(he,yi({key:0,ref_for:!0},kn.value,{nodes:ve.node.children,"index-key":ve.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):ve.slotContent?(k(),ce(he,yi({key:1,ref_for:!0},kn.value,{content:ve.slotContent,final:!ve.node.loading,"index-key":`${ve.indexKey}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):J("",!0)]),_:2},1040,["node","loading","index-key","custom-id","is-dark"])):(k(),ce(fs(ve.component),yi({key:2,node:ve.node,loading:ve.node.loading,"index-key":ve.indexKey},{ref_for:!0},ve.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onCopy:te[14]||(te[14]=Ne=>s(Ne)),onHandleArtifactClick:te[15]||(te[15]=Ne=>o("handleArtifactClick",Ne))}),null,16,["node","loading","index-key","custom-id","is-dark"])):(k(),ce(Po,{key:0,name:"fade",css:I.fade!==!1,appear:I.fade!==!1},{default:ae(()=>[ve.rendersCustomNode?(k(),ce(fs(ve.component),yi({key:0,ref_for:!0},ve.customBindings,{node:ve.node,loading:ve.node.loading,"index-key":ve.indexKey,"custom-id":I.customId,"is-dark":I.isDark,onCopy:te[8]||(te[8]=Ne=>s(Ne)),onHandleArtifactClick:te[9]||(te[9]=Ne=>o("handleArtifactClick",Ne))}),{default:ae(()=>[ve.hasSlotChildren?(k(),ce(he,yi({key:0,ref_for:!0},kn.value,{nodes:ve.node.children,"index-key":ve.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):ve.slotContent?(k(),ce(he,yi({key:1,ref_for:!0},kn.value,{content:ve.slotContent,final:!ve.node.loading,"index-key":`${ve.indexKey}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):J("",!0)]),_:2},1040,["node","loading","index-key","custom-id","is-dark"])):(k(),ce(fs(ve.component),yi({key:1,node:ve.node,loading:ve.node.loading,"index-key":ve.indexKey},{ref_for:!0},ve.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onCopy:te[10]||(te[10]=Ne=>s(Ne)),onHandleArtifactClick:te[11]||(te[11]=Ne=>o("handleArtifactClick",Ne))}),null,16,["node","loading","index-key","custom-id","is-dark"]))]),_:2},1032,["css","appear"]))],512)):(k(),L("div",{key:1,class:"node-placeholder",style:an({height:`${Is(ve.index)}px`})},null,4))],8,s4e))),128)),El.value&&d.value==="precise"?(k(),L("span",{key:3,ref_key:"typewriterCursorRef",ref:Yf,class:"typewriter-cursor","aria-hidden":"true"},null,512)):J("",!0),An.value?(k(),L("div",{key:4,class:"node-spacer",style:an({height:`${Tl.value}px`}),"aria-hidden":"true"},null,4)):J("",!0)],42,o4e))}}})),[["__scopeId","data-v-a9489508"]]),Zl=Aq;Zl.install=e=>{const t=new Set(["MarkdownRender","NodeRenderer",Zl.__name,Zl.name].filter(n=>!!n));for(const n of t)e.component(n,Aq)};const Fx=Object.freeze(Object.defineProperty({__proto__:null,default:Zl},Symbol.toStringTag,{value:"Module"})),r4e={key:0,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},l4e={key:1,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},a4e={key:2,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},u4e={key:3,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},c4e={class:"admonition-title"},d4e=["aria-expanded","aria-controls"],f4e=["id"],E9=Hi(dt({__name:"AdmonitionNode",props:{node:{},indexKey:{},isDark:{type:Boolean},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},emits:["copy"],setup(e,{emit:t}){var n;const i=e,o=t,s=D(()=>{if(i.node.title&&i.node.title.trim().length)return i.node.title;const u=i.node.kind||"note";return u.charAt(0).toUpperCase()+u.slice(1)}),r=q(!!i.node.collapsible&&!((n=i.node.open)==null||n));function l(){i.node.collapsible&&(r.value=!r.value)}const a=`admonition-${Math.random().toString(36).slice(2,9)}`;return(u,c)=>(k(),L("div",{class:Pe(["admonition",[`admonition-${i.node.kind}`]])},[_("div",{id:a,class:"admonition-legend"},[i.node.kind==="note"||i.node.kind==="info"?(k(),L("svg",r4e,[...c[1]||(c[1]=[_("circle",{cx:"12",cy:"12",r:"10"},null,-1),_("path",{d:"M12 16v-4"},null,-1),_("path",{d:"M12 8h.01"},null,-1)])])):i.node.kind==="tip"?(k(),L("svg",l4e,[...c[2]||(c[2]=[_("path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"},null,-1),_("path",{d:"M9 18h6"},null,-1),_("path",{d:"M10 22h4"},null,-1)])])):i.node.kind==="warning"||i.node.kind==="caution"?(k(),L("svg",a4e,[...c[3]||(c[3]=[_("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"},null,-1),_("path",{d:"M12 9v4"},null,-1),_("path",{d:"M12 17h.01"},null,-1)])])):i.node.kind==="danger"||i.node.kind==="error"?(k(),L("svg",u4e,[...c[4]||(c[4]=[_("polygon",{points:"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2"},null,-1),_("path",{d:"M12 8v4"},null,-1),_("path",{d:"M12 16h.01"},null,-1)])])):J("",!0),_("span",c4e,P(s.value),1),i.node.collapsible?(k(),L("button",{key:4,class:"admonition-toggle","aria-expanded":!r.value,"aria-controls":`${a}-content`,onClick:l},[(k(),L("svg",{style:an({rotate:r.value?"0deg":"90deg"}),xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[...c[5]||(c[5]=[_("path",{d:"m9 18 6-6-6-6"},null,-1)])],4))],8,d4e)):J("",!0)]),mi(_("div",{id:`${a}-content`,class:"admonition-content","aria-labelledby":a},[U(f(Zl),{"index-key":`admonition-${e.indexKey}`,nodes:i.node.children,"custom-id":i.customId,typewriter:i.typewriter,fade:i.fade,onCopy:c[0]||(c[0]=d=>o("copy",d))},null,8,["index-key","nodes","custom-id","typewriter","fade"])],8,f4e),[[hs,!r.value]])],2))}}),[["__scopeId","data-v-a83480e1"]]);E9.install=e=>{e.component(E9.__name,E9)};const IA=()=>_s(()=>import("./d2_markstream-vue-yoD6TSFD.js"),[]);let xy=null,Sy=IA,_y=null,_D=!1,ID=!1;function g8t(){return xo(this,null,function*(){if(xy)return xy;const e=Sy;return e?e===IA&&_D?null:_y||(_y=xo(null,null,function*(){let t;try{t=yield e()}catch(n){if(e===IA)return e===Sy&&(_D=!0,(function(i){ID||(ID=!0,console.warn('[markstream-vue] Optional dependency "@terrastruct/d2" is not installed. D2 blocks will render as source.',i))})(n)),null;throw n}finally{e===Sy&&(_y=null)}return e!==Sy?null:t?(xy=(function(n){var i;if(!n)return n;if(n.D2&&typeof n.D2=="function")return n.D2;if(n.default&&n.default.D2&&typeof n.default.D2=="function")return n.default.D2;const o=(i=n.default)!=null?i:n;return typeof o=="function"?o:o?.D2&&typeof o.D2=="function"?o.D2:o})(t),xy):null}),_y):null})}let Iy=null,xq=null,My=null;function v8t(){return typeof xq=="function"}function y8t(){return xo(this,null,function*(){if(Iy)return Iy;const e=xq;return e?My||(My=xo(null,null,function*(){const t=yield e(),n=(function(i){var o,s,r;if(!i)return null;const l=(o=i.default)!=null?o:i,a=typeof l=="function"&&typeof((s=l.prototype)==null?void 0:s.render)=="function"?l:(r=i.Infographic)!=null?r:l?.Infographic;return typeof a=="function"?a:null})(t);return n?(Iy=n,Iy):null}).finally(()=>{My=null}),My):null})}const k8t=Symbol("markstreamLanguageIconResolver");function h4e(e){return new Worker("/assets/katexRenderer.worker-CO_gEm4q.js",{type:"module",name:e?.name})}function p4e(e){return new Worker("/assets/mermaidParser.worker-BFSlSHEW.js",{type:"module",name:e?.name})}let MD=!1;function Sq(){MD||typeof Worker>"u"||(MD=!0,Uye(new h4e),o9e(new p4e))}Sq();function Hd(e,t,n="/api/v1"){return`${e}${n}${t.startsWith("/")?t:`/${t}`}`}function TD(e,t){const n=new URL(`${e}/api/v1/ws`);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.searchParams.set("client_id",t),n.toString()}const Rx={},ob=Symbol("resolveImage"),Lc=3e4,Ty=5*6e4,ED=5*6e4,_q="0123456789ABCDEFGHJKMNPQRSTVWXYZ",MA=500,Iq=40101;function LD(e,t){for(const[n,i]of Object.entries(t))if(i!==void 0)if(Array.isArray(i))for(const o of i)o!==void 0&&e.append(n,String(o));else e.set(n,String(i))}function i0(e=Lc){try{return AbortSignal.timeout(e)}catch{return}}function m4e(e,t){const n=i0(e);if(n===void 0)return t;try{return AbortSignal.any([n,t])}catch{return t}}function g4e(e,t){let n="",i=e;for(let o=0;o_q[n%32]).join("")}function Ng(){return`${g4e(Date.now(),10)}${v4e(16)}`}function ND(e){try{const t=[];return e.forEach((n,i)=>{typeof n=="string"?t.push({field:i,value:n}):t.push({field:i,file:n.name,size:n.size,type:n.type})}),{formData:t}}catch{return"[FormData]"}}async function hw(e){try{const t=await e.text();return t?t.length>MA?`${t.slice(0,MA)}...`:t:void 0}catch{return}}class DD{constructor(t){this.opts=t,this.tracer=t.tracer??Rx}tracer;async get(t,n){return this.request("GET",t,void 0,n)}async getBlob(t,n,i){let o=Hd(this.opts.origin,t,this.opts.restBasePath);if(n){const c=new URLSearchParams;LD(c,n);const d=c.toString();d&&(o=`${o}?${d}`)}const s=Ng(),r={"X-Request-Id":s};this.addClientHeaders(r);const l=Date.now();this.tracer.restRequest?.({method:"GET",path:t,url:o,requestId:s});let a;try{a=await fetch(o,{method:"GET",headers:r,signal:i0()})}catch(c){throw this.tracer.restFailure?.({method:"GET",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:c}),new ra({message:`Network error calling GET ${t}`,cause:c,method:"GET",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Lc,timestamp:Date.now(),durationMs:Date.now()-l})}if(a.ok){this.tracer.restResponse?.({method:"GET",path:t,requestId:s,status:a.status,durationMs:Date.now()-l,code:0,msg:""});const c=Number(a.headers.get("content-length")??0);if(i?.maxBytes!==void 0&&c>i.maxBytes)throw a.body?.cancel(),new A7({size:c,limit:i.maxBytes});return a.blob()}let u;try{u=await a.clone().json()}catch{}throw this.checkAuthRequired(a,u?.code??0),this.tracer.restResponse?.({method:"GET",path:t,requestId:s,status:a.status,durationMs:Date.now()-l,code:u?.code??a.status,msg:u?.msg??a.statusText,envelopeRequestId:u?.request_id}),new Vu({code:u?.code??a.status,msg:u?.msg??a.statusText,requestId:u?.request_id??s,details:u?.details,timestamp:Date.now(),durationMs:Date.now()-l})}async post(t,n,i){return this.request("POST",t,n,void 0,i)}async postZip(t,n,i){const o="POST",s=Hd(this.opts.origin,t,this.opts.restBasePath),r=Ng(),l={"X-Request-Id":r,"Content-Type":"application/json; charset=utf-8"};this.addClientHeaders(l);const a=Date.now();this.tracer.restRequest?.({method:o,path:t,url:s,requestId:r,body:i});let u;try{u=await fetch(s,{method:o,headers:l,body:JSON.stringify(n),signal:i0(Ty)})}catch(p){throw this.tracer.restFailure?.({method:o,path:t,requestId:r,phase:"fetch",durationMs:Date.now()-a,error:p}),new ra({message:`Network error calling ${o} ${t}`,cause:p,method:o,path:t,url:s,requestId:r,phase:"fetch",timeoutMs:Ty,timestamp:Date.now(),durationMs:Date.now()-a})}const c=u.headers.get("content-type")??void 0,d=c?.split(";",1)[0]?.trim().toLowerCase();if(!u.ok||d!=="application/zip"){let p;try{p=await u.clone().json()}catch{}if(this.checkAuthRequired(u,p?.code??0),!u.ok||p!==void 0&&p.code!==0){const y=p?.code??u.status,b=p?.msg??u.statusText;throw this.tracer.restResponse?.({method:o,path:t,requestId:r,status:u.status,durationMs:Date.now()-a,code:y,msg:b,envelopeRequestId:p?.request_id}),new Vu({code:y,msg:b,requestId:p?.request_id??r,details:p?.details,timestamp:Date.now(),durationMs:Date.now()-a})}const m=u.clone(),g=new TypeError(`Expected application/zip, received ${c??"no content type"}`);throw this.tracer.restFailure?.({method:o,path:t,requestId:r,phase:"parse",durationMs:Date.now()-a,status:u.status,error:g}),new ra({message:`Invalid ZIP response from ${o} ${t}`,cause:g,method:o,path:t,url:s,requestId:r,phase:"parse",timeoutMs:Ty,status:u.status,statusText:u.statusText,contentType:c,bodyPreview:await hw(m),timestamp:Date.now(),durationMs:Date.now()-a})}let h;try{h=await u.blob()}catch(p){throw this.tracer.restFailure?.({method:o,path:t,requestId:r,phase:"parse",durationMs:Date.now()-a,status:u.status,error:p}),new ra({message:`Failed to read ZIP response from ${o} ${t}`,cause:p,method:o,path:t,url:s,requestId:r,phase:"parse",timeoutMs:Ty,status:u.status,statusText:u.statusText,contentType:c,timestamp:Date.now(),durationMs:Date.now()-a})}return this.tracer.restResponse?.({method:o,path:t,requestId:r,status:u.status,durationMs:Date.now()-a,code:0,msg:""}),{blob:h,contentDisposition:u.headers.get("content-disposition")??void 0}}async postForm(t,n,i){if(i?.onUploadProgress!==void 0)return this.postFormXhr(t,n,i.onUploadProgress);const o=Hd(this.opts.origin,t,this.opts.restBasePath),s=Ng(),r={"X-Request-Id":s};this.addClientHeaders(r);const l=Date.now();this.tracer.restRequest?.({method:"POST",path:t,url:o,requestId:s,body:ND(n)});let a;try{a=await fetch(o,{method:"POST",headers:r,body:n,signal:i0()})}catch(d){throw this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:d}),new ra({message:`Network error calling POST ${t}`,cause:d,method:"POST",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Lc,timestamp:Date.now(),durationMs:Date.now()-l})}let u;const c=a.clone();try{u=await a.json()}catch(d){throw this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"parse",durationMs:Date.now()-l,status:a.status,error:d}),new ra({message:`Failed to parse JSON response from POST ${t}`,cause:d,method:"POST",path:t,url:o,requestId:s,phase:"parse",timeoutMs:Lc,status:a.status,statusText:a.statusText,contentType:a.headers.get("content-type")??void 0,bodyPreview:await hw(c),timestamp:Date.now(),durationMs:Date.now()-l})}if(this.tracer.restResponse?.({method:"POST",path:t,requestId:s,status:a.status,durationMs:Date.now()-l,code:u.code,msg:u.msg,envelopeRequestId:u.request_id,data:u.data}),this.checkAuthRequired(a,u.code),u.code!==0){const d=u.code??a.status;throw new Vu({code:d,msg:u.msg??a.statusText,requestId:u.request_id??s,details:u.details,timestamp:Date.now(),durationMs:Date.now()-l})}return u.data}postFormXhr(t,n,i){const o=Hd(this.opts.origin,t,this.opts.restBasePath),s=Ng(),r={"X-Request-Id":s};this.addClientHeaders(r);const l=Date.now();return this.tracer.restRequest?.({method:"POST",path:t,url:o,requestId:s,body:ND(n)}),new Promise((a,u)=>{const c=new XMLHttpRequest;c.open("POST",o),c.timeout=Lc;for(const[d,h]of Object.entries(r))c.setRequestHeader(d,h);c.upload.onprogress=d=>{d.lengthComputable&&i(d.loaded,d.total)},c.onerror=()=>{this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:c.statusText||"network error"}),u(new ra({message:`Network error calling POST ${t}`,cause:null,method:"POST",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Lc,timestamp:Date.now(),durationMs:Date.now()-l}))},c.ontimeout=()=>{this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:"timeout"}),u(new ra({message:`Timeout calling POST ${t}`,cause:null,method:"POST",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Lc,timestamp:Date.now(),durationMs:Date.now()-l}))},c.onload=()=>{let d;try{d=JSON.parse(c.responseText)}catch(h){this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"parse",durationMs:Date.now()-l,status:c.status,error:h}),u(new ra({message:`Failed to parse JSON response from POST ${t}`,cause:h,method:"POST",path:t,url:o,requestId:s,phase:"parse",timeoutMs:Lc,status:c.status,statusText:c.statusText,bodyPreview:c.responseText.slice(0,MA),timestamp:Date.now(),durationMs:Date.now()-l}));return}if(this.tracer.restResponse?.({method:"POST",path:t,requestId:s,status:c.status,durationMs:Date.now()-l,code:d.code,msg:d.msg,envelopeRequestId:d.request_id,data:d.data}),this.checkAuthStatus(c.status,d.code),d.code!==0){const h=d.code??c.status;u(new Vu({code:h,msg:d.msg??c.statusText,requestId:d.request_id??s,details:d.details,timestamp:Date.now(),durationMs:Date.now()-l}));return}a(d.data)},c.send(n)})}async patch(t,n){return this.request("PATCH",t,n)}async put(t,n){return this.request("PUT",t,n)}async delete(t){return this.request("DELETE",t)}async request(t,n,i,o,s={}){const r=s.allowCodes??[],l=s.timeoutMs??Lc,a=s.signal;let u=Hd(this.opts.origin,n,this.opts.restBasePath);if(o){const y=new URLSearchParams;LD(y,o);const b=y.toString();b&&(u=`${u}?${b}`)}const c=Ng(),d={"X-Request-Id":c};this.addClientHeaders(d),i!==void 0&&(d["Content-Type"]="application/json; charset=utf-8");const h=Date.now();this.tracer.restRequest?.({method:t,path:n,url:u,requestId:c,body:i});let p;try{p=await fetch(u,{method:t,headers:d,body:i!==void 0?JSON.stringify(i):void 0,signal:a!==void 0?m4e(l,a):i0(l)})}catch(y){throw a?.aborted&&y instanceof Error&&y.name==="AbortError"?y:(this.tracer.restFailure?.({method:t,path:n,requestId:c,phase:"fetch",durationMs:Date.now()-h,error:y}),new ra({message:`Network error calling ${t} ${n}`,cause:y,method:t,path:n,url:u,requestId:c,phase:"fetch",timeoutMs:l,timestamp:Date.now(),durationMs:Date.now()-h}))}let m;const g=p.clone();try{const y=await p.text();m=p.status===204&&y===""?{code:0,msg:"",data:null,request_id:c}:JSON.parse(y)}catch(y){throw a?.aborted&&y instanceof Error&&y.name==="AbortError"?y:(this.tracer.restFailure?.({method:t,path:n,requestId:c,phase:"parse",durationMs:Date.now()-h,status:p.status,error:y}),new ra({message:`Failed to parse JSON response from ${t} ${n}`,cause:y,method:t,path:n,url:u,requestId:c,phase:"parse",timeoutMs:l,status:p.status,statusText:p.statusText,contentType:p.headers.get("content-type")??void 0,bodyPreview:await hw(g),timestamp:Date.now(),durationMs:Date.now()-h}))}if(this.tracer.restResponse?.({method:t,path:n,requestId:c,status:p.status,durationMs:Date.now()-h,code:m.code,msg:m.msg,envelopeRequestId:m.request_id,data:m.data}),this.checkAuthRequired(p,m.code),m.code!==0&&!r.includes(m.code))throw new Vu({code:typeof m.code=="number"?m.code:p.status,msg:typeof m.msg=="string"&&m.msg.length>0?m.msg:`HTTP ${p.status}${p.statusText?` ${p.statusText}`:""}`,requestId:m.request_id??c,details:m.details,timestamp:Date.now(),durationMs:Date.now()-h});return m.data}addClientHeaders(t){const n=this.opts.credentialStore?.getToken();n!==void 0&&(t.Authorization=`Bearer ${n}`);const i=this.opts.identity;i!==void 0&&(t["X-Kimi-Client-Id"]=i.clientId,t["X-Kimi-Client-Name"]=i.clientName,t["X-Kimi-Client-Version"]=i.clientVersion,t["X-Kimi-Client-Ui-Mode"]=i.clientUiMode)}checkAuthRequired(t,n){this.checkAuthStatus(t.status,n)}checkAuthStatus(t,n){(t===401||n===Iq)&&this.opts.credentialStore?.markAuthRequired?.()}}function Mq(e){return{inputTokens:e.input_tokens,outputTokens:e.output_tokens,cacheReadTokens:e.cache_read_tokens,cacheCreationTokens:e.cache_creation_tokens,totalCostUsd:e.total_cost_usd,contextTokens:e.context_tokens,contextLimit:e.context_limit,turnCount:e.turn_count}}function FD(e){return e.contextTokens===0&&e.contextLimit===0&&e.inputTokens===0&&e.outputTokens===0&&e.turnCount===0}function ju(e){return{id:e.id,title:e.title,createdAt:e.created_at,updatedAt:e.updated_at,busy:e.busy,mainTurnActive:e.main_turn_active,pendingInteraction:e.pending_interaction,lastTurnReason:e.last_turn_reason,archived:e.archived??!1,archivedAt:e.archived_at,currentPromptId:e.current_prompt_id,lastPrompt:e.last_prompt,cwd:e.metadata.cwd,model:e.agent_config.model,usage:Mq(e.usage),messageCount:e.message_count,lastSeq:e.last_seq,workspaceId:e.workspace_id,parentSessionId:typeof e.metadata.parent_session_id=="string"?e.metadata.parent_session_id:void 0}}function Ey(e){const t=e.activity.status;return{id:e.id,title:e.meta.title??e.meta.last_prompt??e.id.slice(0,12),createdAt:new Date(e.meta.created_at).toISOString(),updatedAt:new Date(e.meta.updated_at).toISOString(),busy:t==="running",pendingInteraction:t==="approval"?"approval":t==="question"?"question":void 0,lastTurnReason:t==="failed"?"failed":void 0,archived:e.meta.archived,archivedAt:e.meta.archived_at==null?void 0:new Date(e.meta.archived_at).toISOString(),lastPrompt:e.meta.last_prompt??void 0,cwd:e.workspace.cwd??"",model:e.activity.model??"",pullRequest:e.git===void 0?void 0:e.git.pull_request,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalCostUsd:0,contextTokens:0,contextLimit:0,turnCount:0},messageCount:0,lastSeq:0,workspaceId:e.workspace.id.length>0?e.workspace.id:void 0}}function j0(e){return{id:e.id,root:e.root,name:e.name,lastOpenedAt:e.last_opened_at,sessionCount:e.session_count}}function RD(e){return e.kind==="base64"?{kind:"base64",mediaType:e.media_type,data:e.data}:e.kind==="file"?{kind:"file",fileId:e.file_id}:e.kind==="session_media"?{kind:"sessionMedia",fileId:e.file_id}:{kind:"url",url:e.url}}function D4(e){switch(e.type){case"text":return{type:"text",text:e.text};case"tool_use":return{type:"toolUse",toolCallId:e.tool_call_id,toolName:e.tool_name,input:e.input};case"tool_result":return{type:"toolResult",toolCallId:e.tool_call_id,output:e.output,isError:e.is_error};case"image":return{type:"image",source:RD(e.source)};case"video":return{type:"video",source:RD(e.source)};case"file":return{type:"file",fileId:e.file_id,name:e.name,mediaType:e.media_type,size:e.size};case"thinking":return{type:"thinking",thinking:e.thinking,signature:e.signature};default:return{type:"unknown",raw:e}}}function Tq(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content.map(D4),createdAt:e.created_at,promptId:e.prompt_id,parentMessageId:e.parent_message_id,metadata:e.metadata}}function Eq(e){switch(e.type){case"text":return{type:"text",text:e.text};case"toolUse":return{type:"tool_use",tool_call_id:e.toolCallId,tool_name:e.toolName,input:e.input};case"toolResult":return{type:"tool_result",tool_call_id:e.toolCallId,output:e.output,is_error:e.isError};case"image":case"video":{const t=e.source;let n;return t.kind==="base64"?n={kind:"base64",media_type:t.mediaType,data:t.data}:t.kind==="file"?n={kind:"file",file_id:t.fileId}:t.kind==="sessionMedia"?n={kind:"session_media",file_id:t.fileId}:n={kind:"url",url:t.url},{type:e.type,source:n}}case"file":return{type:"file",file_id:e.fileId,name:e.name,media_type:e.mediaType,size:e.size};case"thinking":return{type:"thinking",thinking:e.thinking,signature:e.signature};case"unknown":return e.raw}}function y4e(e){return{content:e.content.map(Eq),metadata:e.metadata,agent_id:e.agentId,model:e.model,thinking:e.thinking,permission_mode:e.permissionMode,plan_mode:e.planMode,swarm_mode:e.swarmMode,goal_objective:e.goalObjective,goal_control:e.goalControl,skills:e.skills}}function k4e(e){return{decision:e.decision,scope:e.scope,feedback:e.feedback,selected_label:e.selectedLabel}}function b4e(e){return{approvalId:e.approval_id,sessionId:e.session_id,turnId:e.turn_id,toolCallId:e.tool_call_id,toolName:e.tool_name,action:e.action,display:e.tool_input_display??e.display,expiresAt:e.expires_at,createdAt:e.created_at}}function w4e(e){return{id:e.id,label:e.label,description:e.description,recommended:e.recommended===!0||e.is_recommended===!0}}function C4e(e){return{id:e.id,question:e.question,header:e.header,body:e.body,options:e.options.map(w4e),multiSelect:e.multi_select,allowOther:e.allow_other,otherLabel:e.other_label,otherDescription:e.other_description}}function A4e(e){return{questionId:e.question_id,sessionId:e.session_id,turnId:e.turn_id,toolCallId:e.tool_call_id,questions:e.questions.map(C4e),createdAt:e.created_at}}function x4e(e){switch(e.kind){case"single":return{kind:"single",option_id:e.optionId};case"multi":return{kind:"multi",option_ids:e.optionIds};case"other":return{kind:"other",text:e.text};case"multiWithOther":return{kind:"multi_with_other",option_ids:e.optionIds,other_text:e.otherText};case"skipped":return{kind:"skipped"}}}function S4e(e){const t={};for(const[n,i]of Object.entries(e.answers))t[n]=x4e(i);return{answers:t,method:e.method,note:e.note}}function TA(e,t){if(typeof e.run_in_background!="boolean")throw new Error(`task wire missing required run_in_background (id ${e.id})`);return{id:e.id,agentId:e.agent_id??t,sessionId:e.session_id,kind:e.kind,description:e.description,status:e.status,command:e.command,createdAt:e.created_at,startedAt:e.started_at,completedAt:e.completed_at,outputPreview:e.output_preview,outputBytes:e.output_bytes,subagentPhase:e.subagent_phase,subagentType:e.subagent_type,model:e.model,thinkingEffort:e.thinking_effort,parentToolCallId:e.parent_tool_call_id,suspendedReason:e.suspended_reason,swarmIndex:e.swarm_index,runInBackground:e.run_in_background}}function OD(e){return{path:e.path,name:e.name,kind:e.kind,size:e.size,modifiedAt:e.modified_at,etag:e.etag,mime:e.mime,languageId:e.language_id,isBinary:e.is_binary,isSymlinkTo:e.is_symlink_to,gitStatus:e.git_status,childCount:e.child_count}}function xd(e,t){const n=e[t];return typeof n=="string"?n:void 0}function Jp(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ia(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function Lq(e){if(!e||typeof e!="object")return null;const t=e,n=xd(t,"status");if(n!=="active"&&n!=="paused"&&n!=="blocked"&&n!=="complete")return null;const i=t.budget,o=i&&typeof i=="object"?i:{};return{goalId:xd(t,"goalId")??xd(t,"goal_id")??"goal",objective:xd(t,"objective")??"",completionCriterion:xd(t,"completionCriterion")??xd(t,"completion_criterion"),status:n,turnsUsed:Jp(t,"turnsUsed")??Jp(t,"turns_used")??0,tokensUsed:Jp(t,"tokensUsed")??Jp(t,"tokens_used")??0,wallClockMs:Jp(t,"wallClockMs")??Jp(t,"wall_clock_ms")??0,terminalReason:xd(t,"terminalReason")??xd(t,"terminal_reason"),budget:{tokenBudget:Ia(o,"tokenBudget")??Ia(o,"token_budget"),remainingTokens:Ia(o,"remainingTokens")??Ia(o,"remaining_tokens"),turnBudget:Ia(o,"turnBudget")??Ia(o,"turn_budget"),remainingTurns:Ia(o,"remainingTurns")??Ia(o,"remaining_turns"),wallClockBudgetMs:Ia(o,"wallClockBudgetMs")??Ia(o,"wall_clock_budget_ms"),remainingWallClockMs:Ia(o,"remainingWallClockMs")??Ia(o,"remaining_wall_clock_ms"),overBudget:o.overBudget===!0||o.over_budget===!0}}}function _4e(e){const t=e;switch(e.type){case"event.session.created":return{type:"sessionCreated",session:ju(t.payload.session)};case"event.session.updated":return{type:"sessionUpdated",session:ju(t.payload.session),changedFields:t.payload.changed_fields};case"event.session.deleted":return{type:"sessionDeleted",sessionId:t.session_id};case"event.session.archived":{const n=t.payload?.sessionId??t.payload?.session_id;if(typeof n!="string"||n.length===0)return{type:"unknown",raw:{_noop:!0,_wireType:t.type}};const i=t.payload?.workspace_id;return{type:"sessionArchived",sessionId:n,workspaceId:typeof i=="string"&&i.length>0?i:void 0}}case"event.workspace.created":return{type:"workspaceCreated",workspace:j0(t.payload.workspace)};case"event.workspace.updated":return{type:"workspaceUpdated",workspace:j0(t.payload.workspace)};case"event.workspace.deleted":return{type:"workspaceDeleted",workspaceId:t.payload.workspace_id,root:t.payload.root};case"event.session.work_changed":return{type:"sessionWorkChanged",sessionId:t.session_id,busy:t.payload.busy,mainTurnActive:t.payload.main_turn_active,pendingInteraction:t.payload.pending_interaction,lastTurnReason:t.payload.last_turn_reason};case"event.session.status_changed":return{type:"sessionWorkChanged",sessionId:t.session_id,busy:t.payload.status!=="idle"&&t.payload.status!=="aborted",mainTurnActive:t.payload.status!=="idle"&&t.payload.status!=="aborted",pendingInteraction:t.payload.status==="awaiting_approval"?"approval":t.payload.status==="awaiting_question"?"question":"none",lastTurnReason:t.payload.status==="aborted"?"cancelled":void 0};case"event.session.usage_updated":return{type:"sessionUsageUpdated",sessionId:t.session_id,usage:Mq(t.payload.usage)};case"event.session.history_compacted":return{type:"historyCompacted",sessionId:t.session_id,beforeSeq:t.payload.before_seq,reason:t.payload.reason,summaryMessageId:t.payload.summary_message_id};case"event.goal.updated":{const n=Lq(t.payload.snapshot??null);return{type:"goalUpdated",sessionId:t.session_id,goal:n?.status==="complete"?null:n}}case"event.message.created":return{type:"messageCreated",message:Tq(t.payload.message)};case"event.message.updated":return{type:"messageUpdated",sessionId:t.session_id,messageId:t.payload.message_id,content:t.payload.content.map(D4),status:t.payload.status};case"event.assistant.delta":return{type:"assistantDelta",sessionId:t.session_id,messageId:t.payload.message_id,contentIndex:t.payload.content_index,delta:t.payload.delta};case"event.assistant.tool_use_started":case"event.assistant.tool_use_delta":case"event.assistant.tool_use_completed":case"event.assistant.completed":case"event.tool.started":return{type:"unknown",raw:{_noop:!0,_wireType:t.type}};case"event.tool.output":return{type:"toolOutput",sessionId:t.session_id,toolCallId:t.payload.tool_call_id,outputChunk:t.payload.chunk,stream:t.payload.stream};case"event.tool.progress":return typeof t.payload.message=="string"&&t.payload.message.length>0?{type:"toolOutput",sessionId:t.session_id,toolCallId:t.payload.tool_call_id,outputChunk:t.payload.message,stream:"stdout"}:{type:"unknown",raw:{_noop:!0,_wireType:t.type}};case"event.tool.completed":return{type:"unknown",raw:{_noop:!0,_wireType:t.type}};case"event.approval.requested":return{type:"approvalRequested",sessionId:t.session_id,approval:b4e(t.payload)};case"event.approval.resolved":return{type:"approvalResolved",sessionId:t.session_id,approvalId:t.payload.approval_id,decision:t.payload.decision,resolvedAt:t.payload.resolved_at,feedback:t.payload.feedback,selectedLabel:t.payload.selected_label};case"event.approval.expired":return{type:"approvalExpired",sessionId:t.session_id,approvalId:t.payload.approval_id};case"event.question.requested":return{type:"questionRequested",sessionId:t.session_id,question:A4e(t.payload)};case"event.question.answered":return{type:"questionAnswered",sessionId:t.session_id,questionId:t.payload.question_id,resolvedAt:t.payload.resolved_at};case"event.question.dismissed":return{type:"questionDismissed",sessionId:t.session_id,questionId:t.payload.question_id,dismissedAt:t.payload.dismissed_at};case"event.task.created":return{type:"taskCreated",sessionId:t.session_id,task:TA(t.payload.task)};case"event.task.progress":return{type:"taskProgress",sessionId:t.session_id,taskId:t.payload.task_id,outputChunk:t.payload.output_chunk,stream:t.payload.stream};case"event.task.completed":return{type:"taskCompleted",sessionId:t.session_id,taskId:t.payload.task_id,status:t.payload.status,outputPreview:t.payload.output_preview,outputBytes:t.payload.output_bytes};case"event.plugin.changed":return{type:"pluginsChanged"};case"event.capability.changed":return{type:"capabilityChanged",capabilityId:t.payload.capability_id,install:t.payload.install};case"event.config.changed":return{type:"configChanged",changedFields:t.payload.changed_fields,config:EA(t.payload.config)};case"event.model_catalog.changed":return{type:"modelCatalogChanged",changed:t.payload.changed.map(n=>({providerId:n.provider_id,providerName:n.provider_name,added:n.added,removed:n.removed})),unchanged:t.payload.unchanged,failed:t.payload.failed};default:return{type:"unknown",raw:e}}}function I4e(e){return{id:e.model,provider:e.provider,model:e.model,displayName:e.display_name,maxContextSize:e.max_context_size,capabilities:e.capabilities,supportEfforts:e.support_efforts,defaultEffort:e.default_effort}}function Xp(e){return{id:e.id,type:e.type,baseUrl:e.base_url,defaultModel:e.default_model,hasApiKey:e.has_api_key,status:e.status,models:e.models}}function PD(e){return{id:e.id,name:e.name,wireType:e.wire_type,guessed:e.guessed,needsBaseUrl:e.needs_base_url,rejected:e.rejected,rejectReason:e.reject_reason,envKey:e.env_key,models:e.models.map(t=>({id:t.id,name:t.name,maxContextSize:t.max_context_size,capabilities:t.capabilities,reasoning:t.reasoning}))}}function EA(e){const t={};for(const[n,i]of Object.entries(e.providers))t[n]={type:i.type,baseUrl:i.base_url,defaultModel:i.default_model,hasApiKey:i.has_api_key};return{providers:t,defaultProvider:e.default_provider,defaultModel:e.default_model,secondaryModel:e.secondary_model,models:e.models,thinking:e.thinking,planMode:e.plan_mode,yolo:e.yolo,defaultPermissionMode:e.default_permission_mode,defaultPlanMode:e.default_plan_mode,permission:e.permission,hooks:e.hooks,services:e.services,mergeAllAvailableSkills:e.merge_all_available_skills,extraSkillDirs:e.extra_skill_dirs,loopControl:e.loop_control,background:e.background,experimental:e.experimental,telemetry:e.telemetry,raw:e.raw}}function M4e(e){return e.session_id}function T4e(e){return e.seq}function E4e(e){const t=Number(e.slice(1));return Number.isFinite(t)?t:0}function $D(e){switch(e.kind){case"turn":return e.turnId;case"marker":return e.markerId;case"taskref":return e.refId}}const L4e={items:[],tasks:new Map,interactions:new Map,attachments:new Map,todos:new Map,prompts:new Map,meta:{},pendingInteractions:new Set,hasMoreOlder:!1};function N4e(e,t){switch(t.op){case"reset":return D4e(e,t);case"turn.upsert":return R4e(e,t.turn);case"step.upsert":return P4e(e,t.turnId,t.step);case"frame.upsert":return B4e(e,t);case"append":return j4e(e,t);case"marker.upsert":return zD(e,t.item,t.item.markerId,t.beforeTurn);case"taskref.upsert":return zD(e,t.item,t.item.refId,t.beforeTurn);case"task.upsert":return q4e(e,t.task);case"interaction.upsert":return U4e(e,t.interaction);case"attachment.upsert":return K4e(e,t.attachment);case"todo.upsert":return G4e(e,t.todo);case"prompt.upsert":return Y4e(e,t.prompt);case"meta.merge":return e3e(e,t.meta);case"items.remove":return W4e(e,t.ids)}}function D4e(e,t){const n=new Set;for(const i of t.snapshot.interactions)i.state==="pending"&&n.add(i.interactionId);return{state:{items:t.snapshot.items,tasks:new Map(t.snapshot.tasks.map(i=>[i.taskId,i])),interactions:new Map(t.snapshot.interactions.map(i=>[i.interactionId,i])),attachments:new Map(t.snapshot.attachments.map(i=>[i.attachmentId,i])),todos:new Map(t.snapshot.todos.map(i=>[i.todoId,i])),prompts:new Map(t.snapshot.prompts.map(i=>[i.promptId,i])),meta:t.snapshot.meta,pendingInteractions:n,hasMoreOlder:t.snapshot.hasMoreOlder??!1},changed:!0}}function BD(e,t){return{...e,kind:"turn",steps:[...t]}}function Nq(e){return{kind:"turn",turnId:e,ordinal:E4e(e),state:"running",origin:{kind:"other"},steps:[]}}function F4e(e,t){const n=Number(e.slice(t.length+1))||0;return{kind:"step",stepId:e,turnId:t,ordinal:n,state:"running",frames:[]}}function dm(e,t){const n=e.items.find(i=>i.kind==="turn"&&i.turnId===t);return n?.kind==="turn"?n:void 0}function Ox(e,t){const n=[...e];let i=n.length;for(let o=0;ot.ordinal){i=o;break}}return n.splice(i,0,t),n}function F4(e,t,n){return e.map(i=>i.kind==="turn"&&i.turnId===t?n(i):i)}function R4e(e,t){const n=dm(e,t.turnId);return n?O4e(n,t)?{state:e,changed:!1}:{state:{...e,items:F4(e.items,t.turnId,i=>BD(t,i.steps))},changed:!0}:{state:{...e,items:Ox(e.items,BD(t,[]))},changed:!0}}function O4e(e,t){return e.ordinal===t.ordinal&&e.triggerPromptId===t.triggerPromptId&&e.state===t.state&&e.prompt===t.prompt&&e.attachmentIds===t.attachmentIds&&e.startedAt===t.startedAt&&e.endedAt===t.endedAt&&e.origin.kind===t.origin.kind&&e.origin.payload===t.origin.payload&&e.usage===t.usage&&e.durationMs===t.durationMs&&e.error===t.error}function P4e(e,t,n){const i=dm(e,t)??Nq(t),o=i.steps.findIndex(u=>u.stepId===n.stepId);let s,r=!0;if(o>=0){const u=i.steps[o];u&&$4e(u,n)?(r=!1,s=i.steps):s=i.steps.map(c=>c.stepId===n.stepId?{...n,kind:"step",frames:c.frames}:c)}else s=[...i.steps,{...n,kind:"step",frames:[]}].toSorted((u,c)=>u.ordinal-c.ordinal);if(!r)return{state:e,changed:!1};const l={...i,steps:[...s]},a=dm(e,t)?F4(e.items,t,()=>l):Ox(e.items,l);return{state:{...e,items:a},changed:!0}}function $4e(e,t){return e.ordinal===t.ordinal&&e.state===t.state&&e.startedAt===t.startedAt&&e.endedAt===t.endedAt&&e.usage===t.usage&&e.finishReason===t.finishReason&&e.timing===t.timing&&e.retry===t.retry&&e.endReason===t.endReason&&e.endMessage===t.endMessage}function B4e(e,t){const n=dm(e,t.turnId)??Nq(t.turnId),i=n.steps.find(c=>c.stepId===t.stepId)??F4e(t.stepId,t.turnId),o=i.frames.findIndex(c=>c.frameId===t.frame.frameId);let s;if(o>=0){const c=i.frames[o];if(c!==void 0&&z4e(c,t.frame))return{state:e,changed:!1};s=i.frames.map(d=>d.frameId===t.frame.frameId?t.frame:d)}else s=[...i.frames,t.frame];const r={...i,frames:[...s]},l=n.steps.some(c=>c.stepId===t.stepId)?n.steps.map(c=>c.stepId===t.stepId?r:c):[...n.steps,r].toSorted((c,d)=>c.ordinal-d.ordinal),a={...n,steps:l},u=dm(e,t.turnId)?F4(e.items,t.turnId,()=>a):Ox(e.items,a);return{state:{...e,items:u},changed:!0}}function z4e(e,t){return e.kind!==t.kind?!1:e.kind==="text"&&t.kind==="text"?e.text===t.text&&e.role===t.role&&e.attachmentIds===t.attachmentIds&&e.taskId===t.taskId:e.kind==="thinking"&&t.kind==="thinking"?e.text===t.text:e.kind==="tool"&&t.kind==="tool"?e.state===t.state&&e.toolCallId===t.toolCallId&&e.name===t.name&&e.view===t.view&&e.input===t.input&&e.output===t.output&&e.display===t.display&&e.error===t.error&&e.inputText===t.inputText&&e.progress===t.progress&&e.taskId===t.taskId&&e.approvalId===t.approvalId&&e.todoId===t.todoId&&e.agentRefs===t.agentRefs:e.kind==="notice"&&t.kind==="notice"?e.message===t.message&&e.level===t.level&&e.detail===t.detail:!1}function j4e(e,t){if(t.target.type==="task")return H4e(e,t);const{turnId:n,stepId:i,frameId:o}=t.target,s=dm(e,n),r=s?.steps.find(h=>h.stepId===i),l=r?.frames.find(h=>h.frameId===o);if(!s||!r||!l||l.kind!=="text"&&l.kind!=="thinking")return{state:e,changed:!1,gap:{expected:0,got:t.offset}};const a=Dq(l.text,t.offset,t.text);if(a.gap)return{state:e,changed:!1,gap:a.gap};if(!a.changed)return{state:e,changed:!1};const u={...l,text:a.text},c={...r,frames:r.frames.map(h=>h.frameId===o?u:h)},d={...s,steps:s.steps.map(h=>h.stepId===i?c:h)};return{state:{...e,items:F4(e.items,n,()=>d)},changed:!0}}function H4e(e,t){if(t.target.type!=="task")throw new Error("unreachable");const n=t.target.taskId,i=e.tasks.get(n),o=i?.outputTail??"",s=Dq(o,t.offset,t.text);if(s.gap)return{state:e,changed:!1,gap:s.gap};if(!s.changed)return{state:e,changed:!1};const r=i?{...i,outputTail:s.text}:{taskId:n,kind:"other",state:"running",detached:!1,outputTail:s.text},l=new Map(e.tasks);return l.set(n,r),{state:{...e,tasks:l},changed:!0}}function Dq(e,t,n){if(t>e.length)return{text:e,changed:!1,gap:{expected:e.length,got:t}};if(e.slice(t,t+n.length)===n)return{text:e,changed:!1};const i=e.length-t;return e.slice(t)!==n.slice(0,i)?{text:e,changed:!1,gap:{expected:e.length,got:t}}:(i>0?n.slice(i):n).length===0?{text:e,changed:!1}:{text:e.slice(0,t)+n,changed:!0}}function zD(e,t,n,i){if(e.items.some(s=>LA(s)===n)){let s=!1;const r=e.items.map(l=>LA(l)!==n||l===t?l:(s=!0,t));return s?{state:{...e,items:r},changed:!0}:{state:e,changed:!1}}if(i!==void 0){const s=[...e.items];let r=s.length;for(let l=0;l=i){r=l;break}}return s.splice(r,0,t),{state:{...e,items:s},changed:!0}}return{state:{...e,items:[...e.items,t]},changed:!0}}function LA(e){switch(e.kind){case"turn":return e.turnId;case"marker":return e.markerId;case"taskref":return e.refId}}function W4e(e,t){const n=new Set(t),i=e.items.filter(l=>l.kind==="turn"&&n.has(l.turnId)),o=e.items.filter(l=>!n.has(LA(l)));if(o.length===e.items.length)return{state:e,changed:!1};let s=e.pendingInteractions,r=e.interactions;if(i.length>0){const l=new Set,a=new Set(s),u=new Set;for(const c of i)for(const d of c.steps)for(const h of d.frames)h.kind==="tool"&&l.add(h.toolCallId);for(const c of r.values())c.toolCallId!==void 0&&l.has(c.toolCallId)&&(u.add(c.interactionId),a.delete(c.interactionId));if(u.size>0){const c=new Map(r);for(const d of u)c.delete(d);r=c}s=a}return{state:{...e,items:o,interactions:r,pendingInteractions:s},changed:!0}}function q4e(e,t){const n=e.tasks.get(t.taskId);if(n&&X4e(n,t))return{state:e,changed:!1};const i=new Map(e.tasks);return i.set(t.taskId,t),{state:{...e,tasks:i},changed:!0}}function U4e(e,t){const n=e.interactions.get(t.interactionId);if(n&&V4e(n,t))return{state:e,changed:!1};const i=new Map(e.interactions);i.set(t.interactionId,t);let o=e.pendingInteractions;if(t.state==="pending"){if(!o.has(t.interactionId)){const s=new Set(o);s.add(t.interactionId),o=s}}else if(o.has(t.interactionId)){const s=new Set(o);s.delete(t.interactionId),o=s}return{state:{...e,interactions:i,pendingInteractions:o},changed:!0}}function V4e(e,t){return e.interactionKind===t.interactionKind&&e.toolCallId===t.toolCallId&&e.state===t.state&&e.request===t.request&&e.response===t.response}function K4e(e,t){const n=e.attachments.get(t.attachmentId);if(n&&Z4e(n,t))return{state:e,changed:!1};const i=new Map(e.attachments);return i.set(t.attachmentId,t),{state:{...e,attachments:i},changed:!0}}function Z4e(e,t){return e.mediaType===t.mediaType&&e.name===t.name&&e.size===t.size&&e.source===t.source&&e.placeholder===t.placeholder}function G4e(e,t){const n=e.todos.get(t.todoId);if(n&&Q4e(n,t))return{state:e,changed:!1};const i=new Map(e.todos);return i.set(t.todoId,t),{state:{...e,todos:i},changed:!0}}function Q4e(e,t){return e.items===t.items&&e.updatedAt===t.updatedAt}function Y4e(e,t){const n=e.prompts.get(t.promptId);if(n&&J4e(n,t))return{state:e,changed:!1};const i=new Map(e.prompts);return i.set(t.promptId,t),{state:{...e,prompts:i},changed:!0}}function J4e(e,t){return e.status===t.status&&e.userMessageId===t.userMessageId&&e.content===t.content&&e.createdAt===t.createdAt&&e.finishedAt===t.finishedAt&&e.steeredAt===t.steeredAt}function X4e(e,t){return e.kind===t.kind&&e.state===t.state&&e.detached===t.detached&&e.description===t.description&&e.agentId===t.agentId&&e.outputTail===t.outputTail&&e.startedAt===t.startedAt&&e.endedAt===t.endedAt&&e.resultSummary===t.resultSummary&&e.error===t.error&&e.stateReason===t.stateReason&&e.usage===t.usage}function e3e(e,t){const n=t.modes!==void 0?{plan:t.modes.plan===null?void 0:t.modes.plan??e.meta.modes?.plan,swarm:t.modes.swarm===null?void 0:t.modes.swarm??e.meta.modes?.swarm,tower:t.modes.tower===null?void 0:t.modes.tower??e.meta.modes?.tower}:e.meta.modes,i=t.agent!==void 0?{...e.meta.agent,...t.agent}:e.meta.agent,o={goal:t.goal===null?void 0:t.goal??e.meta.goal,activity:t.activity??e.meta.activity,modes:n!==void 0&&n.plan===void 0&&n.swarm===void 0&&n.tower===void 0?void 0:n,agent:i};return o.goal===e.meta.goal&&o.activity===e.meta.activity&&o.modes===e.meta.modes&&o.agent===e.meta.agent?{state:e,changed:!1}:{state:{...e,meta:o},changed:!0}}class t3e{constructor(t){this.agentId=t}#e=L4e;#t=new Set;receive(t){return this.apply(t)}apply(t){const n=[];let i,o=this.#e;for(const s of t){const r=N4e(o,s);if(r.gap){i={target:s.target,...r.gap};continue}r.changed&&(o=r.state,n.push(s))}if(this.#e=o,n.length>0){const s={agentId:this.agentId,ops:n};for(const r of this.#t)r(s)}return{accepted:n,gap:i}}onChange(t){return this.#t.add(t),{dispose:()=>void this.#t.delete(t)}}getItems(){return this.#e.items}getTurn(t){const n=this.#e.items.find(i=>i.kind==="turn"&&i.turnId===t);return n?.kind==="turn"?n:void 0}getTasks(){return this.#e.tasks}getTask(t){return this.#e.tasks.get(t)}getInteractions(){return this.#e.interactions}getInteraction(t){return this.#e.interactions.get(t)}getAttachments(){return this.#e.attachments}getAttachment(t){return this.#e.attachments.get(t)}getTodos(){return this.#e.todos}getTodo(t){return this.#e.todos.get(t)}getPrompts(){return this.#e.prompts}getPrompt(t){return this.#e.prompts.get(t)}getMeta(){return this.#e.meta}listPendingInteractions(){return[...this.#e.pendingInteractions]}get hasMoreOlder(){return this.#e.hasMoreOlder}snapshot(t){let n=this.#e.items,i=this.#e.hasMoreOlder;if(t!==void 0){const o=n.reduce((s,r)=>r.kind==="turn"?s+1:s,0);if(o>t.tailTurns){const s=o-t.tailTurns,r=[];let l=0;for(const a of n)if(a.kind==="turn"){if(l+=1,l<=s)continue;r.push(a)}else l>s&&r.push(a);n=r,i=!0}}return{items:n,tasks:[...this.#e.tasks.values()],interactions:[...this.#e.interactions.values()],attachments:[...this.#e.attachments.values()],todos:[...this.#e.todos.values()],prompts:[...this.#e.prompts.values()],meta:this.#e.meta,hasMoreOlder:i}}}function Pt(e,t,n){function i(l,a){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:a,constr:r,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,a);const u=r.prototype,c=Object.keys(u);for(let d=0;dn?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(r,"name",{value:e}),r}class Q1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Fq extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Rq={};function bf(e){return Rq}function Oq(e){const t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,o])=>t.indexOf(+i)===-1).map(([i,o])=>o)}function NA(e,t){return typeof t=="bigint"?t.toString():t}function R4(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Px(e){return e==null}function $x(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function n3e(e,t){const n=(e.toString().split(".")[1]||"").length,i=t.toString();let o=(i.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(i)){const a=i.match(/\d?e-(\d?)/);a?.[1]&&(o=Number.parseInt(a[1]))}const s=n>o?n:o,r=Number.parseInt(e.toFixed(s).replace(".","")),l=Number.parseInt(t.toFixed(s).replace(".",""));return r%l/10**s}const jD=Symbol("evaluating");function Zi(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==jD)return i===void 0&&(i=jD,i=n()),i},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function bp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Rf(...e){const t={};for(const n of e){const i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function HD(e){return JSON.stringify(e)}function i3e(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Pq="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Tv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const o3e=R4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function fm(e){if(Tv(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Tv(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function $q(e){return fm(e)?{...e}:Array.isArray(e)?[...e]:e}const s3e=new Set(["string","number","symbol"]);function hm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Of(e,t,n){const i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function On(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function r3e(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const l3e={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function a3e(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=Rf(e._zod.def,{get shape(){const r={};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(r[l]=n.shape[l])}return bp(this,"shape",r),r},checks:[]});return Of(e,s)}function u3e(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=Rf(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&delete r[l]}return bp(this,"shape",r),r},checks:[]});return Of(e,s)}function c3e(e,t){if(!fm(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const s=e._zod.def.shape;for(const r in t)if(Object.getOwnPropertyDescriptor(s,r)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=Rf(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return bp(this,"shape",s),s}});return Of(e,o)}function d3e(e,t){if(!fm(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Rf(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return bp(this,"shape",i),i}});return Of(e,n)}function f3e(e,t){const n=Rf(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t._zod.def.shape};return bp(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return Of(e,n)}function h3e(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const r=Rf(t._zod.def,{get shape(){const l=t._zod.def.shape,a={...l};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(a[u]=e?new e({type:"optional",innerType:l[u]}):l[u])}else for(const u in l)a[u]=e?new e({type:"optional",innerType:l[u]}):l[u];return bp(this,"shape",a),a},checks:[]});return Of(t,r)}function p3e(e,t,n){const i=Rf(t._zod.def,{get shape(){const o=t._zod.def.shape,s={...o};if(n)for(const r in n){if(!(r in s))throw new Error(`Unrecognized key: "${r}"`);n[r]&&(s[r]=new e({type:"nonoptional",innerType:o[r]}))}else for(const r in o)s[r]=new e({type:"nonoptional",innerType:o[r]});return bp(this,"shape",s),s}});return Of(t,i)}function S1(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Ly(e){return typeof e=="string"?e:e?.message}function wf(e,t,n){const i={...e,path:e.path??[]};if(!e.message){const o=Ly(e.inst?._zod.def?.error?.(e))??Ly(t?.error?.(e))??Ly(n.customError?.(e))??Ly(n.localeError?.(e))??"Invalid input";i.message=o}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Bx(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ev(...e){const[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}const Bq=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,NA,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},zq=Pt("$ZodError",Bq),jq=Pt("$ZodError",Bq,{Parent:Error});function m3e(e,t=n=>n.message){const n={},i=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):i.push(t(o));return{formErrors:i,fieldErrors:n}}function g3e(e,t=n=>n.message){const n={_errors:[]},i=o=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(r=>i({issues:r}));else if(s.code==="invalid_key")i({issues:s.issues});else if(s.code==="invalid_element")i({issues:s.issues});else if(s.path.length===0)n._errors.push(t(s));else{let r=n,l=0;for(;l(t,n,i,o)=>{const s=i?Object.assign(i,{async:!1}):{async:!1},r=t._zod.run({value:n,issues:[]},s);if(r instanceof Promise)throw new Q1;if(r.issues.length){const l=new(o?.Err??e)(r.issues.map(a=>wf(a,s,bf())));throw Pq(l,o?.callee),l}return r.value},jx=e=>async(t,n,i,o)=>{const s=i?Object.assign(i,{async:!0}):{async:!0};let r=t._zod.run({value:n,issues:[]},s);if(r instanceof Promise&&(r=await r),r.issues.length){const l=new(o?.Err??e)(r.issues.map(a=>wf(a,s,bf())));throw Pq(l,o?.callee),l}return r.value},O4=e=>(t,n,i)=>{const o=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Q1;return s.issues.length?{success:!1,error:new(e??zq)(s.issues.map(r=>wf(r,o,bf())))}:{success:!0,data:s.value}},v3e=O4(jq),P4=e=>async(t,n,i)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(r=>wf(r,o,bf())))}:{success:!0,data:s.value}},y3e=P4(jq),k3e=e=>(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return zx(e)(t,n,o)},b3e=e=>(t,n,i)=>zx(e)(t,n,i),w3e=e=>async(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return jx(e)(t,n,o)},C3e=e=>async(t,n,i)=>jx(e)(t,n,i),A3e=e=>(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return O4(e)(t,n,o)},x3e=e=>(t,n,i)=>O4(e)(t,n,i),S3e=e=>async(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return P4(e)(t,n,o)},_3e=e=>async(t,n,i)=>P4(e)(t,n,i),I3e=/^[cC][^\s-]{8,}$/,M3e=/^[0-9a-z]+$/,T3e=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,E3e=/^[0-9a-vA-V]{20}$/,L3e=/^[A-Za-z0-9]{27}$/,N3e=/^[a-zA-Z0-9_-]{21}$/,D3e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,F3e=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,WD=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,R3e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,O3e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function P3e(){return new RegExp(O3e,"u")}const $3e=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B3e=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,z3e=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,j3e=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,H3e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hq=/^[A-Za-z0-9_-]*$/,W3e=/^\+[1-9]\d{6,14}$/,Wq="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",q3e=new RegExp(`^${Wq}$`);function qq(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function U3e(e){return new RegExp(`^${qq(e)}$`)}function V3e(e){const t=qq({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${Wq}T(?:${i})$`)}const K3e=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Z3e=/^-?\d+$/,Uq=/^-?\d+(?:\.\d+)?$/,G3e=/^(?:true|false)$/i,Q3e=/^[^A-Z]*$/,Y3e=/^[^a-z]*$/,Xl=Pt("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Vq={number:"number",bigint:"bigint",object:"date"},Kq=Pt("$ZodCheckLessThan",(e,t)=>{Xl.init(e,t);const n=Vq[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?i.value<=t.value:i.value{Xl.init(e,t);const n=Vq[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),J3e=Pt("$ZodCheckMultipleOf",(e,t)=>{Xl.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):n3e(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),X3e=Pt("$ZodCheckNumberFormat",(e,t)=>{Xl.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[o,s]=l3e[t.format];e._zod.onattach.push(r=>{const l=r._zod.bag;l.format=t.format,l.minimum=o,l.maximum=s,n&&(l.pattern=Z3e)}),e._zod.check=r=>{const l=r.value;if(n){if(!Number.isInteger(l)){r.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?r.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort}):r.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}ls&&r.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),e8e=Pt("$ZodCheckMaxLength",(e,t)=>{var n;Xl.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!Px(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const o=i.value;if(o.length<=t.maximum)return;const r=Bx(o);i.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),t8e=Pt("$ZodCheckMinLength",(e,t)=>{var n;Xl.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!Px(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const o=i.value;if(o.length>=t.minimum)return;const r=Bx(o);i.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),n8e=Pt("$ZodCheckLengthEquals",(e,t)=>{var n;Xl.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!Px(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=i=>{const o=i.value,s=o.length;if(s===t.length)return;const r=Bx(o),l=s>t.length;i.issues.push({origin:r,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),$4=Pt("$ZodCheckStringFormat",(e,t)=>{var n,i;Xl.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),i8e=Pt("$ZodCheckRegex",(e,t)=>{$4.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),o8e=Pt("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Q3e),$4.init(e,t)}),s8e=Pt("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Y3e),$4.init(e,t)}),r8e=Pt("$ZodCheckIncludes",(e,t)=>{Xl.init(e,t);const n=hm(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(i)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),l8e=Pt("$ZodCheckStartsWith",(e,t)=>{Xl.init(e,t);const n=new RegExp(`^${hm(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),a8e=Pt("$ZodCheckEndsWith",(e,t)=>{Xl.init(e,t);const n=new RegExp(`.*${hm(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}}),u8e=Pt("$ZodCheckOverwrite",(e,t)=>{Xl.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class c8e{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const i=t.split(` -`).filter(r=>r),o=Math.min(...i.map(r=>r.length-r.trimStart().length)),s=i.map(r=>r.slice(o)).map(r=>" ".repeat(this.indent*2)+r);for(const r of s)this.content.push(r)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(` -`))}}const d8e={major:4,minor:3,patch:6},rs=Pt("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=d8e;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const o of i)for(const s of o._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(r,l,a)=>{let u=S1(r),c;for(const d of l){if(d._zod.def.when){if(!d._zod.def.when(r))continue}else if(u)continue;const h=r.issues.length,p=d._zod.check(r);if(p instanceof Promise&&a?.async===!1)throw new Q1;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,r.issues.length!==h&&(u||(u=S1(r,h)))});else{if(r.issues.length===h)continue;u||(u=S1(r,h))}}return c?c.then(()=>r):r},s=(r,l,a)=>{if(S1(r))return r.aborted=!0,r;const u=o(l,i,a);if(u instanceof Promise){if(a.async===!1)throw new Q1;return u.then(c=>e._zod.parse(c,a))}return e._zod.parse(u,a)};e._zod.run=(r,l)=>{if(l.skipChecks)return e._zod.parse(r,l);if(l.direction==="backward"){const u=e._zod.parse({value:r.value,issues:[]},{...l,skipChecks:!0});return u instanceof Promise?u.then(c=>s(c,r,l)):s(u,r,l)}const a=e._zod.parse(r,l);if(a instanceof Promise){if(l.async===!1)throw new Q1;return a.then(u=>o(u,i,l))}return o(a,i,l)}}Zi(e,"~standard",()=>({validate:o=>{try{const s=v3e(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return y3e(e,o).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}))}),Hx=Pt("$ZodString",(e,t)=>{rs.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??K3e(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ko=Pt("$ZodStringFormat",(e,t)=>{$4.init(e,t),Hx.init(e,t)}),f8e=Pt("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=F3e),Ko.init(e,t)}),h8e=Pt("$ZodUUID",(e,t)=>{if(t.version){const i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=WD(i))}else t.pattern??(t.pattern=WD());Ko.init(e,t)}),p8e=Pt("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=R3e),Ko.init(e,t)}),m8e=Pt("$ZodURL",(e,t)=>{Ko.init(e,t),e._zod.check=n=>{try{const i=n.value.trim(),o=new URL(i);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),g8e=Pt("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=P3e()),Ko.init(e,t)}),v8e=Pt("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=N3e),Ko.init(e,t)}),y8e=Pt("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=I3e),Ko.init(e,t)}),k8e=Pt("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=M3e),Ko.init(e,t)}),b8e=Pt("$ZodULID",(e,t)=>{t.pattern??(t.pattern=T3e),Ko.init(e,t)}),w8e=Pt("$ZodXID",(e,t)=>{t.pattern??(t.pattern=E3e),Ko.init(e,t)}),C8e=Pt("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=L3e),Ko.init(e,t)}),A8e=Pt("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=V3e(t)),Ko.init(e,t)}),x8e=Pt("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=q3e),Ko.init(e,t)}),S8e=Pt("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=U3e(t)),Ko.init(e,t)}),_8e=Pt("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=D3e),Ko.init(e,t)}),I8e=Pt("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$3e),Ko.init(e,t),e._zod.bag.format="ipv4"}),M8e=Pt("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=B3e),Ko.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),T8e=Pt("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=z3e),Ko.init(e,t)}),E8e=Pt("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=j3e),Ko.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(i.length!==2)throw new Error;const[o,s]=i;if(!s)throw new Error;const r=Number(s);if(`${r}`!==s)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Gq(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const L8e=Pt("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=H3e),Ko.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Gq(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function N8e(e){if(!Hq.test(e))return!1;const t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Gq(n)}const D8e=Pt("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Hq),Ko.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{N8e(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),F8e=Pt("$ZodE164",(e,t)=>{t.pattern??(t.pattern=W3e),Ko.init(e,t)});function R8e(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[i]=n;if(!i)return!1;const o=JSON.parse(atob(i));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const O8e=Pt("$ZodJWT",(e,t)=>{Ko.init(e,t),e._zod.check=n=>{R8e(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Qq=Pt("$ZodNumber",(e,t)=>{rs.init(e,t),e._zod.pattern=e._zod.bag.pattern??Uq,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),P8e=Pt("$ZodNumberFormat",(e,t)=>{X3e.init(e,t),Qq.init(e,t)}),$8e=Pt("$ZodBoolean",(e,t)=>{rs.init(e,t),e._zod.pattern=G3e,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),B8e=Pt("$ZodUnknown",(e,t)=>{rs.init(e,t),e._zod.parse=n=>n}),z8e=Pt("$ZodNever",(e,t)=>{rs.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function qD(e,t,n){e.issues.length&&t.issues.push(..._1(n,e.issues)),t.value[n]=e.value}const j8e=Pt("$ZodArray",(e,t)=>{rs.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let r=0;rqD(u,n,r))):qD(a,n,r)}return s.length?Promise.all(s).then(()=>n):n}});function sb(e,t,n,i,o){if(e.issues.length){if(o&&!(n in i))return;t.issues.push(..._1(n,e.issues))}e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function Yq(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=r3e(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Jq(e,t,n,i,o,s){const r=[],l=o.keySet,a=o.catchall._zod,u=a.def.type,c=a.optout==="optional";for(const d in t){if(l.has(d))continue;if(u==="never"){r.push(d);continue}const h=a.run({value:t[d],issues:[]},i);h instanceof Promise?e.push(h.then(p=>sb(p,n,d,t,c))):sb(h,n,d,t,c)}return r.length&&n.issues.push({code:"unrecognized_keys",keys:r,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}const H8e=Pt("$ZodObject",(e,t)=>{if(rs.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const a={...l};return Object.defineProperty(t,"shape",{value:a}),a}})}const i=R4(()=>Yq(t));Zi(e._zod,"propValues",()=>{const l=t.shape,a={};for(const u in l){const c=l[u]._zod;if(c.values){a[u]??(a[u]=new Set);for(const d of c.values)a[u].add(d)}}return a});const o=Tv,s=t.catchall;let r;e._zod.parse=(l,a)=>{r??(r=i.value);const u=l.value;if(!o(u))return l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l;l.value={};const c=[],d=r.shape;for(const h of r.keys){const p=d[h],m=p._zod.optout==="optional",g=p._zod.run({value:u[h],issues:[]},a);g instanceof Promise?c.push(g.then(y=>sb(y,l,h,u,m))):sb(g,l,h,u,m)}return s?Jq(c,u,l,a,i.value,e):c.length?Promise.all(c).then(()=>l):l}}),W8e=Pt("$ZodObjectJIT",(e,t)=>{H8e.init(e,t);const n=e._zod.parse,i=R4(()=>Yq(t)),o=h=>{const p=new c8e(["shape","payload","ctx"]),m=i.value,g=C=>{const w=HD(C);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let b=0;for(const C of m.keys)y[C]=`key_${b++}`;p.write("const newResult = {};");for(const C of m.keys){const w=y[C],M=HD(C),T=h[C]?._zod?.optout==="optional";p.write(`const ${w} = ${g(C)};`),T?p.write(` - if (${w}.issues.length) { - if (${M} in input) { - payload.issues = payload.issues.concat(${w}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${M}, ...iss.path] : [${M}] - }))); - } - } - - if (${w}.value === undefined) { - if (${M} in input) { - newResult[${M}] = undefined; - } - } else { - newResult[${M}] = ${w}.value; - } - - `):p.write(` - if (${w}.issues.length) { - payload.issues = payload.issues.concat(${w}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${M}, ...iss.path] : [${M}] - }))); - } - - if (${w}.value === undefined) { - if (${M} in input) { - newResult[${M}] = undefined; - } - } else { - newResult[${M}] = ${w}.value; - } - - `)}p.write("payload.value = newResult;"),p.write("return payload;");const v=p.compile();return(C,w)=>v(h,C,w)};let s;const r=Tv,l=!Rq.jitless,u=l&&o3e.value,c=t.catchall;let d;e._zod.parse=(h,p)=>{d??(d=i.value);const m=h.value;return r(m)?l&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(t.shape)),h=s(h,p),c?Jq([],m,h,p,d,e):h):n(h,p):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h)}});function UD(e,t,n,i){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const o=e.filter(s=>!S1(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(r=>wf(r,i,bf())))}),t)}const Xq=Pt("$ZodUnion",(e,t)=>{rs.init(e,t),Zi(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Zi(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Zi(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Zi(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>$x(s.source)).join("|")})$`)}});const n=t.options.length===1,i=t.options[0]._zod.run;e._zod.parse=(o,s)=>{if(n)return i(o,s);let r=!1;const l=[];for(const a of t.options){const u=a._zod.run({value:o.value,issues:[]},s);if(u instanceof Promise)l.push(u),r=!0;else{if(u.issues.length===0)return u;l.push(u)}}return r?Promise.all(l).then(a=>UD(a,o,e,s)):UD(l,o,e,s)}}),q8e=Pt("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Xq.init(e,t);const n=e._zod.parse;Zi(e._zod,"propValues",()=>{const o={};for(const s of t.options){const r=s._zod.propValues;if(!r||Object.keys(r).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[l,a]of Object.entries(r)){o[l]||(o[l]=new Set);for(const u of a)o[l].add(u)}}return o});const i=R4(()=>{const o=t.options,s=new Map;for(const r of o){const l=r._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const a of l){if(s.has(a))throw new Error(`Duplicate discriminator value "${String(a)}"`);s.set(a,r)}}return s});e._zod.parse=(o,s)=>{const r=o.value;if(!Tv(r))return o.issues.push({code:"invalid_type",expected:"object",input:r,inst:e}),o;const l=i.value.get(r?.[t.discriminator]);return l?l._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:r,path:[t.discriminator],inst:e}),o)}}),U8e=Pt("$ZodIntersection",(e,t)=>{rs.init(e,t),e._zod.parse=(n,i)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},i),r=t.right._zod.run({value:o,issues:[]},i);return s instanceof Promise||r instanceof Promise?Promise.all([s,r]).then(([a,u])=>VD(n,a,u)):VD(n,s,r)}});function DA(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(fm(e)&&fm(t)){const n=Object.keys(t),i=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of i){const r=DA(e[s],t[s]);if(!r.valid)return{valid:!1,mergeErrorPath:[s,...r.mergeErrorPath]};o[s]=r.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;il.l&&l.r).map(([l])=>l);if(s.length&&o&&e.issues.push({...o,keys:s}),S1(e))return e;const r=DA(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const V8e=Pt("$ZodRecord",(e,t)=>{rs.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!fm(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[],r=t.keyType._zod.values;if(r){n.value={};const l=new Set;for(const u of r)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){l.add(typeof u=="number"?u.toString():u);const c=t.valueType._zod.run({value:o[u],issues:[]},i);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(..._1(u,d.issues)),n.value[u]=d.value})):(c.issues.length&&n.issues.push(..._1(u,c.issues)),n.value[u]=c.value)}let a;for(const u in o)l.has(u)||(a=a??[],a.push(u));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.value={};for(const l of Reflect.ownKeys(o)){if(l==="__proto__")continue;let a=t.keyType._zod.run({value:l,issues:[]},i);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&Uq.test(l)&&a.issues.length){const d=t.keyType._zod.run({value:Number(l),issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(a=d)}if(a.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(d=>wf(d,i,bf())),input:l,path:[l],inst:e});continue}const c=t.valueType._zod.run({value:o[l],issues:[]},i);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(..._1(l,d.issues)),n.value[a.value]=d.value})):(c.issues.length&&n.issues.push(..._1(l,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),K8e=Pt("$ZodEnum",(e,t)=>{rs.init(e,t);const n=Oq(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(o=>s3e.has(typeof o)).map(o=>typeof o=="string"?hm(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{const r=o.value;return i.has(r)||o.issues.push({code:"invalid_value",values:n,input:r,inst:e}),o}}),Z8e=Pt("$ZodLiteral",(e,t)=>{if(rs.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(i=>typeof i=="string"?hm(i):i?hm(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,o)=>{const s=i.value;return n.has(s)||i.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),i}}),G8e=Pt("$ZodTransform",(e,t)=>{rs.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Fq(e.constructor.name);const o=t.transform(n.value,n);if(i.async)return(o instanceof Promise?o:Promise.resolve(o)).then(r=>(n.value=r,n));if(o instanceof Promise)throw new Q1;return n.value=o,n}});function KD(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const eU=Pt("$ZodOptional",(e,t)=>{rs.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Zi(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Zi(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${$x(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>KD(s,n.value)):KD(o,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,i)}}),Q8e=Pt("$ZodExactOptional",(e,t)=>{eU.init(e,t),Zi(e._zod,"values",()=>t.innerType._zod.values),Zi(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),Y8e=Pt("$ZodNullable",(e,t)=>{rs.init(e,t),Zi(e._zod,"optin",()=>t.innerType._zod.optin),Zi(e._zod,"optout",()=>t.innerType._zod.optout),Zi(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${$x(n.source)}|null)$`):void 0}),Zi(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>n.value===null?n:t.innerType._zod.run(n,i)}),J8e=Pt("$ZodDefault",(e,t)=>{rs.init(e,t),e._zod.optin="optional",Zi(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>ZD(s,t)):ZD(o,t)}});function ZD(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const X8e=Pt("$ZodPrefault",(e,t)=>{rs.init(e,t),e._zod.optin="optional",Zi(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>(i.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,i))}),ewe=Pt("$ZodNonOptional",(e,t)=>{rs.init(e,t),Zi(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>GD(s,e)):GD(o,e)}});function GD(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const twe=Pt("$ZodCatch",(e,t)=>{rs.init(e,t),Zi(e._zod,"optin",()=>t.innerType._zod.optin),Zi(e._zod,"optout",()=>t.innerType._zod.optout),Zi(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(r=>wf(r,i,bf()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>wf(s,i,bf()))},input:n.value}),n.issues=[]),n)}}),nwe=Pt("$ZodPipe",(e,t)=>{rs.init(e,t),Zi(e._zod,"values",()=>t.in._zod.values),Zi(e._zod,"optin",()=>t.in._zod.optin),Zi(e._zod,"optout",()=>t.out._zod.optout),Zi(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){const s=t.out._zod.run(n,i);return s instanceof Promise?s.then(r=>Ny(r,t.in,i)):Ny(s,t.in,i)}const o=t.in._zod.run(n,i);return o instanceof Promise?o.then(s=>Ny(s,t.out,i)):Ny(o,t.out,i)}});function Ny(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const iwe=Pt("$ZodReadonly",(e,t)=>{rs.init(e,t),Zi(e._zod,"propValues",()=>t.innerType._zod.propValues),Zi(e._zod,"values",()=>t.innerType._zod.values),Zi(e._zod,"optin",()=>t.innerType?._zod?.optin),Zi(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(QD):QD(o)}});function QD(e){return e.value=Object.freeze(e.value),e}const owe=Pt("$ZodCustom",(e,t)=>{Xl.init(e,t),rs.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=n=>{const i=n.value,o=t.fn(i);if(o instanceof Promise)return o.then(s=>YD(s,n,i,e));YD(o,n,i,e)}});function YD(e,t,n,i){if(!e){const o={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(o.params=i._zod.def.params),t.issues.push(Ev(o))}}var JD;class swe{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const i=n[0];return this._map.set(t,i),i&&typeof i=="object"&&"id"in i&&this._idmap.set(i.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const i={...this.get(n)??{}};delete i.id;const o={...i,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function rwe(){return new swe}(JD=globalThis).__zod_globalRegistry??(JD.__zod_globalRegistry=rwe());const o0=globalThis.__zod_globalRegistry;function lwe(e,t){return new e({type:"string",...On(t)})}function awe(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...On(t)})}function XD(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...On(t)})}function uwe(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...On(t)})}function cwe(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...On(t)})}function dwe(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...On(t)})}function fwe(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...On(t)})}function hwe(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...On(t)})}function pwe(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...On(t)})}function mwe(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...On(t)})}function gwe(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...On(t)})}function vwe(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...On(t)})}function ywe(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...On(t)})}function kwe(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...On(t)})}function bwe(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...On(t)})}function wwe(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...On(t)})}function Cwe(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...On(t)})}function Awe(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...On(t)})}function xwe(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...On(t)})}function Swe(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...On(t)})}function _we(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...On(t)})}function Iwe(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...On(t)})}function Mwe(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...On(t)})}function Twe(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...On(t)})}function Ewe(e,t){return new e({type:"string",format:"date",check:"string_format",...On(t)})}function Lwe(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...On(t)})}function Nwe(e,t){return new e({type:"string",format:"duration",check:"string_format",...On(t)})}function Dwe(e,t){return new e({type:"number",checks:[],...On(t)})}function Fwe(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...On(t)})}function Rwe(e,t){return new e({type:"boolean",...On(t)})}function Owe(e){return new e({type:"unknown"})}function Pwe(e,t){return new e({type:"never",...On(t)})}function eF(e,t){return new Kq({check:"less_than",...On(t),value:e,inclusive:!1})}function pw(e,t){return new Kq({check:"less_than",...On(t),value:e,inclusive:!0})}function tF(e,t){return new Zq({check:"greater_than",...On(t),value:e,inclusive:!1})}function mw(e,t){return new Zq({check:"greater_than",...On(t),value:e,inclusive:!0})}function nF(e,t){return new J3e({check:"multiple_of",...On(t),value:e})}function tU(e,t){return new e8e({check:"max_length",...On(t),maximum:e})}function rb(e,t){return new t8e({check:"min_length",...On(t),minimum:e})}function nU(e,t){return new n8e({check:"length_equals",...On(t),length:e})}function $we(e,t){return new i8e({check:"string_format",format:"regex",...On(t),pattern:e})}function Bwe(e){return new o8e({check:"string_format",format:"lowercase",...On(e)})}function zwe(e){return new s8e({check:"string_format",format:"uppercase",...On(e)})}function jwe(e,t){return new r8e({check:"string_format",format:"includes",...On(t),includes:e})}function Hwe(e,t){return new l8e({check:"string_format",format:"starts_with",...On(t),prefix:e})}function Wwe(e,t){return new a8e({check:"string_format",format:"ends_with",...On(t),suffix:e})}function zm(e){return new u8e({check:"overwrite",tx:e})}function qwe(e){return zm(t=>t.normalize(e))}function Uwe(){return zm(e=>e.trim())}function Vwe(){return zm(e=>e.toLowerCase())}function Kwe(){return zm(e=>e.toUpperCase())}function Zwe(){return zm(e=>i3e(e))}function Gwe(e,t,n){return new e({type:"array",element:t,...On(n)})}function Qwe(e,t,n){return new e({type:"custom",check:"custom",fn:t,...On(n)})}function Ywe(e){const t=Jwe(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(Ev(i,n.value,t._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(Ev(o))}},e(n.value,n)));return t}function Jwe(e,t){const n=new Xl({check:"custom",...On(t)});return n._zod.check=e,n}function iU(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??o0,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Us(e,t,n={path:[],schemaPath:[]}){var i;const o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const r={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,r);const l=e._zod.toJSONSchema?.();if(l)r.schema=l;else{const c={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,r.schema,c);else{const h=r.schema,p=t.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(e,t,h,c)}const d=e._zod.parent;d&&(r.ref||(r.ref=d),Us(d,t,c),t.seen.get(d).isParent=!0)}const a=t.metadataRegistry.get(e);return a&&Object.assign(r.schema,a),t.io==="input"&&dl(e)&&(delete r.schema.examples,delete r.schema.default),t.io==="input"&&r.schema._prefault&&((i=r.schema).default??(i.default=r.schema._prefault)),delete r.schema._prefault,t.seen.get(e).schema}function oU(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=new Map;for(const r of e.seen.entries()){const l=e.metadataRegistry.get(r[0])?.id;if(l){const a=i.get(l);if(a&&a!==r[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(l,r[0])}}const o=r=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(r[0])?.id,h=e.external.uri??(m=>m);if(d)return{ref:h(d)};const p=r[1].defId??r[1].schema.id??`schema${e.counter++}`;return r[1].defId=p,{defId:p,ref:`${h("__shared")}#/${l}/${p}`}}if(r[1]===n)return{ref:"#"};const u=`#/${l}/`,c=r[1].schema.id??`__schema${e.counter++}`;return{defId:c,ref:u+c}},s=r=>{if(r[1].schema.$ref)return;const l=r[1],{ref:a,defId:u}=o(r);l.def={...l.schema},u&&(l.defId=u);const c=l.schema;for(const d in c)delete c[d];c.$ref=a};if(e.cycles==="throw")for(const r of e.seen.entries()){const l=r[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const r of e.seen.entries()){const l=r[1];if(t===r[0]){s(r);continue}if(e.external){const u=e.external.registry.get(r[0])?.id;if(t!==r[0]&&u){s(r);continue}}if(e.metadataRegistry.get(r[0])?.id){s(r);continue}if(l.cycle){s(r);continue}if(l.count>1&&e.reused==="ref"){s(r);continue}}}function sU(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=r=>{const l=e.seen.get(r);if(l.ref===null)return;const a=l.def??l.schema,u={...a},c=l.ref;if(l.ref=null,c){i(c);const h=e.seen.get(c),p=h.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(a.allOf=a.allOf??[],a.allOf.push(p)):Object.assign(a,p),Object.assign(a,u),r._zod.parent===c)for(const g in a)g==="$ref"||g==="allOf"||g in u||delete a[g];if(p.$ref&&h.def)for(const g in a)g==="$ref"||g==="allOf"||g in h.def&&JSON.stringify(a[g])===JSON.stringify(h.def[g])&&delete a[g]}const d=r._zod.parent;if(d&&d!==c){i(d);const h=e.seen.get(d);if(h?.schema.$ref&&(a.$ref=h.schema.$ref,h.def))for(const p in a)p==="$ref"||p==="allOf"||p in h.def&&JSON.stringify(a[p])===JSON.stringify(h.def[p])&&delete a[p]}e.override({zodSchema:r,jsonSchema:a,path:l.path??[]})};for(const r of[...e.seen.entries()].reverse())i(r[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const r=e.external.registry.get(t)?.id;if(!r)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(r)}Object.assign(o,n.def??n.schema);const s=e.external?.defs??{};for(const r of e.seen.entries()){const l=r[1];l.def&&l.defId&&(s[l.defId]=l.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const r=JSON.parse(JSON.stringify(o));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:lb(t,"input",e.processors),output:lb(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch{throw new Error("Error converting schema to JSON.")}}function dl(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return dl(i.element,n);if(i.type==="set")return dl(i.valueType,n);if(i.type==="lazy")return dl(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return dl(i.innerType,n);if(i.type==="intersection")return dl(i.left,n)||dl(i.right,n);if(i.type==="record"||i.type==="map")return dl(i.keyType,n)||dl(i.valueType,n);if(i.type==="pipe")return dl(i.in,n)||dl(i.out,n);if(i.type==="object"){for(const o in i.shape)if(dl(i.shape[o],n))return!0;return!1}if(i.type==="union"){for(const o of i.options)if(dl(o,n))return!0;return!1}if(i.type==="tuple"){for(const o of i.items)if(dl(o,n))return!0;return!!(i.rest&&dl(i.rest,n))}return!1}const Xwe=(e,t={})=>n=>{const i=iU({...n,processors:t});return Us(e,i),oU(i,e),sU(i,e)},lb=(e,t,n={})=>i=>{const{libraryOptions:o,target:s}=i??{},r=iU({...o??{},target:s,io:t,processors:n});return Us(e,r),oU(r,e),sU(r,e)},e5e={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},t5e=(e,t,n,i)=>{const o=n;o.type="string";const{minimum:s,maximum:r,format:l,patterns:a,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof r=="number"&&(o.maxLength=r),l&&(o.format=e5e[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),u&&(o.contentEncoding=u),a&&a.size>0){const c=[...a];c.length===1?o.pattern=c[0].source:c.length>1&&(o.allOf=[...c.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},n5e=(e,t,n,i)=>{const o=n,{minimum:s,maximum:r,format:l,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.type="number",typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=c,o.exclusiveMinimum=!0):o.exclusiveMinimum=c),typeof s=="number"&&(o.minimum=s,typeof c=="number"&&t.target!=="draft-04"&&(c>=s?delete o.minimum:delete o.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u),typeof r=="number"&&(o.maximum=r,typeof u=="number"&&t.target!=="draft-04"&&(u<=r?delete o.maximum:delete o.exclusiveMaximum)),typeof a=="number"&&(o.multipleOf=a)},i5e=(e,t,n,i)=>{n.type="boolean"},o5e=(e,t,n,i)=>{n.not={}},s5e=(e,t,n,i)=>{},r5e=(e,t,n,i)=>{const o=e._zod.def,s=Oq(o.entries);s.every(r=>typeof r=="number")&&(n.type="number"),s.every(r=>typeof r=="string")&&(n.type="string"),n.enum=s},l5e=(e,t,n,i)=>{const o=e._zod.def,s=[];for(const r of o.values)if(r===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof r=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(r))}else s.push(r);if(s.length!==0)if(s.length===1){const r=s[0];n.type=r===null?"null":typeof r,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[r]:n.const=r}else s.every(r=>typeof r=="number")&&(n.type="number"),s.every(r=>typeof r=="string")&&(n.type="string"),s.every(r=>typeof r=="boolean")&&(n.type="boolean"),s.every(r=>r===null)&&(n.type="null"),n.enum=s},a5e=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},u5e=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},c5e=(e,t,n,i)=>{const o=n,s=e._zod.def,{minimum:r,maximum:l}=e._zod.bag;typeof r=="number"&&(o.minItems=r),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=Us(s.element,t,{...i,path:[...i.path,"items"]})},d5e=(e,t,n,i)=>{const o=n,s=e._zod.def;o.type="object",o.properties={};const r=s.shape;for(const u in r)o.properties[u]=Us(r[u],t,{...i,path:[...i.path,"properties",u]});const l=new Set(Object.keys(r)),a=new Set([...l].filter(u=>{const c=s.shape[u]._zod;return t.io==="input"?c.optin===void 0:c.optout===void 0}));a.size>0&&(o.required=Array.from(a)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=Us(s.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},f5e=(e,t,n,i)=>{const o=e._zod.def,s=o.inclusive===!1,r=o.options.map((l,a)=>Us(l,t,{...i,path:[...i.path,s?"oneOf":"anyOf",a]}));s?n.oneOf=r:n.anyOf=r},h5e=(e,t,n,i)=>{const o=e._zod.def,s=Us(o.left,t,{...i,path:[...i.path,"allOf",0]}),r=Us(o.right,t,{...i,path:[...i.path,"allOf",1]}),l=u=>"allOf"in u&&Object.keys(u).length===1,a=[...l(s)?s.allOf:[s],...l(r)?r.allOf:[r]];n.allOf=a},p5e=(e,t,n,i)=>{const o=n,s=e._zod.def;o.type="object";const r=s.keyType,a=r._zod.bag?.patterns;if(s.mode==="loose"&&a&&a.size>0){const c=Us(s.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});o.patternProperties={};for(const d of a)o.patternProperties[d.source]=c}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=Us(s.keyType,t,{...i,path:[...i.path,"propertyNames"]})),o.additionalProperties=Us(s.valueType,t,{...i,path:[...i.path,"additionalProperties"]});const u=r._zod.values;if(u){const c=[...u].filter(d=>typeof d=="string"||typeof d=="number");c.length>0&&(o.required=c)}},m5e=(e,t,n,i)=>{const o=e._zod.def,s=Us(o.innerType,t,i),r=t.seen.get(e);t.target==="openapi-3.0"?(r.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},g5e=(e,t,n,i)=>{const o=e._zod.def;Us(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType},v5e=(e,t,n,i)=>{const o=e._zod.def;Us(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},y5e=(e,t,n,i)=>{const o=e._zod.def;Us(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},k5e=(e,t,n,i)=>{const o=e._zod.def;Us(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType;let r;try{r=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=r},b5e=(e,t,n,i)=>{const o=e._zod.def,s=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Us(s,t,i);const r=t.seen.get(e);r.ref=s},w5e=(e,t,n,i)=>{const o=e._zod.def;Us(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0},rU=(e,t,n,i)=>{const o=e._zod.def;Us(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType},C5e=Pt("ZodISODateTime",(e,t)=>{A8e.init(e,t),as.init(e,t)});function A5e(e){return Twe(C5e,e)}const x5e=Pt("ZodISODate",(e,t)=>{x8e.init(e,t),as.init(e,t)});function S5e(e){return Ewe(x5e,e)}const _5e=Pt("ZodISOTime",(e,t)=>{S8e.init(e,t),as.init(e,t)});function I5e(e){return Lwe(_5e,e)}const M5e=Pt("ZodISODuration",(e,t)=>{_8e.init(e,t),as.init(e,t)});function T5e(e){return Nwe(M5e,e)}const E5e=(e,t)=>{zq.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>g3e(e,n)},flatten:{value:n=>m3e(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,NA,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,NA,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ya=Pt("ZodError",E5e,{Parent:Error}),L5e=zx(Ya),N5e=jx(Ya),D5e=O4(Ya),F5e=P4(Ya),R5e=k3e(Ya),O5e=b3e(Ya),P5e=w3e(Ya),$5e=C3e(Ya),B5e=A3e(Ya),z5e=x3e(Ya),j5e=S3e(Ya),H5e=_3e(Ya),ls=Pt("ZodType",(e,t)=>(rs.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:lb(e,"input"),output:lb(e,"output")}}),e.toJSONSchema=Xwe(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Rf(t,{checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0}),e.with=e.check,e.clone=(n,i)=>Of(e,n,i),e.brand=()=>e,e.register=((n,i)=>(n.add(e,i),e)),e.parse=(n,i)=>L5e(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>D5e(e,n,i),e.parseAsync=async(n,i)=>N5e(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>F5e(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>R5e(e,n,i),e.decode=(n,i)=>O5e(e,n,i),e.encodeAsync=async(n,i)=>P5e(e,n,i),e.decodeAsync=async(n,i)=>$5e(e,n,i),e.safeEncode=(n,i)=>B5e(e,n,i),e.safeDecode=(n,i)=>z5e(e,n,i),e.safeEncodeAsync=async(n,i)=>j5e(e,n,i),e.safeDecodeAsync=async(n,i)=>H5e(e,n,i),e.refine=(n,i)=>e.check(RCe(n,i)),e.superRefine=n=>e.check(OCe(n)),e.overwrite=n=>e.check(zm(n)),e.optional=()=>sF(e),e.exactOptional=()=>CCe(e),e.nullable=()=>rF(e),e.nullish=()=>sF(rF(e)),e.nonoptional=n=>MCe(e,n),e.array=()=>Si(e),e.or=n=>hCe([e,n]),e.and=n=>gCe(e,n),e.transform=n=>lF(e,bCe(n)),e.default=n=>SCe(e,n),e.prefault=n=>ICe(e,n),e.catch=n=>ECe(e,n),e.pipe=n=>lF(e,n),e.readonly=()=>DCe(e),e.describe=n=>{const i=e.clone();return o0.add(i,{description:n}),i},Object.defineProperty(e,"description",{get(){return o0.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return o0.get(e);const i=e.clone();return o0.add(i,n[0]),i},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),lU=Pt("_ZodString",(e,t)=>{Hx.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(i,o,s)=>t5e(e,i,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...i)=>e.check($we(...i)),e.includes=(...i)=>e.check(jwe(...i)),e.startsWith=(...i)=>e.check(Hwe(...i)),e.endsWith=(...i)=>e.check(Wwe(...i)),e.min=(...i)=>e.check(rb(...i)),e.max=(...i)=>e.check(tU(...i)),e.length=(...i)=>e.check(nU(...i)),e.nonempty=(...i)=>e.check(rb(1,...i)),e.lowercase=i=>e.check(Bwe(i)),e.uppercase=i=>e.check(zwe(i)),e.trim=()=>e.check(Uwe()),e.normalize=(...i)=>e.check(qwe(...i)),e.toLowerCase=()=>e.check(Vwe()),e.toUpperCase=()=>e.check(Kwe()),e.slugify=()=>e.check(Zwe())}),W5e=Pt("ZodString",(e,t)=>{Hx.init(e,t),lU.init(e,t),e.email=n=>e.check(awe(q5e,n)),e.url=n=>e.check(hwe(U5e,n)),e.jwt=n=>e.check(Mwe(rCe,n)),e.emoji=n=>e.check(pwe(V5e,n)),e.guid=n=>e.check(XD(iF,n)),e.uuid=n=>e.check(uwe(Dy,n)),e.uuidv4=n=>e.check(cwe(Dy,n)),e.uuidv6=n=>e.check(dwe(Dy,n)),e.uuidv7=n=>e.check(fwe(Dy,n)),e.nanoid=n=>e.check(mwe(K5e,n)),e.guid=n=>e.check(XD(iF,n)),e.cuid=n=>e.check(gwe(Z5e,n)),e.cuid2=n=>e.check(vwe(G5e,n)),e.ulid=n=>e.check(ywe(Q5e,n)),e.base64=n=>e.check(Swe(iCe,n)),e.base64url=n=>e.check(_we(oCe,n)),e.xid=n=>e.check(kwe(Y5e,n)),e.ksuid=n=>e.check(bwe(J5e,n)),e.ipv4=n=>e.check(wwe(X5e,n)),e.ipv6=n=>e.check(Cwe(eCe,n)),e.cidrv4=n=>e.check(Awe(tCe,n)),e.cidrv6=n=>e.check(xwe(nCe,n)),e.e164=n=>e.check(Iwe(sCe,n)),e.datetime=n=>e.check(A5e(n)),e.date=n=>e.check(S5e(n)),e.time=n=>e.check(I5e(n)),e.duration=n=>e.check(T5e(n))});function Ut(e){return lwe(W5e,e)}const as=Pt("ZodStringFormat",(e,t)=>{Ko.init(e,t),lU.init(e,t)}),q5e=Pt("ZodEmail",(e,t)=>{p8e.init(e,t),as.init(e,t)}),iF=Pt("ZodGUID",(e,t)=>{f8e.init(e,t),as.init(e,t)}),Dy=Pt("ZodUUID",(e,t)=>{h8e.init(e,t),as.init(e,t)}),U5e=Pt("ZodURL",(e,t)=>{m8e.init(e,t),as.init(e,t)}),V5e=Pt("ZodEmoji",(e,t)=>{g8e.init(e,t),as.init(e,t)}),K5e=Pt("ZodNanoID",(e,t)=>{v8e.init(e,t),as.init(e,t)}),Z5e=Pt("ZodCUID",(e,t)=>{y8e.init(e,t),as.init(e,t)}),G5e=Pt("ZodCUID2",(e,t)=>{k8e.init(e,t),as.init(e,t)}),Q5e=Pt("ZodULID",(e,t)=>{b8e.init(e,t),as.init(e,t)}),Y5e=Pt("ZodXID",(e,t)=>{w8e.init(e,t),as.init(e,t)}),J5e=Pt("ZodKSUID",(e,t)=>{C8e.init(e,t),as.init(e,t)}),X5e=Pt("ZodIPv4",(e,t)=>{I8e.init(e,t),as.init(e,t)}),eCe=Pt("ZodIPv6",(e,t)=>{M8e.init(e,t),as.init(e,t)}),tCe=Pt("ZodCIDRv4",(e,t)=>{T8e.init(e,t),as.init(e,t)}),nCe=Pt("ZodCIDRv6",(e,t)=>{E8e.init(e,t),as.init(e,t)}),iCe=Pt("ZodBase64",(e,t)=>{L8e.init(e,t),as.init(e,t)}),oCe=Pt("ZodBase64URL",(e,t)=>{D8e.init(e,t),as.init(e,t)}),sCe=Pt("ZodE164",(e,t)=>{F8e.init(e,t),as.init(e,t)}),rCe=Pt("ZodJWT",(e,t)=>{O8e.init(e,t),as.init(e,t)}),aU=Pt("ZodNumber",(e,t)=>{Qq.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(i,o,s)=>n5e(e,i,o),e.gt=(i,o)=>e.check(tF(i,o)),e.gte=(i,o)=>e.check(mw(i,o)),e.min=(i,o)=>e.check(mw(i,o)),e.lt=(i,o)=>e.check(eF(i,o)),e.lte=(i,o)=>e.check(pw(i,o)),e.max=(i,o)=>e.check(pw(i,o)),e.int=i=>e.check(oF(i)),e.safe=i=>e.check(oF(i)),e.positive=i=>e.check(tF(0,i)),e.nonnegative=i=>e.check(mw(0,i)),e.negative=i=>e.check(eF(0,i)),e.nonpositive=i=>e.check(pw(0,i)),e.multipleOf=(i,o)=>e.check(nF(i,o)),e.step=(i,o)=>e.check(nF(i,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Tn(e){return Dwe(aU,e)}const lCe=Pt("ZodNumberFormat",(e,t)=>{P8e.init(e,t),aU.init(e,t)});function oF(e){return Fwe(lCe,e)}const aCe=Pt("ZodBoolean",(e,t)=>{$8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>i5e(e,n,i)});function u2(e){return Rwe(aCe,e)}const uCe=Pt("ZodUnknown",(e,t)=>{B8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>s5e()});function rr(){return Owe(uCe)}const cCe=Pt("ZodNever",(e,t)=>{z8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>o5e(e,n,i)});function uU(e){return Pwe(cCe,e)}const dCe=Pt("ZodArray",(e,t)=>{j8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>c5e(e,n,i,o),e.element=t.element,e.min=(n,i)=>e.check(rb(n,i)),e.nonempty=n=>e.check(rb(1,n)),e.max=(n,i)=>e.check(tU(n,i)),e.length=(n,i)=>e.check(nU(n,i)),e.unwrap=()=>e.element});function Si(e,t){return Gwe(dCe,e,t)}const fCe=Pt("ZodObject",(e,t)=>{W8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>d5e(e,n,i,o),Zi(e,"shape",()=>t.shape),e.keyof=()=>ss(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:rr()}),e.loose=()=>e.clone({...e._zod.def,catchall:rr()}),e.strict=()=>e.clone({...e._zod.def,catchall:uU()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>c3e(e,n),e.safeExtend=n=>d3e(e,n),e.merge=n=>f3e(e,n),e.pick=n=>a3e(e,n),e.omit=n=>u3e(e,n),e.partial=(...n)=>h3e(dU,e,n[0]),e.required=(...n)=>p3e(fU,e,n[0])});function tn(e,t){const n={type:"object",shape:e??{},...On(t)};return new fCe(n)}const cU=Pt("ZodUnion",(e,t)=>{Xq.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>f5e(e,n,i,o),e.options=t.options});function hCe(e,t){return new cU({type:"union",options:e,...On(t)})}const pCe=Pt("ZodDiscriminatedUnion",(e,t)=>{cU.init(e,t),q8e.init(e,t)});function cd(e,t,n){return new pCe({type:"union",options:t,discriminator:e,...On(n)})}const mCe=Pt("ZodIntersection",(e,t)=>{U8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>h5e(e,n,i,o)});function gCe(e,t){return new mCe({type:"intersection",left:e,right:t})}const vCe=Pt("ZodRecord",(e,t)=>{V8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>p5e(e,n,i,o),e.keyType=t.keyType,e.valueType=t.valueType});function Wx(e,t,n){return new vCe({type:"record",keyType:e,valueType:t,...On(n)})}const FA=Pt("ZodEnum",(e,t)=>{K8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(i,o,s)=>r5e(e,i,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(i,o)=>{const s={};for(const r of i)if(n.has(r))s[r]=t.entries[r];else throw new Error(`Key ${r} not found in enum`);return new FA({...t,checks:[],...On(o),entries:s})},e.exclude=(i,o)=>{const s={...t.entries};for(const r of i)if(n.has(r))delete s[r];else throw new Error(`Key ${r} not found in enum`);return new FA({...t,checks:[],...On(o),entries:s})}});function ss(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new FA({type:"enum",entries:n,...On(t)})}const yCe=Pt("ZodLiteral",(e,t)=>{Z8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>l5e(e,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Kn(e,t){return new yCe({type:"literal",values:Array.isArray(e)?e:[e],...On(t)})}const kCe=Pt("ZodTransform",(e,t)=>{G8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>u5e(e,n),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Fq(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Ev(s,n.value,t));else{const r=s;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=e),n.issues.push(Ev(r))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function bCe(e){return new kCe({type:"transform",transform:e})}const dU=Pt("ZodOptional",(e,t)=>{eU.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>rU(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function sF(e){return new dU({type:"optional",innerType:e})}const wCe=Pt("ZodExactOptional",(e,t)=>{Q8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>rU(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function CCe(e){return new wCe({type:"optional",innerType:e})}const ACe=Pt("ZodNullable",(e,t)=>{Y8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>m5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function rF(e){return new ACe({type:"nullable",innerType:e})}const xCe=Pt("ZodDefault",(e,t)=>{J8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>v5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function SCe(e,t){return new xCe({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():$q(t)}})}const _Ce=Pt("ZodPrefault",(e,t)=>{X8e.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>y5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function ICe(e,t){return new _Ce({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():$q(t)}})}const fU=Pt("ZodNonOptional",(e,t)=>{ewe.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>g5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function MCe(e,t){return new fU({type:"nonoptional",innerType:e,...On(t)})}const TCe=Pt("ZodCatch",(e,t)=>{twe.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>k5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ECe(e,t){return new TCe({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const LCe=Pt("ZodPipe",(e,t)=>{nwe.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>b5e(e,n,i,o),e.in=t.in,e.out=t.out});function lF(e,t){return new LCe({type:"pipe",in:e,out:t})}const NCe=Pt("ZodReadonly",(e,t)=>{iwe.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>w5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function DCe(e){return new NCe({type:"readonly",innerType:e})}const FCe=Pt("ZodCustom",(e,t)=>{owe.init(e,t),ls.init(e,t),e._zod.processJSONSchema=(n,i,o)=>a5e(e,n)});function RCe(e,t={}){return Qwe(FCe,e,t)}function OCe(e){return Ywe(e)}const lp=Ut().min(1),qx=Ut().min(1),c2=Ut().min(1),ap=Ut().min(1),Ca=Ut().min(1),PCe=/^[A-Za-z0-9._-]{1,128}$/;function $Ce(e){return PCe.test(e)&&e!=="."&&e!==".."}const hU=cd("kind",[tn({kind:Kn("user"),payload:rr().optional()}),tn({kind:Kn("cron"),taskId:ap.optional(),payload:rr().optional()}),tn({kind:Kn("task"),taskId:ap,payload:rr().optional()}),tn({kind:Kn("hook"),payload:rr().optional()}),tn({kind:Kn("compaction"),payload:rr().optional()}),tn({kind:Kn("side"),payload:rr().optional()}),tn({kind:Kn("other"),payload:rr().optional()})]),BCe=tn({inputTokens:Tn().optional(),outputTokens:Tn().optional(),cachedTokens:Tn().optional(),cost:Tn().optional()}),H0=tn({inputOther:Tn(),output:Tn(),inputCacheRead:Tn(),inputCacheCreation:Tn()}),zCe=tn({llmFirstTokenLatencyMs:Tn().optional(),llmStreamDurationMs:Tn().optional(),llmRequestBuildMs:Tn().optional(),llmServerFirstTokenMs:Tn().optional(),llmServerDecodeMs:Tn().optional(),llmClientConsumeMs:Tn().optional()}),jCe=tn({failedAttempt:Tn(),nextAttempt:Tn(),maxAttempts:Tn(),delayMs:Tn(),errorName:Ut(),errorMessage:Ut(),statusCode:Tn().optional()}),pU=ss(["queued","running","completed","failed","cancelled"]),HCe=ss(["running","completed","interrupted","failed"]),WCe=tn({skillName:Ut(),skillArgs:Ut().optional()}),qCe=tn({kind:Kn("user"),skillActivations:Si(WCe).optional()}),aF={kind:Kn("text"),frameId:c2,text:Ut(),attachmentIds:Si(Ut()).optional(),taskId:ap.optional(),promptIds:Si(Ut()).optional()},UCe=cd("role",[tn({...aF,role:Kn("assistant"),origin:uU().optional()}),tn({...aF,role:Kn("user"),origin:qCe.optional()})]),VCe=tn({kind:Kn("thinking"),frameId:c2,text:Ut()}),KCe=tn({agentId:Ca,role:ss(["child","member"]).optional()}),ZCe=tn({kind:ss(["stdout","stderr","progress","status","custom"]),text:Ut().optional(),percent:Tn().optional(),customKind:Ut().optional(),customData:rr().optional()}),GCe=tn({kind:Kn("tool"),frameId:c2,toolCallId:Ut(),name:Ut(),view:Ut().optional(),state:ss(["running","done","error"]),input:rr().optional(),output:rr().optional(),display:rr().optional(),error:Ut().optional(),inputText:Ut().optional(),progress:ZCe.optional(),taskId:ap.optional(),approvalId:Ut().optional(),todoId:Ut().optional(),agentRefs:Si(KCe).optional()}),Ux=tn({interactionId:Ut(),interactionKind:ss(["approval","question"]),toolCallId:Ut().optional(),state:ss(["pending","approved","rejected","cancelled","answered","dismissed"]),request:rr().optional(),response:rr().optional()}),QCe=tn({kind:Kn("notice"),frameId:c2,level:ss(["error","warning","info"]),source:Ut().optional(),message:Ut(),detail:rr().optional()}),mU=cd("kind",[UCe,VCe,GCe,QCe]),gU=tn({kind:Kn("step"),stepId:qx,turnId:lp,ordinal:Tn().int(),state:HCe,frames:Si(mU),startedAt:Ut().optional(),endedAt:Ut().optional(),usage:H0.optional(),finishReason:Ut().optional(),timing:zCe.optional(),retry:jCe.optional(),endReason:Ut().optional(),endMessage:Ut().optional()}),vU=tn({kind:Kn("turn"),turnId:lp,triggerPromptId:Ut().min(1).optional(),ordinal:Tn().int(),state:pU,origin:hU,prompt:Ut().optional(),attachmentIds:Si(Ut()).optional(),steps:Si(gU),startedAt:Ut().optional(),endedAt:Ut().optional(),usage:BCe.optional(),durationMs:Tn().optional(),error:Ut().optional()}),yU=tn({kind:Kn("marker"),markerId:Ut(),marker:Ut(),payload:rr().optional(),at:Ut().optional()}),kU=tn({kind:Kn("taskref"),refId:Ut(),taskId:ap,at:Ut().optional()}),bU=cd("kind",[vU,yU,kU]),Vx=tn({taskId:ap,kind:ss(["shell","subagent","tool","other"]),state:ss(["running","completed","failed","timed_out","killed","lost"]),detached:u2(),description:Ut().optional(),agentId:Ca.optional(),outputTail:Ut(),startedAt:Ut().optional(),endedAt:Ut().optional(),resultSummary:Ut().optional(),error:Ut().optional(),stateReason:Ut().optional(),usage:H0.optional(),model:Ut().optional(),thinkingEffort:Ut().optional()}),wU=tn({objective:Ut(),status:ss(["active","paused","blocked","complete"]),completionCriterion:Ut().optional(),budgetUsed:Tn().optional(),budgetLimit:Tn().optional()}),YCe=tn({plan:tn({reviewPath:Ut().optional(),version:Tn().optional()}).optional(),swarm:tn({trigger:Ut().optional()}).optional(),tower:tn({}).optional()}),JCe=tn({plan:tn({reviewPath:Ut().optional(),version:Tn().optional()}).nullable().optional(),swarm:tn({trigger:Ut().optional()}).nullable().optional(),tower:tn({}).nullable().optional()}),XCe=cd("kind",[tn({kind:Kn("idle")}),tn({kind:Kn("running"),turnId:Tn(),step:Tn(),stepId:Ut(),since:Tn()}),tn({kind:Kn("streaming"),turnId:Tn(),step:Tn(),stepId:Ut(),stream:ss(["assistant","thinking","tool_call"]),toolCallId:Ut().optional(),toolName:Ut().optional(),since:Tn()}),tn({kind:Kn("tool_call"),turnId:Tn(),step:Tn(),toolCallId:Ut(),name:Ut(),since:Tn()}),tn({kind:Kn("retrying"),turnId:Tn(),step:Tn(),stepId:Ut(),failedAttempt:Tn(),nextAttempt:Tn(),maxAttempts:Tn(),delayMs:Tn(),errorName:Ut().optional(),statusCode:Tn().optional(),since:Tn()}),tn({kind:Kn("awaiting_approval"),turnId:Tn(),step:Tn().optional(),approval:rr().optional(),since:Tn()}),tn({kind:Kn("interrupted"),turnId:Tn(),step:Tn().optional(),reason:ss(["aborted","max_steps","error"]),message:Ut().optional(),at:Tn()}),tn({kind:Kn("ended"),turnId:Tn(),reason:ss(["completed","cancelled","failed","blocked"]),durationMs:Tn().optional(),at:Tn()})]),eAe=tn({byModel:Wx(Ut(),H0).optional(),currentTurn:H0.optional(),total:H0.optional()}),tAe=tn({model:Ut().optional(),thinkingEffort:Ut().optional(),usage:eAe.optional(),contextTokens:Tn().optional(),maxContextTokens:Tn().optional(),contextUsage:Tn().optional(),permission:ss(["manual","yolo","auto"]).optional(),phase:XCe.optional()}),Kx=tn({goal:wU.optional(),modes:YCe.optional(),activity:ss(["idle","turn","disposing","unknown"]).optional(),agent:tAe.optional()}),nAe=Kx.extend({goal:wU.nullable().optional(),modes:JCe.optional()}),B4=tn({attachmentId:Ut(),mediaType:Ut(),name:Ut().optional(),size:Tn().optional(),source:cd("kind",[tn({kind:Kn("url"),url:Ut()}),tn({kind:Kn("file"),fileId:Ut()}),tn({kind:Kn("session_media"),fileId:Ut()})]).optional(),placeholder:Ut().optional()}),iAe=tn({title:Ut(),status:ss(["pending","in_progress","done"])}),Zx=tn({todoId:Ut(),items:Si(iAe),updatedAt:Ut().optional()}),Gx=tn({promptId:Ut(),status:ss(["running","queued","blocked","completed","failed","aborted"]),userMessageId:Ut().optional(),content:rr().optional(),createdAt:Ut(),finishedAt:Ut().optional(),steeredAt:Ut().optional()}),CU=tn({items:Si(bU),tasks:Si(Vx),interactions:Si(Ux).default([]),attachments:Si(B4).default([]),todos:Si(Zx).default([]),prompts:Si(Gx).default([]),meta:Kx,hasMoreOlder:u2().optional()}),oAe=vU.omit({steps:!0}),sAe=gU.omit({frames:!0}),rAe=cd("type",[tn({type:Kn("frame"),turnId:lp,stepId:qx,frameId:c2}),tn({type:Kn("task"),taskId:ap})]),Qx=cd("op",[tn({op:Kn("reset"),agentId:Ca,snapshot:CU}),tn({op:Kn("turn.upsert"),turn:oAe}),tn({op:Kn("step.upsert"),turnId:lp,step:sAe}),tn({op:Kn("frame.upsert"),turnId:lp,stepId:qx,frame:mU}),tn({op:Kn("append"),target:rAe,offset:Tn().int().nonnegative(),text:Ut()}),tn({op:Kn("marker.upsert"),item:yU,beforeTurn:Tn().int().optional()}),tn({op:Kn("taskref.upsert"),item:kU,beforeTurn:Tn().int().optional()}),tn({op:Kn("task.upsert"),task:Vx}),tn({op:Kn("interaction.upsert"),interaction:Ux}),tn({op:Kn("attachment.upsert"),attachment:B4}),tn({op:Kn("todo.upsert"),todo:Zx}),tn({op:Kn("prompt.upsert"),prompt:Gx}),tn({op:Kn("meta.merge"),meta:nAe}),tn({op:Kn("items.remove"),ids:Si(Ut())})]);tn({agentId:Ca,ops:Si(Qx)});const lAe=ss(["off","turn","block","delta"]),pm=Tn().int().nonnegative(),aAe=Wx(Ut(),lAe);tn({session_id:Ut().min(1),transcript:aAe,transcript_since:Wx(Ut(),pm).optional()});tn({agent_id:Ca,before_turn:Ut().min(1).optional(),after_turn:Ut().min(1).optional(),page_size:Tn().int().min(1).max(100).optional()}).superRefine((e,t)=>{e.before_turn!==void 0&&e.after_turn!==void 0&&t.addIssue({code:"custom",message:"before_turn and after_turn are mutually exclusive",path:["before_turn"]}),$Ce(e.agent_id)||t.addIssue({code:"custom",message:"agent_id must be a plain agent id (no path separators)",path:["agent_id"]})});const uAe=tn({agentId:Ca,type:ss(["main","sub","independent"]).optional(),parentAgentId:Ca.optional(),label:Ut().optional(),createdAt:Ut().optional(),disposedAt:Ut().optional()}),cAe=tn({agent_id:Ca,items:Si(bU),has_more:u2(),tasks:Si(Vx),interactions:Si(Ux).default([]),attachments:Si(B4).default([]),todos:Si(Zx).default([]),prompts:Si(Gx).default([]),meta:Kx,agents:Si(uAe),pending_interactions:Si(Ut()),seq:pm.optional()});tn({agent_id:Ca,batches:Si(tn({seq:pm,ops:Si(Qx)})),latest_seq:pm,complete:u2()});const dAe=tn({turn_id:lp,ordinal:Tn().int(),state:pU,origin:hU,prompt:Ut(),attachment_ids:Si(Ut()).optional(),started_at:Ut().optional()});tn({agents:Si(tn({agent_id:Ca,messages:Si(dAe),attachments:Si(B4).default([])}))});const fAe=tn({state:ss(["pending","approved","rejected","cancelled"]),selected_option:Ut().optional(),feedback:Ut().optional()}),hAe=tn({tool_call_id:Ut(),turn_id:lp,source:ss(["interaction","display","output"]),plan:Ut(),path:Ut().optional(),options:Si(tn({label:Ut(),description:Ut().optional()})).optional(),review:fAe.optional()});tn({agent_id:Ca,plans:Si(hAe)});const pAe=tn({agent_id:Ca,snapshot:CU,has_more_older:u2(),seq:pm.optional()}),mAe=tn({agent_id:Ca,ops:Si(Qx),seq:pm.optional()}),AU=pAe.extend({type:Kn("transcript.reset")}),xU=mAe.extend({type:Kn("transcript.ops")});cd("type",[AU,xU]);const uF=new Set(["turn.started","turn.step.started","turn.step.completed","turn.step.retrying","turn.step.interrupted","turn.ended","thinking.delta","assistant.delta","tool.call.started","tool.use","tool.call.delta","tool.progress","tool.result","agent.status.updated","prompt.submitted","prompt.completed","prompt.aborted","session.meta.updated","compaction.started","compaction.completed","compaction.cancelled","goal.updated","error","warning","subagent.spawned","subagent.started","subagent.suspended","subagent.completed","subagent.failed","task.started","task.terminated","background.task.started","background.task.terminated","cron.fired"]),gAe=new Set(["session.created","session.updated","session.deleted","session.status_changed","session.usage_updated","session.history_compacted","message.created","message.updated","approval.requested","approval.resolved","approval.expired","question.requested","question.answered","question.dismissed","task.created","task.progress","task.completed","assistant.tool_use_started","assistant.tool_use_delta","assistant.tool_use_completed","assistant.completed","tool.started","tool.output","tool.completed"]),vAe=new Set(["server_hello","ack","ping","resync_required","error","pong"]),yAe=new Set(["assistant.delta","thinking.delta"]);function kAe(e,t){if(vAe.has(e))return{route:"ignore"};const n=e.startsWith("event."),i=n?e.slice(6):e;return yAe.has(i)?bAe(t)?{route:"agent",agentType:i}:{route:"protocol"}:n?gAe.has(i)?{route:"protocol"}:uF.has(i)?{route:"agent",agentType:i}:{route:"protocol"}:uF.has(i)?{route:"agent",agentType:i}:{route:"agent",agentType:i}}function bAe(e){if(!e||typeof e!="object")return!1;const t=e;return"message_id"in t||"content_index"in t?!1:typeof t.delta=="string"}const wAe="kimi-code.bearer.",CAe=3e4;class cF{constructor(t){this.opts=t,this.tracer=t.tracer??Rx}ws=null;connected=!1;closed=!1;subscriptions=new Map;transcriptSubscriptions=new Map;sideChannelAgents=new Map;pendingSubscriptions=[];terminalAttachments=new Map;msgSeq=0;clientHelloId=null;reconnectAttempts=0;reconnectTimer=null;heartbeatMs=3e4;lastActivityAt=0;tracer;connect(){if(this.ws!==null||this.closed)return;this.lastActivityAt=Date.now(),this.tracer.wsEvent?.({kind:"lifecycle",event:"connect",detail:{url:this.opts.wsUrl,attempt:this.reconnectAttempts}});const t=this.opts.credentialStore?.getToken(),n=t!==void 0?[`${wAe}${t}`]:void 0,i=new WebSocket(this.opts.wsUrl,n);this.ws=i,i.onopen=()=>{this.tracer.wsEvent?.({kind:"lifecycle",event:"open"})},i.onmessage=o=>{this.lastActivityAt=Date.now();try{const s=JSON.parse(String(o.data));this.tracer.wsEvent?.({kind:"in",frame:s}),this.handleFrame(s)}catch(s){this.tracer.wsEvent?.({kind:"lifecycle",event:"parse-error",detail:{error:String(s)}}),this.opts.handlers.onError(0,`Failed to parse WS frame: ${String(s)}`,!1)}},i.onerror=()=>{this.tracer.wsEvent?.({kind:"lifecycle",event:"error"}),this.opts.handlers.onError(0,"WebSocket error",!1)},i.onclose=o=>{this.tracer.wsEvent?.({kind:"lifecycle",event:"close",detail:o?{code:o.code,reason:o.reason,wasClean:o.wasClean}:void 0}),this.connected=!1,this.ws=null,this.opts.handlers.onConnectionState(!1),this.scheduleReconnect()}}scheduleReconnect(){if(this.closed||this.reconnectTimer!==null)return;const n=Math.min(3e4,1e3*2**this.reconnectAttempts)+Math.floor(Math.random()*250);this.reconnectAttempts+=1,this.tracer.wsEvent?.({kind:"lifecycle",event:"reconnect-scheduled",detail:{delayMs:n,attempt:this.reconnectAttempts}}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},n)}subscribe(t,n={seq:0}){if(this.subscriptions.set(t,{...n}),this.connected)this.sendSubscribe([t],{[t]:n});else{const i=this.pendingSubscriptions.findIndex(o=>o.sessionId===t);i!==-1&&this.pendingSubscriptions.splice(i,1),this.pendingSubscriptions.push({sessionId:t,cursor:{...n}})}}unsubscribe(t){this.subscriptions.delete(t);const n=this.pendingSubscriptions.findIndex(i=>i.sessionId===t);n!==-1&&this.pendingSubscriptions.splice(n,1),this.connected&&this.ws&&this.send({type:"unsubscribe",id:this.nextId(),payload:{session_ids:[t]}})}subscribeTranscript(t,n,i){let o=this.transcriptSubscriptions.get(t);o===void 0&&(o=new Map,this.transcriptSubscriptions.set(t,o)),o.set(n,i!==void 0?{sinceSeq:i}:{}),this.connected&&this.sendTranscriptSubscribe(t,n)}unsubscribeTranscript(t,n){const i=this.transcriptSubscriptions.get(t);if(i!==void 0)if(n===void 0)this.transcriptSubscriptions.delete(t);else{for(const o of n)i.delete(o);i.size===0&&this.transcriptSubscriptions.delete(t)}!this.connected||!this.ws||this.send({type:"unsubscribe_v2",id:this.nextId(),payload:{session_id:t,...n!==void 0?{agent_ids:n}:{}}})}markSideChannelAgent(t,n){if(!this.opts.mainAgentOnly)return;let i=this.sideChannelAgents.get(t);if(i===void 0&&(i=new Set,this.sideChannelAgents.set(t,i)),i.has(n))return;i.add(n);const o=this.subscriptions.get(t);this.connected&&o!==void 0&&this.sendSubscribe([t],{[t]:o})}abort(t,n){!this.connected||!this.ws||this.send({type:"abort",id:this.nextId(),payload:{session_id:t,prompt_id:n}})}terminalAttach(t,n,i){const o=Fy(t,n),s=this.terminalAttachments.get(o),r=i??s?.lastSeq??0;this.terminalAttachments.set(o,{sessionId:t,terminalId:n,lastSeq:r}),!(!this.connected||!this.ws)&&this.sendTerminalAttach(t,n,r)}terminalInput(t,n,i){!this.connected||!this.ws||this.send({type:"terminal_input",id:this.nextId(),payload:{session_id:t,terminal_id:n,data:i}})}terminalResize(t,n,i,o){!this.connected||!this.ws||this.send({type:"terminal_resize",id:this.nextId(),payload:{session_id:t,terminal_id:n,cols:i,rows:o}})}terminalDetach(t,n){this.terminalAttachments.delete(Fy(t,n)),!(!this.connected||!this.ws)&&this.send({type:"terminal_detach",id:this.nextId(),payload:{session_id:t,terminal_id:n}})}terminalClose(t,n){this.terminalAttachments.delete(Fy(t,n)),!(!this.connected||!this.ws)&&this.send({type:"terminal_close",id:this.nextId(),payload:{session_id:t,terminal_id:n}})}close(){this.closed=!0,this.connected=!1,this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(1e3),this.ws=null)}health(){const t=this.ws!==null&&this.ws.readyState===WebSocket.OPEN,n=Math.max(this.heartbeatMs*2,CAe),i=this.lastActivityAt>0&&Date.now()-this.lastActivityAt>n;return{connected:this.connected,open:t,stale:i}}reconnect(){if(this.closed)return;this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);const t=this.ws;if(t!==null){t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{t.close(1e3,"reconnect")}catch{}}const n=this.connected;this.ws=null,this.connected=!1,n&&this.opts.handlers.onConnectionState(!1),this.connect()}handleFrame(t){const n=t,i=t.type;if(i==="transcript.reset"){const o=AU.safeParse({type:i,...n.payload}),s=n.session_id;if(!o.success||typeof s!="string"){this.opts.handlers.onError(0,"Invalid transcript.reset frame",!1);return}const r=o.data;this.opts.handlers.onTranscriptReset?.(s,r.agent_id,{...r.snapshot,hasMoreOlder:r.has_more_older},r.seq);const l=this.transcriptSubscriptions.get(s)?.get(r.agent_id);l!==void 0&&r.seq!==void 0&&(l.sinceSeq=r.seq);return}if(i==="transcript.ops"){const o=xU.safeParse({type:i,...n.payload}),s=n.session_id;if(!o.success||typeof s!="string"){this.opts.handlers.onError(0,"Invalid transcript.ops frame",!1);return}const r=o.data,l=this.opts.handlers.onTranscriptOps?.(s,r.agent_id,r.ops,r.seq),a=this.transcriptSubscriptions.get(s)?.get(r.agent_id);l!==!1&&a!==void 0&&r.seq!==void 0&&(a.sinceSeq=r.seq);return}switch(i){case"server_hello":{const o=n.payload?.heartbeat_ms;typeof o=="number"&&o>0&&(this.heartbeatMs=o),this.onServerHello();break}case"ping":this.send({type:"pong",payload:{nonce:n.payload.nonce}});break;case"resync_required":{const o=n.payload.session_id,s=n.payload.epoch;this.subscriptions.set(o,{seq:n.payload.current_seq,epoch:s}),this.opts.handlers.onResync(o,n.payload.current_seq,s);break}case"error":{const o=n.session_id;typeof o=="string"&&this.opts.handlers.onRawAgentEvent?this.opts.handlers.onRawAgentEvent({type:"error",seq:n.seq,session_id:o,timestamp:n.timestamp,payload:n.payload}):this.opts.handlers.onError(n.payload.code,n.payload.msg,n.payload.fatal);break}case"ack":n.id===this.clientHelloId&&(this.clientHelloId=null,n.code===0&&this.opts.handlers.onReplayComplete?.());break;case"terminal_output":{const o=n.session_id,s=n.terminal_id,r=n.seq,l=Fy(o,s),a=this.terminalAttachments.get(l);a&&this.terminalAttachments.set(l,{...a,lastSeq:Math.max(a.lastSeq,r)});const u=typeof n.payload?.data=="string"?n.payload.data:"";this.opts.handlers.onTerminalOutput?.(o,s,u,r);break}case"terminal_exit":{const o=n.session_id,s=n.terminal_id,r=n.payload?.exit_code,l=typeof r=="number"?r:null;this.opts.handlers.onTerminalExit?.(o,s,l);break}default:{this.trackCursor(n);const o=n.type,s=kAe(o,n.payload);if(s.route==="protocol"){this.opts.handlers.onWireEvent(n);break}if(s.route==="agent"){if(this.opts.handlers.onRawAgentEvent&&typeof n.session_id=="string"){const r=n,l=n;this.opts.handlers.onRawAgentEvent({type:s.agentType,seq:r.seq,session_id:r.session_id,timestamp:r.timestamp,payload:r.payload,...l.volatile!==void 0?{volatile:l.volatile}:{},...l.offset!==void 0?{offset:l.offset}:{}})}break}break}}}onServerHello(){this.connected=!0,this.reconnectAttempts=0,this.opts.handlers.onConnectionState(!0);const t=Array.from(this.subscriptions.keys());for(const o of this.pendingSubscriptions)this.subscriptions.set(o.sessionId,o.cursor),t.includes(o.sessionId)||t.push(o.sessionId);this.pendingSubscriptions.length=0;const n={};for(const[o,s]of this.subscriptions.entries())n[o]=s;const i=this.nextId();this.clientHelloId=i,this.send({type:"client_hello",id:i,payload:{client_id:this.opts.clientId,subscriptions:t,cursors:n,...this.opts.mainAgentOnly?{agent_filter:this.rawAgentFilter(t)}:{}}});for(const o of this.transcriptSubscriptions.keys())this.sendTranscriptSubscribe(o);for(const o of this.terminalAttachments.values())this.sendTerminalAttach(o.sessionId,o.terminalId,o.lastSeq)}sendSubscribe(t,n){this.send({type:"subscribe",id:this.nextId(),payload:{session_ids:t,cursors:n,...this.opts.mainAgentOnly?{agent_filter:this.rawAgentFilter(t)}:{}}})}rawAgentFilter(t){return Object.fromEntries(t.map(n=>[n,["main",...this.sideChannelAgents.get(n)??[]]]))}sendTranscriptSubscribe(t,n){const i=this.transcriptSubscriptions.get(t);if(i===void 0||i.size===0)return;const o={},s={};for(const[r,l]of i)o[r]="delta",l.sinceSeq!==void 0&&(n===void 0||n===r)&&(s[r]=l.sinceSeq);this.send({type:"subscribe_v2",id:this.nextId(),payload:{session_id:t,transcript:o,...Object.keys(s).length>0?{transcript_since:s}:{}}})}sendTerminalAttach(t,n,i){this.send({type:"terminal_attach",id:this.nextId(),payload:{session_id:t,terminal_id:n,since_seq:i>0?i:void 0}})}trackCursor(t){if(t.volatile===!0)return;const n=t.session_id,i=t.seq;if(typeof n!="string"||typeof i!="number")return;const o=this.subscriptions.get(n);if(!o||i<=o.seq&&o.epoch!==void 0)return;const s=typeof t.epoch=="string"?t.epoch:o.epoch;this.subscriptions.set(n,{seq:Math.max(i,o.seq),epoch:s})}send(t){if(!(!this.ws||this.ws.readyState!==WebSocket.OPEN))try{this.ws.send(JSON.stringify(t)),this.tracer.wsEvent?.({kind:"out",frame:t})}catch{}}nextId(){return`c_${++this.msgSeq}`}}function Fy(e,t){return`${e}\0${t}`}async function AAe(e,t,n){const i=await e.get(`/sessions/${encodeURIComponent(t)}/transcript`,{agent_id:n.agentId,before_turn:n.beforeTurn,after_turn:n.afterTurn,page_size:n.pageSize}),o=cAe.parse(i),s={items:o.items,tasks:o.tasks,interactions:o.interactions,attachments:o.attachments,todos:o.todos,prompts:o.prompts,meta:o.meta,hasMoreOlder:o.has_more};return{agentId:o.agent_id,...s,agents:o.agents,pendingInteractions:o.pending_interactions,...o.seq!==void 0?{seq:o.seq}:{}}}const gw=10485760,xAe=5e3,dF=40001;function SAe(e,t){if(e===void 0)return t;let n;const i=/filename\*\s*=\s*UTF-8''([^;]+)/i.exec(e)?.[1]?.trim();if(i!==void 0)try{n=decodeURIComponent(i.replaceAll(/^"|"$/g,""))}catch{return t}else n=/filename\s*=\s*"([^"]*)"/i.exec(e)?.[1]??/filename\s*=\s*([^;]+)/i.exec(e)?.[1]?.trim();return n===void 0||n.length===0||n.length>200||n==="."||n===".."||/[\u0000-\u001F\u007F/\\]/.test(n)||!n.toLowerCase().endsWith(".zip")?t:n}function _Ae(e){if(typeof e!="object"||e===null)return{errorName:typeof e};const t=e;return{errorName:typeof t.name=="string"?t.name:"Error",errorCode:typeof t.code=="number"?t.code:void 0,requestId:typeof t.requestId=="string"?t.requestId:void 0,phase:typeof t.phase=="string"?t.phase:void 0,httpStatus:typeof t.status=="number"?t.status:void 0}}function vw(e){return{id:e.id,sessionId:e.session_id,cwd:e.cwd,shell:e.shell,cols:e.cols,rows:e.rows,status:e.status,createdAt:e.created_at,exitedAt:e.exited_at,exitCode:e.exit_code}}function fF(e){return e==="auto_compact"||e==="manual_compact"}class IAe{constructor(t){this.opts=t,this.tracer=t.tracer??Rx,this.http=new DD({origin:t.origin,identity:t.identity,tracer:this.tracer,credentialStore:t.credentialStore}),this.httpV2=new DD({origin:t.origin,identity:t.identity,tracer:this.tracer,credentialStore:t.credentialStore,restBasePath:"/api/v2"})}http;httpV2;tracer;async getHealth(){return{status:"ok",uptimeSec:(await this.http.get("/healthz")).uptime_sec??0}}async getMeta(){const t=await this.http.get("/meta");return{serverVersion:t.server_version,serverId:t.server_id,startedAt:t.started_at,capabilities:t.capabilities,openInApps:Array.isArray(t.open_in_apps)?t.open_in_apps:[],dangerousBypassAuth:t.dangerous_bypass_auth===!0,experimentalFlags:t.experimental_flags??{},backend:t.backend==="v2"?"v2":"v1",webTitle:t.web_title??""}}async listSessions(t){const n={before_id:t?.beforeId,after_id:t?.afterId,page_size:t?.pageSize,busy:t?.busy,include_archive:t?.includeArchive,archived_only:t?.archivedOnly,exclude_empty:t?.excludeEmpty,workspace_id:t?.workspaceId},i=await this.http.get("/sessions",n);return{items:i.items.map(ju),hasMore:i.has_more}}async listSessionsV2(t){const n={sort:t?.sort,page_size:t?.pageSize,page_token:t?.pageToken,page:t?.page,"meta.updated_after":t?.updatedAfter,"meta.updated_before":t?.updatedBefore,"meta.archived":t?.archived===void 0?void 0:String(t.archived),include:t?.include,"workspace.id":t?.workspaceIds,"activity.status":t?.statuses},i=await this.httpV2.get("/sessions",n);return{items:i.items,hasMore:i.has_more,nextPageToken:i.next_page_token,total:i.total}}async listSessionIdsV2(t){const n={sort:t?.sort,page_size:t?.pageSize,page_token:t?.pageToken,page:t?.page,"meta.updated_after":t?.updatedAfter,"meta.updated_before":t?.updatedBefore,"meta.archived":t?.archived===void 0?void 0:String(t.archived),fields:"id,archived","workspace.id":t?.workspaceIds,"activity.status":t?.statuses},i=await this.httpV2.get("/sessions",n);return{items:i.items,hasMore:i.has_more,nextPageToken:i.next_page_token,total:i.total}}async listSessionGroupsV2(t){const n={view:"by_workspace","group.page_size":t?.groupPageSize,"meta.has_prompt":t?.hasPrompt===void 0?void 0:String(t.hasPrompt),sort:t?.sort,page_size:t?.pageSize,page_token:t?.pageToken,"meta.archived":t?.archived===void 0?void 0:String(t.archived),"workspace.id":t?.workspaceIds,"activity.status":t?.statuses},i=await this.httpV2.get("/sessions",n);return{groups:i.groups,hasMore:i.has_more,nextPageToken:i.next_page_token,total:i.total}}async createSession(t){const n={metadata:t.cwd!==void 0?{cwd:t.cwd}:{}};t.workspaceId!==void 0&&(n.workspace_id=t.workspaceId),t.title!==void 0&&(n.title=t.title),t.model!==void 0&&(n.agent_config={model:t.model});const i=await this.http.post("/sessions",n);return ju(i)}async getSession(t){const n=await this.http.get(`/sessions/${encodeURIComponent(t)}`);return ju(n)}async updateSession(t,n){const i={};n.title!==void 0&&(i.title=n.title),n.cwd!==void 0&&(i.metadata={cwd:n.cwd});const o={};n.model!==void 0&&(o.model=n.model),n.permissionMode!==void 0&&(o.permission_mode=n.permissionMode),n.planMode!==void 0&&(o.plan_mode=n.planMode),n.swarmMode!==void 0&&(o.swarm_mode=n.swarmMode),n.goalObjective!==void 0&&(o.goal_objective=n.goalObjective),n.goalControl!==void 0&&(o.goal_control=n.goalControl),n.thinking!==void 0&&(o.thinking=n.thinking),Object.keys(o).length>0&&(i.agent_config=o);const s=await this.http.post(`/sessions/${encodeURIComponent(t)}/profile`,i);return ju(s)}async getSessionStatus(t){const n=await this.http.get(`/sessions/${encodeURIComponent(t)}/status`);return{model:n.model&&n.model.length>0?n.model:null,thinkingEffort:n.thinking_level,permission:n.permission,planMode:n.plan_mode===!0,swarmMode:n.swarm_mode===!0,contextTokens:n.context_tokens??0,maxContextTokens:n.max_context_tokens??0,contextUsage:n.context_usage??0}}async getSessionGoal(t){const n=await this.http.get(`/sessions/${encodeURIComponent(t)}/goal`);return Lq(n)}async getSessionPlans(t,n){const i=await this.http.get(`/sessions/${encodeURIComponent(t)}/transcript/plan`,{agent_id:n.agentId,tool_call_id:n.toolCallId});return i.plans.map(o=>({agentId:i.agent_id,toolCallId:o.tool_call_id,turnId:o.turn_id,source:o.source,plan:o.plan,...o.path!==void 0?{path:o.path}:{},...o.options!==void 0?{options:o.options.map(s=>({label:s.label,...s.description!==void 0?{description:s.description}:{}}))}:{},...o.review!==void 0?{review:{state:o.review.state,...o.review.selected_option!==void 0?{selectedOption:o.review.selected_option}:{},...o.review.feedback!==void 0?{feedback:o.review.feedback}:{}}}:{}}))}async getSessionWarnings(t){return(await this.http.get(`/sessions/${encodeURIComponent(t)}/warnings`)).warnings??[]}async archiveSession(t){return await this.http.post(`/sessions/${encodeURIComponent(t)}:archive`,{})}async restoreSession(t){const n=await this.http.post(`/sessions/${encodeURIComponent(t)}:restore`,{});return ju(n)}async archiveSessions(t){return this.httpV2.post("/sessions:archive",{ids:t})}async restoreSessions(t){return this.httpV2.post("/sessions:restore",{ids:t})}async listMessages(t,n){const i={before_id:n?.beforeId,after_id:n?.afterId,page_size:n?.pageSize,role:n?.role},o=await this.http.get(`/sessions/${encodeURIComponent(t)}/messages`,i);return{items:o.items.map(Tq),hasMore:o.has_more}}async getSessionTranscript(t,n){return AAe(this.http,t,n)}async exportSession(t,n,i){const o=n===void 0?0:new TextEncoder().encode(n).byteLength,s=n===void 0||n.length===0?0:n.split(` -`).length,r=`/sessions/${encodeURIComponent(t)}/export`,l={web_log_bytes:o,web_log_entries:s},a=i?.desktop===!0;let u;try{u=await this.http.postZip(r,{web_log:n,...a?{desktop:!0}:{}},l)}catch(d){if(a&&di(d)&&d.code===dF)u=await this.http.postZip(r,{web_log:n},l);else throw d}const c=`${t}.zip`;return{blob:u.blob,fileName:SAe(u.contentDisposition,c)}}async submitPrompt(t,n){const i=Date.now();this.tracer.traceKeyEvent?.("prompt:start",{sessionId:t,contentCount:n.content.length,mediaCount:n.content.filter(o=>o.type==="image"||o.type==="video"||o.type==="file").length});try{const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/prompts`,y4e(n));return this.tracer.traceKeyEvent?.("prompt:accepted",{sessionId:t,promptId:o.prompt_id,status:o.status,durationMs:Date.now()-i}),{promptId:o.prompt_id,userMessageId:o.user_message_id,origin:o.origin,status:o.status}}catch(o){throw this.tracer.traceKeyEvent?.("prompt:failed",{sessionId:t,status:"failed",durationMs:Date.now()-i,..._Ae(o)}),o}}async steerPrompts(t,n){const i=await this.http.post(`/sessions/${encodeURIComponent(t)}/prompts:steer`,{prompt_ids:n});return{steered:i.steered,promptIds:i.prompt_ids}}async abortPrompt(t,n){const i=await this.http.post(`/sessions/${encodeURIComponent(t)}/prompts/${encodeURIComponent(n)}:abort`,void 0,{allowCodes:[40903]});return{aborted:i.aborted,atSeq:i.at_seq}}async abortSession(t){return{aborted:(await this.http.post(`/sessions/${encodeURIComponent(t)}:abort`,{})).aborted}}async compactSession(t,n){await this.http.post(`/sessions/${encodeURIComponent(t)}:compact`,n?{instruction:n}:{})}async undoSession(t,n=1){await this.http.post(`/sessions/${encodeURIComponent(t)}:undo`,{count:n})}async generateSessionTitle(t,n){try{const i={};n?.force===!0&&(i.force=!0),n?.source!==void 0&&(i.source=n.source);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/title/generate`,i);return typeof o?.title=="string"&&o.title.length>0?o.title:null}catch{return null}}async forkSession(t,n){const i={};n?.title!==void 0&&(i.title=n.title);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}:fork`,i,{timeoutMs:ED});return ju(o)}async createChildSession(t,n){const i={};n?.title!==void 0&&(i.title=n.title);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/children`,i,{timeoutMs:ED});return ju(o)}async listChildSessions(t){return(await this.http.get(`/sessions/${encodeURIComponent(t)}/children`)).items.map(ju)}async startBtw(t){return{agentId:(await this.http.post(`/sessions/${encodeURIComponent(t)}:btw`,{})).agent_id}}async respondApproval(t,n,i){const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}`,k4e(i));return{resolved:o.resolved,resolvedAt:o.resolved_at}}async respondQuestion(t,n,i){const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/questions/${encodeURIComponent(n)}`,S4e(i));return{resolved:o.resolved,resolvedAt:o.resolved_at}}async dismissQuestion(t,n){return{dismissed:!0,dismissedAt:(await this.http.post(`/sessions/${encodeURIComponent(t)}/questions/${encodeURIComponent(n)}:dismiss`,void 0,{allowCodes:[40909]})).dismissed_at}}async listTasks(t,n){const i={status:n};return(await this.http.get(`/sessions/${encodeURIComponent(t)}/tasks`,i)).items.map(s=>TA(s))}async getTask(t,n,i){const o={with_output:i?.withOutput,output_bytes:i?.outputBytes},s=await this.http.get(`/sessions/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}`,o);return TA(s)}async cancelTask(t,n){return await this.http.post(`/sessions/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}:cancel`)}async detachTask(t,n){return await this.http.post(`/sessions/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}:detach`)}async listTerminals(t){return(await this.http.get(`/sessions/${encodeURIComponent(t)}/terminals`)).items.map(vw)}async createTerminal(t,n={}){const i={cwd:n.cwd,shell:n.shell,cols:n.cols,rows:n.rows},o=await this.http.post(`/sessions/${encodeURIComponent(t)}/terminals`,i);return vw(o)}async getTerminal(t,n){const i=await this.http.get(`/sessions/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`);return vw(i)}async closeTerminal(t,n){return this.http.post(`/sessions/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}:close`)}async listSkills(t){return((await this.http.get(`/sessions/${encodeURIComponent(t)}/skills`)).skills??[]).map(i=>({name:i.name,description:i.description,path:i.path,source:i.source}))}async listSkillsForWorkspace(t){return((await this.http.get(`/workspaces/${encodeURIComponent(t)}/skills`)).skills??[]).map(i=>({name:i.name,description:i.description,path:i.path,source:i.source}))}async activateSkill(t,n,i,o){const s={};i!==void 0&&i.length>0&&(s.args=i),o!==void 0&&o.length>0&&(s.attachments=o.map(Eq));const r=await this.http.post(`/sessions/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}:activate`,s);return{activated:r.activated,skillName:r.skill_name}}async listCapabilities(){return(await this.http.get("/capabilities")).capabilities??[]}async getCapability(t){return this.http.get(`/capabilities/${encodeURIComponent(t)}`)}async installCapability(t){return this.http.post(`/capabilities/${encodeURIComponent(t)}:install`,{})}async listPlugins(){return(await this.http.get("/plugins")).plugins??[]}async listPluginMarketplace(){return(await this.http.get("/plugins/marketplace")).entries??[]}async installPlugin(t){return this.http.post("/plugins",{source:t})}async setPluginEnabled(t,n){return this.http.post(`/plugins/${encodeURIComponent(t)}:${n?"enable":"disable"}`,{})}async removePlugin(t){return this.http.post(`/plugins/${encodeURIComponent(t)}:remove`,{})}async listDirectory(t,n){const i={};n.path!==void 0&&(i.path=n.path),n.depth!==void 0&&(i.depth=n.depth),n.includeGitStatus!==void 0&&(i.include_git_status=n.includeGitStatus);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:list`,i),s=o.children_by_path?Object.fromEntries(Object.entries(o.children_by_path).map(([r,l])=>[r,l.map(OD)])):void 0;return{items:o.items.map(OD),childrenByPath:s,truncated:o.truncated}}async readFile(t,n){const i={path:n.path};n.offset!==void 0&&(i.offset=n.offset),n.length!==void 0&&(i.length=n.length);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:read`,i);return{path:o.path,content:o.content,encoding:o.encoding,size:o.size,truncated:o.truncated,etag:o.etag,mime:o.mime,languageId:o.language_id,lineCount:o.line_count,isBinary:o.is_binary}}async searchFiles(t,n,i){const o={workspace:t,query:n.query};n.limit!==void 0&&(o.limit=n.limit);const s=await this.http.post("/workspace/fs:search",o,{signal:i?.signal});return{items:s.items.map(r=>({path:r.path,name:r.name,kind:r.kind,score:r.score,matchPositions:r.match_positions})),truncated:s.truncated}}async suggestFiles(t,n,i){const o={workspace:t,query:n.query};n.limit!==void 0&&(o.limit=n.limit);const s=await this.http.post("/workspace/fs:suggest",o,{signal:i?.signal});return{items:s.items.map(r=>({path:r.path,name:r.name,kind:r.kind,score:r.score,matchPositions:r.match_positions})),truncated:s.truncated}}async grepFiles(t,n){const i={pattern:n.pattern};n.regex!==void 0&&(i.regex=n.regex),n.caseSensitive!==void 0&&(i.case_sensitive=n.caseSensitive);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:grep`,i);return{files:o.files,filesScanned:o.files_scanned,truncated:o.truncated,elapsedMs:o.elapsed_ms}}async getGitStatus(t,n){const i={};n!==void 0&&(i.paths=n);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:git_status`,i);return{branch:o.branch,ahead:o.ahead,behind:o.behind,entries:o.entries,additions:o.additions,deletions:o.deletions,pullRequest:o.pullRequest??null}}async getFileDiff(t,n){const i=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:diff`,{path:n});return{path:i.path,diff:i.diff,truncated:i.truncated??!1}}getFileDownloadUrl(t,n){const i=n.split("/").map(o=>encodeURIComponent(o)).join("/");return Hd(this.opts.origin,`/sessions/${encodeURIComponent(t)}/fs/${i}:download`)}async openFile(t,n){const i={path:n.path};return n.line!==void 0&&(i.line=n.line),this.http.post(`/sessions/${encodeURIComponent(t)}/fs:open`,i)}async revealFile(t,n){return this.http.post(`/sessions/${encodeURIComponent(t)}/fs:reveal`,{path:n.path})}async openInApp(t,n,i,o){const s={app_id:n,path:i};o!==void 0&&(s.line=o),await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:open-in`,s)}async listWorkspaces(){try{return((await this.http.get("/workspaces")).items??[]).map(j0)}catch{return[]}}async addWorkspace(t){const n={root:t.root};t.name!==void 0&&(n.name=t.name);const i=await this.http.post("/workspaces",n);return j0(i)}async deleteWorkspace(t){await this.http.delete(`/workspaces/${encodeURIComponent(t)}`)}async updateWorkspace(t,n){const i=await this.http.patch(`/workspaces/${encodeURIComponent(t)}`,{name:n.name});return j0(i)}async browseFs(t){try{const n=await this.http.get("/fs:browse",{path:t});return{path:n.path,parent:n.parent,entries:(n.entries??[]).map(i=>({name:i.name,path:i.path,isDir:i.is_dir}))}}catch{return{path:"",parent:null,entries:[]}}}async getFsHome(){try{const t=await this.http.get("/fs:home");return{home:t.home,recentRoots:t.recent_roots??[]}}catch{return{home:"",recentRoots:[]}}}async listModels(){return(await this.http.get("/models")).items.map(I4e)}async listProviders(){return(await this.http.get("/providers")).items.map(Xp)}async getProvider(t){const n=await this.http.get(`/providers/${encodeURIComponent(t)}`),i=Xp(n);return n.api_key!==void 0?{...i,apiKey:n.api_key}:i}async addProvider(t){const n={id:t.id??"",type:t.type,models:(t.models??[]).map(o=>{const s={model:o.model,max_context_size:o.maxContextSize};return o.displayName!==void 0&&(s.display_name=o.displayName),o.capabilities!==void 0&&(s.capabilities=o.capabilities),o.maxOutputSize!==void 0&&(s.max_output_size=o.maxOutputSize),o.supportEfforts!==void 0&&(s.support_efforts=o.supportEfforts),o.adaptiveThinking!==void 0&&(s.adaptive_thinking=o.adaptiveThinking),s})};t.apiKey!==void 0&&(n.api_key=t.apiKey),t.baseUrl!==void 0&&(n.base_url=t.baseUrl),t.defaultModel!==void 0&&(n.default_model=t.defaultModel);const i=await this.http.post("/providers",n);return Xp(i)}async updateProvider(t,n){const i={type:n.type,models:(n.models??[]).map(s=>{const r={model:s.model,max_context_size:s.maxContextSize};return s.displayName!==void 0&&(r.display_name=s.displayName),s.capabilities!==void 0&&(r.capabilities=s.capabilities),s.maxOutputSize!==void 0&&(r.max_output_size=s.maxOutputSize),s.supportEfforts!==void 0&&(r.support_efforts=s.supportEfforts),s.adaptiveThinking!==void 0&&(r.adaptive_thinking=s.adaptiveThinking),r})};n.newId!==void 0&&(i.new_id=n.newId),n.apiKey!==void 0&&(i.api_key=n.apiKey),n.baseUrl!==void 0&&(i.base_url=n.baseUrl),n.defaultModel!==void 0&&(i.default_model=n.defaultModel);const o=await this.http.put(`/providers/${encodeURIComponent(t)}`,i);return{provider:Xp(o.provider)}}async deleteProvider(t){return await this.http.delete(`/providers/${encodeURIComponent(t)}`),{deleted:t}}async listCatalogProviders(){return(await this.http.get("/catalog/providers")).items.map(PD)}async getCatalogProvider(t){const n=await this.http.get(`/catalog/providers/${encodeURIComponent(t)}`);return PD(n)}async importCatalogProvider(t){const n={catalog_id:t.catalogId};t.apiKey!==void 0&&(n.api_key=t.apiKey),t.baseUrl!==void 0&&(n.base_url=t.baseUrl),t.id!==void 0&&(n.id=t.id);const i=await this.http.post("/providers:import_catalog",n);return{provider:Xp(i.provider),modelsImported:i.models_imported}}async importCustomRegistry(t){const n={url:t.url};t.apiKey!==void 0&&(n.api_key=t.apiKey);const i=await this.http.post("/providers:import_registry",n);return{providers:i.providers.map(Xp),modelsImported:i.models_imported}}async refreshProvider(t){const n=await this.http.post(`/providers/${encodeURIComponent(t)}:refresh`);return yw(n)}async refreshAllProviders(){const t=await this.http.post("/providers:refresh");return yw(t)}async refreshOAuthProviderModels(){const t=await this.http.post("/providers:refresh_oauth");return yw(t)}async getConfig(){const t=await this.http.get("/config");return EA(t)}async setConfig(t){const n={},i={providers:"providers",defaultProvider:"default_provider",defaultModel:"default_model",secondaryModel:"secondary_model",models:"models",thinking:"thinking",planMode:"plan_mode",yolo:"yolo",defaultPermissionMode:"default_permission_mode",defaultPlanMode:"default_plan_mode",permission:"permission",hooks:"hooks",services:"services",mergeAllAvailableSkills:"merge_all_available_skills",extraSkillDirs:"extra_skill_dirs",loopControl:"loop_control",background:"background",experimental:"experimental",telemetry:"telemetry",raw:"raw"};for(const[s,r]of Object.entries(t)){const l=i[s];l!==void 0&&(n[l]=r)}const o=await this.http.post("/config",n);return EA(o)}async getAuth(){const t=await this.http.get("/auth");return{modelsReady:t.models_ready,providersCount:t.providers_count,managedProvider:t.managed_provider?{status:t.managed_provider.status}:null}}async startOAuthLogin(t){let n;try{n=await this.http.post("/oauth/login",t===void 0?{}:{region:t})}catch(i){if(t!==void 0&&di(i)&&i.code===dF)n=await this.http.post("/oauth/login",{});else throw i}return n.status==="authenticated"?{flowId:n.flow_id,provider:n.provider,status:"authenticated"}:{flowId:n.flow_id,provider:n.provider,status:"pending",verificationUri:n.verification_uri,verificationUriComplete:n.verification_uri_complete,userCode:n.user_code,expiresIn:n.expires_in,interval:n.interval,expiresAt:n.expires_at}}async pollOAuthLogin(){const t=await this.http.get("/oauth/login");return t?{flowId:t.flow_id,status:t.status,resolvedAt:t.resolved_at,errorMessage:t.error_message}:null}async cancelOAuthLogin(){const t=await this.http.delete("/oauth/login");return{cancelled:t.cancelled,status:t.status}}async logout(){return{loggedOut:(await this.http.post("/oauth/logout",{})).logged_out}}async getUsage(){const t=await this.http.get("/oauth/usage");if(t.kind==="error")return{kind:"error",message:t.message,status:t.status};const n=i=>({name:i.name,window:i.window,used:i.used,limit:i.limit,resetAt:i.reset_at});return{kind:"ok",summary:t.summary===null?null:n(t.summary),limits:t.limits.map(n),extraUsage:t.extra_usage===null?null:{balanceCents:t.extra_usage.balance_cents,totalCents:t.extra_usage.total_cents,monthlyChargeLimitEnabled:t.extra_usage.monthly_charge_limit_enabled,monthlyChargeLimitCents:t.extra_usage.monthly_charge_limit_cents,monthlyUsedCents:t.extra_usage.monthly_used_cents,currency:t.extra_usage.currency}}}async getUserInfo(){return this.http.get("/oauth/userinfo")}async getOAuthRegion(){try{const t=await Promise.race([this.http.get("/oauth/region"),new Promise((n,i)=>{setTimeout(()=>i(new Error("oauth region probe timed out")),xAe)})]);return t.region==="mainland-cn"||t.region==="global"?t.region:null}catch{return null}}async uploadFile(t){const n=new FormData;n.append("file",t.file,t.name??(t.file instanceof File?t.file.name:"upload")),t.name!==void 0&&n.append("name",t.name);const i=await this.http.postForm("/files",n,t.onProgress===void 0?void 0:{onUploadProgress:t.onProgress});return{id:i.id,name:i.name,mediaType:i.media_type,size:i.size}}getFileUrl(t){return Hd(this.opts.origin,`/files/${encodeURIComponent(t)}`)}async getFileBlob(t){return this.http.getBlob(`/files/${encodeURIComponent(t)}`)}getSessionMediaUrl(t,n){return Hd(this.opts.origin,`/sessions/${encodeURIComponent(t)}/media/${encodeURIComponent(n)}`)}async getSessionMediaBlob(t,n){return this.http.getBlob(`/sessions/${encodeURIComponent(t)}/media/${encodeURIComponent(n)}`)}async readHostFileContent(t){const n=await this.http.getBlob("/fs:content",{path:t},{maxBytes:gw});if(n.size>gw)throw new A7({size:n.size,limit:gw});const i=n.type,o=!MAe(i),s=i||(o?"application/octet-stream":"text/plain");if(o){const l=await TAe(n);return{path:t,content:l,encoding:"base64",mime:s,isBinary:!0,size:n.size}}const r=await n.text();return{path:t,content:r,encoding:"utf-8",mime:s,isBinary:!1,size:n.size}}connectEvents(t){const n=TD(this.opts.origin,this.opts.identity.clientId),i=this.opts.projectorFactory(),o=new cF({wsUrl:n,clientId:this.opts.identity.clientId,tracer:this.tracer,credentialStore:this.opts.credentialStore,mainAgentOnly:this.opts.mainAgentOnly,handlers:{onWireEvent:s=>{const r=M4e(s),l=T4e(s),a=_4e(s);a.type==="historyCompacted"&&!fF(a.reason)&&t.onResync(a.sessionId,a.beforeSeq),t.onEvent(a,{sessionId:r,seq:l})},onRawAgentEvent:s=>{const{type:r,seq:l,session_id:a,payload:u,offset:c}=s,d=i.project(r,u,a,{offset:c});for(const h of d){const p=u?.turnId,m=h.type==="assistantDelta"&&typeof p=="number"&&typeof c=="number"&&(r==="assistant.delta"||r==="thinking.delta")?{turnId:p,offset:c,kind:r==="assistant.delta"?"text":"thinking"}:void 0;h.type==="historyCompacted"&&!fF(h.reason)&&t.onResync(a,l),t.onEvent(h,{sessionId:a,seq:l,stream:m})}},onResync:(s,r,l)=>{i.reset(s),t.onResync(s,r,l)},onConnectionState:s=>{t.onConnectionChange(s)},onReplayComplete:()=>{t.onReplayComplete?.()},onError:(s,r,l)=>{t.onError(s,r,l)},onTerminalOutput:(s,r,l,a)=>{t.onTerminalOutput?.(s,r,l,a)},onTerminalExit:(s,r,l)=>{t.onTerminalExit?.(s,r,l)},onTranscriptReset:(s,r,l,a)=>{t.onTranscriptReset?.(s,r,l,a)},onTranscriptOps:(s,r,l,a)=>t.onTranscriptOps?.(s,r,l,a)??!0}});return o.connect(),{subscribe(s,r){o.subscribe(s,r??{seq:0})},unsubscribe(s){o.unsubscribe(s),i.forgetSession(s)},subscribeTranscript(s,r,l){o.subscribeTranscript(s,r,l)},unsubscribeTranscript(s,r){o.unsubscribeTranscript(s,r)},bindNextPromptId(s,r){i.bindNextPromptId(s,r)},abort(s,r){o.abort(s,r)},terminalAttach(s,r,l){o.terminalAttach(s,r,l)},terminalInput(s,r,l){o.terminalInput(s,r,l)},terminalResize(s,r,l,a){o.terminalResize(s,r,l,a)},terminalDetach(s,r){o.terminalDetach(s,r)},terminalClose(s,r){o.terminalClose(s,r)},markSideChannelAgent(s,r){o.markSideChannelAgent(s,r),i.markSideChannelAgent(r)},health(){return o.health()},reconnect(){o.reconnect()},close(){o.close()}}}connectTranscriptChannel(t){const n=`${this.opts.identity.clientId}-transcript`,i=new cF({wsUrl:TD(this.opts.origin,n),clientId:n,tracer:this.tracer,credentialStore:this.opts.credentialStore,handlers:{onWireEvent:()=>{},onResync:()=>{},onConnectionState:o=>t.onConnectionState?.(o),onError:(o,s,r)=>t.onError?.(o,s,r),onTranscriptReset:t.onTranscriptReset,onTranscriptOps:t.onTranscriptOps}});return i.connect(),{subscribe:()=>{},unsubscribe:()=>{},subscribeTranscript:(o,s,r)=>i.subscribeTranscript(o,s,r),unsubscribeTranscript:(o,s)=>i.unsubscribeTranscript(o,s),bindNextPromptId:()=>{},abort:()=>{},terminalAttach:()=>{},terminalInput:()=>{},terminalResize:()=>{},terminalDetach:()=>{},terminalClose:()=>{},markSideChannelAgent:()=>{},health:()=>i.health(),reconnect:()=>i.reconnect(),close:()=>i.close()}}}function yw(e){return{changed:e.changed.map(t=>({providerId:t.provider_id,providerName:t.provider_name,added:t.added,removed:t.removed})),unchanged:e.unchanged,failed:e.failed}}function MAe(e){const t=e.toLowerCase().split(";")[0].trim();return t===""||t==="text/plain"||t.startsWith("text/")?!0:/(json|xml|javascript|typescript|x-yaml|yaml|svg|x-sh|x-python|markdown|csv|html|css)$/.test(t)}function TAe(e){return new Promise((t,n)=>{const i=new FileReader;i.onload=()=>{const o=typeof i.result=="string"?i.result:"";t(o.slice(o.indexOf(",")+1))},i.onerror=()=>n(i.error),i.readAsDataURL(e)})}const EAe="main",LAe=new Set(["turn.started","turn.step.started","turn.step.completed","turn.step.retrying","turn.step.interrupted","turn.ended","thinking.delta","assistant.delta","tool.use","tool.call.started","tool.call.delta","tool.progress","tool.result","agent.status.updated","prompt.completed","prompt.aborted","error"]);function kw(e="msg_"){const t=Date.now().toString(36).padStart(10,"0"),n=Math.random().toString(36).slice(2,12).padEnd(10,"0");return`${e}${t}${n}`}function NAe(e){if(!e||typeof e!="object")return{input:0,output:0,cacheRead:0,cacheCreate:0};const t=e;return{input:t.inputOther??t.input_tokens??0,output:t.output??t.output_tokens??0,cacheRead:t.inputCacheRead??t.cache_read_input_tokens??0,cacheCreate:t.inputCacheCreation??t.cache_creation_input_tokens??0}}function hF(){return{turnPromptId:new Map,currentPromptId:void 0,totalInput:0,totalOutput:0,totalCacheRead:0,totalCacheCreate:0,contextTokens:0,contextLimit:0,turnCount:0,model:"",subagentMeta:new Map,restartedThisRun:new Set,settledByKernel:new Set,retiredBindings:new Set,registrationSeq:0,registrationOrderByKey:new Map,retryActive:!1}}function Xr(e,t){const n=e[t];return typeof n=="string"?n:void 0}function Fr(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ma(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function DAe(e){if(!e||typeof e!="object")return null;const t=e,n=t.budget,i=n&&typeof n=="object"?n:{},o=Xr(t,"status");if(o!=="active"&&o!=="paused"&&o!=="blocked"&&o!=="complete")return null;const s=Xr(t,"goalId")??Xr(t,"goal_id")??"goal",r=Xr(t,"objective")??"";return{goalId:s,objective:r,completionCriterion:Xr(t,"completionCriterion")??Xr(t,"completion_criterion"),status:o,turnsUsed:Fr(t,"turnsUsed")??Fr(t,"turns_used")??0,tokensUsed:Fr(t,"tokensUsed")??Fr(t,"tokens_used")??0,wallClockMs:Fr(t,"wallClockMs")??Fr(t,"wall_clock_ms")??0,terminalReason:Xr(t,"terminalReason")??Xr(t,"terminal_reason"),budget:{tokenBudget:Ma(i,"tokenBudget")??Ma(i,"token_budget"),remainingTokens:Ma(i,"remainingTokens")??Ma(i,"remaining_tokens"),turnBudget:Ma(i,"turnBudget")??Ma(i,"turn_budget"),remainingTurns:Ma(i,"remainingTurns")??Ma(i,"remaining_turns"),wallClockBudgetMs:Ma(i,"wallClockBudgetMs")??Ma(i,"wall_clock_budget_ms"),remainingWallClockMs:Ma(i,"remainingWallClockMs")??Ma(i,"remaining_wall_clock_ms"),overBudget:i.overBudget===!0||i.over_budget===!0}}}function Fd(e,t,n,i,o){if(typeof i!="string"||i.length===0)return null;const r={...t.subagentMeta.get(i)??{id:i,agentId:i,sessionId:n,kind:"subagent",description:e("tasks.dockSubagent"),status:"running",createdAt:new Date().toISOString(),subagentPhase:"queued"},...o,id:i,sessionId:n,kind:"subagent"};return t.subagentMeta.set(i,r),r}function FAe(e,t,n){if(t==="turn.step.started")return null;if(t==="tool.use"||t==="tool.call.started"){const i=Xr(n,"name")??Xr(n,"toolName")??"tool",o=pz(e,RAe(i)),s=OAe(e,i,n.args??n.input);return s?`Calling ${o}: ${s}`:`Calling ${o}`}if(t==="tool.progress"){const i=n.update;if(i&&typeof i=="object"){const s=Xr(i,"text");if(s)return bw(s);const r=Xr(i,"message");if(r)return bw(r)}const o=Xr(n,"message");if(o)return bw(o)}return null}function RAe(e){return e.replace(/_\d+$/,"")}const pF=2e3;function bw(e){return e.length>pF?`${e.slice(0,pF)}…`:e}function OAe(e,t,n){if(n==null)return"";const i=typeof n=="string"?n:JSON.stringify(n);return C7(e,t,i)}function PAe(e,t,n,i,o,s,r){if(r.has(i)&&o==="turn.step.started")return[];if(o==="assistant.delta"){const p=Xr(s,"delta");if(!p)return[];const m=t.subagentMeta.get(i),g=Fd(e,t,n,i,{status:"running",subagentPhase:"working",startedAt:m?.startedAt??new Date().toISOString()}),y=[];return g&&y.push({type:"taskCreated",sessionId:n,task:g}),y.push({type:"taskProgress",sessionId:n,taskId:i,outputChunk:p,stream:"stdout",kind:"text"}),y}const l=FAe(e,o,s);if(l===null||l.length===0)return[];const a=o==="tool.progress"?s.update:void 0,u=a!=null&&typeof a=="object"?a.replace===!0:!1,c=t.subagentMeta.get(i),d=Fd(e,t,n,i,{status:"running",subagentPhase:"working",startedAt:c?.startedAt??new Date().toISOString()}),h=[];return d&&h.push({type:"taskCreated",sessionId:n,task:d}),h.push({type:"taskProgress",sessionId:n,taskId:i,outputChunk:l,stream:"stdout",replace:u}),h}function $Ae(e){return Array.isArray(e)?e.map(t=>D4(t)):[]}function BAe(e){return{inputTokens:e.totalInput,outputTokens:e.totalOutput,cacheReadTokens:e.totalCacheRead,cacheCreationTokens:e.totalCacheCreate,totalCostUsd:0,contextTokens:e.contextTokens,contextLimit:e.contextLimit,turnCount:e.turnCount}}const zAe=new Set(["session.meta.updated","goal.updated","compaction.completed","compaction.started","compaction.cancelled","compaction.blocked","hook.result","mcp.server.status","skill.activated","tool.list.updated"]);function jAe(e,t,n){switch(e){case"session.meta.updated":{const i=t?.patch?.title??t?.title,o=t?.patch?.lastPrompt,s={};return typeof i=="string"&&i.length>0&&(s.title=i),typeof o=="string"&&(s.lastPrompt=o),s.title!==void 0||s.lastPrompt!==void 0?[{type:"sessionMetaUpdated",sessionId:n,...s}]:[]}case"goal.updated":{const i=DAe(t?.snapshot??null);return[{type:"goalUpdated",sessionId:n,goal:i?.status==="complete"?null:i}]}case"compaction.completed":{const i=t?.result??{};return[{type:"compactionCompleted",sessionId:n,tokensBefore:typeof i.tokensBefore=="number"?i.tokensBefore:void 0,tokensAfter:typeof i.tokensAfter=="number"?i.tokensAfter:void 0,summary:typeof i.summary=="string"?i.summary:void 0},{type:"historyCompacted",sessionId:n,beforeSeq:0,reason:"auto_compact"}]}case"compaction.started":return[{type:"compactionStarted",sessionId:n,trigger:t?.trigger==="manual"?"manual":"auto",instruction:typeof t?.instruction=="string"?t.instruction:void 0}];case"compaction.cancelled":return[{type:"compactionCancelled",sessionId:n}];default:return[]}}function HAe(e){const{t}=e,n=new Map,i=new Set;function o(h){let p=n.get(h);return p||(p=hF(),n.set(h,p)),p}function s(h){n.set(h,hF())}function r(h){n.delete(h)}function l(h){return n.has(h)}function a(h){i.add(h)}function u(h,p){const m=o(h);m.currentPromptId=p}function c(h,p,m,g){try{return d(h,p,m,g)}catch(y){return Ku("[agentProjector] Error projecting event:",h,y instanceof Error?y.message:y),[]}}function d(h,p,m,g){if(zAe.has(h))return jAe(h,p,m);const y=o(m),b=p,v=[],C=b?.agentId;if(typeof C=="string"&&C!==EAe){const w=i.has(C);if(h==="prompt.submitted"){if(!w)return[];const M=b?.promptId,N=b?.userMessageId;if(!M||!N)return[];const T=$Ae(b?.content);return T.length===0?[]:[{type:"messageCreated",agentId:C,message:{id:N,sessionId:m,role:"user",content:T,createdAt:typeof b?.createdAt=="string"?b.createdAt:new Date().toISOString(),promptId:M}}]}if(w&&(h==="thinking.delta"||h==="assistant.delta")){const M=b?.delta??"";return M?[{type:"agentDelta",sessionId:m,agentId:C,delta:{[h==="thinking.delta"?"thinking":"text"]:M}}]:[]}if(w&&h==="turn.ended")return[{type:"agentTurnEnded",sessionId:m,agentId:C,reason:b?.reason}];if(LAe.has(h))return PAe(t,y,m,C,h,b??{},i)}switch(h){case"turn.started":{const w=b?.turnId,M=y.currentPromptId??kw("pr_");y.currentPromptId=M,w!==void 0&&y.turnPromptId.set(w,M),v.push({type:"turnActiveChanged",sessionId:m,active:!0});break}case"turn.step.started":case"thinking.delta":case"assistant.delta":case"tool.use":case"tool.call.started":case"tool.call.delta":case"tool.progress":case"tool.result":break;case"turn.step.completed":{const w=NAe(b?.usage);y.totalInput+=w.input,y.totalOutput+=w.output,y.totalCacheRead+=w.cacheRead,y.totalCacheCreate+=w.cacheCreate;break}case"agent.status.updated":{b?.model&&(y.model=b.model),b?.contextTokens!==void 0&&(y.contextTokens=b.contextTokens),b?.maxContextTokens!==void 0&&(y.contextLimit=b.maxContextTokens);const w=b?.phase;w!=null&&w.kind==="retrying"?(y.retryActive=!0,v.push({type:"turnRetry",sessionId:m,retry:{failedAttempt:Fr(w,"failedAttempt")??0,nextAttempt:Fr(w,"nextAttempt")??0,maxAttempts:Fr(w,"maxAttempts")??0,delayMs:Fr(w,"delayMs")??0,errorName:Xr(w,"errorName"),statusCode:Fr(w,"statusCode"),turnId:Fr(w,"turnId")}})):y.retryActive&&w!==void 0&&w!==null&&typeof w.kind=="string"&&(y.retryActive=!1,v.push({type:"turnRetry",sessionId:m,retry:void 0})),v.push({type:"sessionUsageUpdated",sessionId:m,usage:BAe(y),model:y.model||void 0,swarmMode:b?.swarmMode===!0?!0:b?.swarmMode===!1?!1:void 0,planMode:b?.planMode===!0?!0:b?.planMode===!1?!1:void 0,thinking:typeof b?.thinkingEffort=="string"&&b.thinkingEffort.length>0?b.thinkingEffort:void 0});break}case"turn.ended":{const w=b?.turnId,M=(w!==void 0?y.turnPromptId.get(w):void 0)??y.currentPromptId;v.push({type:"turnActiveChanged",sessionId:m,active:!1,reason:b?.reason,promptId:M}),y.turnCount++,y.currentPromptId=void 0;break}case"prompt.completed":{const w=b?.promptId;typeof w=="string"&&w.length>0&&v.push({type:"promptCompleted",sessionId:m,promptId:w,reason:b?.reason??"completed"});break}case"prompt.aborted":{const w=b?.promptId;typeof w=="string"&&w.length>0&&v.push({type:"promptAborted",sessionId:m,promptId:w});break}case"turn.step.retrying":{y.retryActive=!0,v.push({type:"turnRetry",sessionId:m,retry:{failedAttempt:Fr(b??{},"failedAttempt")??0,nextAttempt:Fr(b??{},"nextAttempt")??0,maxAttempts:Fr(b??{},"maxAttempts")??0,delayMs:Fr(b??{},"delayMs")??0,errorName:Xr(b??{},"errorName"),statusCode:Fr(b??{},"statusCode"),turnId:typeof b?.turnId=="number"?b.turnId:void 0}});break}case"turn.step.interrupted":break;case"subagent.spawned":{const w=typeof b?.subagentId=="string"&&b.subagentId.length>0?b.subagentId:kw("task_"),M=typeof b?.taskId=="string"&&b.taskId.length>0?b.taskId:void 0,N=M!==void 0&&M!==w?y.subagentMeta.get(M):void 0,T=y.subagentMeta.get(w);N!==void 0&&y.subagentMeta.delete(M),M!==void 0&&!y.registrationOrderByKey.has(M)&&y.registrationOrderByKey.set(M,++y.registrationSeq);const S=T===void 0||N===void 0?T??N:{...T,createdAt:N.createdAt,startedAt:N.startedAt??T.startedAt,runInBackground:!0,backgroundTaskId:T.backgroundTaskId??M},x=S?.backgroundTaskId??(S!==void 0&&M!==void 0&&S.id===M?M:void 0),A=M!==void 0?y.registrationOrderByKey.get(M):void 0,E=x!==void 0?y.registrationOrderByKey.get(x):void 0,I=y.retiredBindings.has(M??"")||A!==void 0&&E!==void 0&&A0?b.model:S?.model,thinkingEffort:typeof b?.thinkingEffort=="string"&&b.thinkingEffort.length>0?b.thinkingEffort:S?.thinkingEffort,parentToolCallId:typeof b?.parentToolCallId=="string"?b.parentToolCallId:S?.parentToolCallId,swarmIndex:typeof b?.swarmIndex=="number"?b.swarmIndex:S?.swarmIndex,runInBackground:R?b?.runInBackground===!0||b?.runInBackground===void 0&&S?.runInBackground===!0:b?.runInBackground===!0||S?.runInBackground===!0,outputPreview:R?void 0:S?.outputPreview,outputBytes:R?void 0:S?.outputBytes,outputLines:R?void 0:S?.outputLines,suspendedReason:R?void 0:S?.suspendedReason,text:R?void 0:S?.text,backgroundTaskId:I?S?.backgroundTaskId:R?M:M??S?.backgroundTaskId};y.subagentMeta.set(z.id,z),v.push({type:"taskCreated",sessionId:m,task:z});break}case"subagent.started":{const w=typeof b?.subagentId=="string"?b.subagentId:void 0,M=w!==void 0&&(y.subagentMeta.get(w)?.status!==void 0&&y.subagentMeta.get(w).status!=="running"||y.settledByKernel.has(w));M&&y.settledByKernel.delete(w);const N=Fd(t,y,m,b?.subagentId,{subagentPhase:"working",status:"running",startedAt:new Date().toISOString(),suspendedReason:void 0,...M?{createdAt:new Date().toISOString(),completedAt:void 0,completedAtEstimated:void 0,outputPreview:void 0,outputBytes:void 0,outputLines:void 0,text:void 0}:{}});M&&w!==void 0&&y.restartedThisRun.add(w),N&&v.push({type:"taskCreated",sessionId:m,task:N});break}case"subagent.suspended":{const w=Fd(t,y,m,b?.subagentId,{subagentPhase:"suspended",status:"running",suspendedReason:typeof b?.reason=="string"?b.reason:void 0});w&&v.push({type:"taskCreated",sessionId:m,task:w});break}case"subagent.completed":{const w=typeof b?.resultSummary=="string"?b.resultSummary:void 0,M=Fd(t,y,m,b?.subagentId,{subagentPhase:"completed",status:"completed",completedAt:new Date().toISOString(),completedAtEstimated:!0,outputPreview:w});M&&v.push({type:"taskCreated",sessionId:m,task:M}),M!==null&&y.restartedThisRun.delete(M.id),v.push({type:"taskCompleted",sessionId:m,taskId:b?.subagentId??"",status:"completed",outputPreview:w});break}case"subagent.failed":{const w=typeof b?.error=="string"?b.error:void 0,M=Fd(t,y,m,b?.subagentId,{subagentPhase:"failed",status:"failed",completedAt:new Date().toISOString(),completedAtEstimated:!0,outputPreview:w});M&&v.push({type:"taskCreated",sessionId:m,task:M}),M!==null&&y.restartedThisRun.delete(M.id),v.push({type:"taskCompleted",sessionId:m,taskId:b?.subagentId??"",status:"failed",outputPreview:w});break}case"error":{v.push({type:"unknown",raw:{_agentError:!0,code:b?.code,message:b?.message,name:b?.name,details:b?.details,retryable:b?.retryable}});break}case"warning":{v.push({type:"unknown",raw:{_agentWarning:!0,message:b?.message}});break}case"task.started":case"background.task.started":{const w=b?.info??{},M=typeof w.startedAt=="number"?new Date(w.startedAt).toISOString():void 0,N=typeof w.taskId=="string"?w.taskId:typeof w.taskId=="number"?String(w.taskId):kw("task_"),T=typeof w.description=="string"?w.description:typeof w.command=="string"?w.command:t("tasks.defaultDescription");if(w.kind==="agent"){const x=typeof w.agentId=="string"&&w.agentId.length>0?w.agentId:void 0;if(x!==void 0){const A=y.subagentMeta.get(x),E=y.registrationOrderByKey.get(N),I=A?.backgroundTaskId!==void 0?y.registrationOrderByKey.get(A.backgroundTaskId):void 0;if(y.retiredBindings.has(N)||E!==void 0&&I!==void 0&&EI.backgroundTaskId===N);if(A===void 0&&(y.retiredBindings.has(N)||y.registrationOrderByKey.has(N)&&y.registrationOrderByKey.get(N)0&&y.settledByKernel.add(w.agentId),v.push({type:"taskCompleted",sessionId:m,taskId:typeof w.taskId=="string"?w.taskId:typeof w.taskId=="number"?String(w.taskId):"",status:w.status==="killed"?"cancelled":M?"failed":"completed"});break}}return v}return{project:c,bindNextPromptId:u,reset:s,forgetSession:r,markSideChannelAgent:a,hasSessionState:l}}function WAe(e){return new IAe({origin:e.origin,identity:e.identity,tracer:e.tracer,credentialStore:e.credentialStore,projectorFactory:()=>HAe({t:e.t}),mainAgentOnly:e.mainAgentOnly})}const qAe={t:e=>e},mF="Sub Agent";function UAe(){return{sessions:[],activeSessionId:void 0,approvalsBySession:{},planReviewByToolCallId:{},questionsBySession:{},tasksBySession:{},goalBySession:{},goalVersionBySession:{},lastSeqBySession:{},turnActiveBySession:{},turnErrorBySession:{},turnRetryBySession:{},compactionBySession:{},warnings:[]}}function VAe(e){return{...e,sessions:e.sessions,approvalsBySession:{...e.approvalsBySession},planReviewByToolCallId:{...e.planReviewByToolCallId},questionsBySession:{...e.questionsBySession},tasksBySession:{...e.tasksBySession},goalBySession:{...e.goalBySession},goalVersionBySession:{...e.goalVersionBySession},lastSeqBySession:{...e.lastSeqBySession},turnActiveBySession:{...e.turnActiveBySession},turnErrorBySession:{...e.turnErrorBySession},turnRetryBySession:{...e.turnRetryBySession},compactionBySession:{...e.compactionBySession},warnings:[...e.warnings]}}function KAe(e,t,n){if(t!==void 0&&n!==void 0&&n>0){const i=e.lastSeqBySession[t]??0;n>i&&(e.lastSeqBySession[t]=n)}}function Ry(e,t){const n=e.sessions.find(i=>i.id===t.sessionId)?.lastSeq??0;return t.seq>Math.max(e.lastSeqBySession[t.sessionId]??0,n)}const ZAe={"provider.connection_error":"connection","provider.auth_error":"auth","provider.rate_limit":"rateLimit","provider.overloaded":"overloaded","provider.filtered":"filtered","provider.api_error":"api","context.overflow":"contextOverflow"};function RA(e,t){const n=[],i=(r,l)=>{typeof l=="number"||typeof l=="boolean"?n.push({label:r,value:String(l)}):typeof l=="string"&&l.length>0&&n.push({label:r,value:l})};i(t("warnings.details.code"),e.code);const o=e.details??{};i(t("warnings.details.status"),o.statusCode),i(t("warnings.details.requestId"),o.requestId),i(t("warnings.details.errorName"),e.name);for(const[r,l]of Object.entries(o))r==="statusCode"||r==="requestId"||i(r,l);const s=(e.code!==void 0?ZAe[e.code]:void 0)??"title";return{severity:"error",title:t(`warnings.agentError.${s}`),message:e.message,details:n.length>0?n:void 0}}function GAe(e,t,n,i=qAe){const o=VAe(e);switch(KAe(o,n.sessionId,n.seq),t.type){case"sessionCreated":{o.sessions.some(r=>r.id===t.session.id)||(o.sessions=[t.session,...o.sessions]);break}case"sessionUpdated":{o.sessions=o.sessions.map(s=>s.id===t.session.id?{...t.session,pullRequest:s.pullRequest}:s);break}case"sessionDeleted":{const s=t.sessionId;o.sessions=o.sessions.filter(r=>r.id!==s),delete o.tasksBySession[s],delete o.goalBySession[s],delete o.goalVersionBySession[s],delete o.approvalsBySession[s],delete o.questionsBySession[s],delete o.lastSeqBySession[s],delete o.turnActiveBySession[s],delete o.turnErrorBySession[s],delete o.turnRetryBySession[s],o.activeSessionId===s&&(o.activeSessionId=void 0);break}case"sessionWorkChanged":{if(!Ry(e,n))break;let s;o.sessions=o.sessions.map(r=>r.id!==t.sessionId?r:(s=t.pendingInteraction??(t.busy?r.pendingInteraction:"none"),{...r,busy:t.busy,mainTurnActive:t.mainTurnActive??(t.busy?r.mainTurnActive:!1),pendingInteraction:s,lastTurnReason:t.lastTurnReason})),s==="none"?(delete o.approvalsBySession[t.sessionId],delete o.questionsBySession[t.sessionId]):s==="question"&&delete o.approvalsBySession[t.sessionId],t.mainTurnActive===!0?o.turnActiveBySession[t.sessionId]=!0:(t.mainTurnActive===!1||!t.busy)&&(delete o.turnActiveBySession[t.sessionId],delete o.turnRetryBySession[t.sessionId]);break}case"sessionMetaUpdated":{o.sessions=o.sessions.map(s=>s.id===t.sessionId?{...s,title:t.title??s.title,lastPrompt:t.lastPrompt??s.lastPrompt}:s);break}case"sessionUsageUpdated":{o.sessions=o.sessions.map(s=>{if(s.id!==t.sessionId)return s;const r=t.model&&t.model.length>0?t.model:s.model;return{...s,usage:t.usage,model:r}});break}case"historyCompacted":break;case"compactionStarted":{o.compactionBySession={...o.compactionBySession,[t.sessionId]:{status:"running",trigger:t.trigger}};break}case"compactionCompleted":{const s=t.sessionId,{[s]:r,...l}=o.compactionBySession;o.compactionBySession=l;break}case"compactionCancelled":{const{[t.sessionId]:s,...r}=o.compactionBySession;o.compactionBySession=r;break}case"messageCreated":case"messageUpdated":case"assistantDelta":case"toolOutput":break;case"approvalRequested":{const s=t.sessionId,r=o.approvalsBySession[s]??[];r.some(u=>u.approvalId===t.approval.approvalId)||(o.approvalsBySession[s]=[...r,t.approval]);const a=t.approval.display;a?.kind==="plan_review"&&typeof a.plan=="string"&&a.plan.length>0&&(o.planReviewByToolCallId={...o.planReviewByToolCallId,[t.approval.toolCallId]:{plan:a.plan,path:typeof a.path=="string"?a.path:void 0}});break}case"approvalResolved":case"approvalExpired":{const s=t.sessionId,r=t.approvalId,l=o.approvalsBySession[s]??[];o.approvalsBySession[s]=l.filter(a=>a.approvalId!==r);break}case"questionRequested":{const s=t.sessionId,r=o.questionsBySession[s]??[];r.some(a=>a.questionId===t.question.questionId)||(o.questionsBySession[s]=[...r,t.question]);break}case"questionAnswered":case"questionDismissed":{const s=t.sessionId,r=t.questionId,l=o.questionsBySession[s]??[];o.questionsBySession[s]=l.filter(a=>a.questionId!==r);break}case"taskCreated":{const s=t.sessionId,r=o.tasksBySession[s]??[],l=r.findIndex(h=>h.id===t.task.id),a=t.task.backgroundTaskId===void 0?-1:r.findIndex(h=>h.id===t.task.backgroundTaskId),u=a!==-1&&l!==-1&&a!==l?r[a]:void 0,c=u!==void 0?r.filter((h,p)=>p!==a):r,d=c.findIndex(h=>h.id===t.task.id||t.task.backgroundTaskId!==void 0&&h.id===t.task.backgroundTaskId);if(d===-1)o.tasksBySession[s]=[...c,t.task];else{const h=[...c],p=c[d],m=t.task.backgroundTaskId!==void 0&&(t.task.backgroundTaskId===p.backgroundTaskId||p.id===t.task.backgroundTaskId)||p.id===t.task.id&&(p.kind!=="subagent"||p.agentId===void 0),g=(m&&p.status!=="running"?p:void 0)??(u!==void 0&&u.status!=="running"?u:void 0),y=g!==void 0&&(t.task.status==="running"||t.task.status!==g.status),b=!m&&p.status!=="running"||t.task.backgroundTaskId!==void 0&&p.backgroundTaskId!==void 0&&t.task.backgroundTaskId!==p.backgroundTaskId,v=m&&p.completedAt!==void 0&&p.completedAtEstimated!==!0;h[d]={...t.task,status:y?g.status:t.task.status,subagentPhase:y?g.subagentPhase:t.task.subagentPhase,completedAt:y?g.completedAt:v?p.completedAt:t.task.completedAt,completedAtEstimated:y?g.completedAtEstimated:v?p.completedAtEstimated:t.task.completedAtEstimated,outputLines:y?g.outputLines:b?u?.outputLines??t.task.outputLines:p.outputLines??u?.outputLines??t.task.outputLines,text:y?g.text:b?u?.text??t.task.text:p.text??u?.text??t.task.text,outputPreview:y?g.outputPreview:t.task.outputPreview??(b?u?.outputPreview:p.outputPreview??u?.outputPreview),outputBytes:y?g.outputBytes:t.task.outputBytes??(b?u?.outputBytes:p.outputBytes??u?.outputBytes),description:t.task.description===mF&&p.description!==mF?p.description:t.task.description,swarmIndex:t.task.swarmIndex??p.swarmIndex,parentToolCallId:t.task.parentToolCallId??p.parentToolCallId,subagentType:t.task.subagentType??p.subagentType,model:t.task.model??p.model,thinkingEffort:t.task.thinkingEffort??p.thinkingEffort,runInBackground:b?t.task.runInBackground:t.task.runInBackground??p.runInBackground,backgroundTaskId:b?t.task.backgroundTaskId:t.task.backgroundTaskId??p.backgroundTaskId,agentId:t.task.agentId??p.agentId},o.tasksBySession[s]=h}break}case"taskProgress":{const s=t.sessionId,r=o.tasksBySession[s]??[];o.tasksBySession[s]=r.map(l=>{if(l.id!==t.taskId)return l;if(l.kind==="subagent"&&t.kind==="text")return{...l,text:(l.text??"")+t.outputChunk};const a=l.outputLines??[];if(t.replace===!0){const c=a.length>0?[...a.slice(0,-1),t.outputChunk]:[t.outputChunk];return{...l,outputLines:c}}if(a.at(-1)===t.outputChunk)return l;const u=[...a,t.outputChunk];return{...l,outputLines:l.kind==="subagent"?u:u.slice(-40)}});break}case"taskCompleted":{const s=t.sessionId,r=o.tasksBySession[s]??[];o.tasksBySession[s]=r.map(l=>l.id!==t.taskId&&l.backgroundTaskId!==t.taskId||t.status==="completed"&&(l.status==="cancelled"||l.status==="failed")||t.status==="failed"&&l.status==="cancelled"?l:{...l,status:t.status,completedAt:l.completedAt??new Date().toISOString(),completedAtEstimated:l.completedAt===void 0?!0:l.completedAtEstimated,outputPreview:t.outputPreview??l.outputPreview,outputBytes:t.outputBytes??l.outputBytes});break}case"goalUpdated":{const s=t.sessionId;o.goalVersionBySession[s]=(o.goalVersionBySession[s]??0)+1,t.goal===null||t.goal.status==="complete"?delete o.goalBySession[s]:o.goalBySession[s]=t.goal;break}case"configChanged":{o.config=t.config;break}case"modelCatalogChanged":break;case"agentDelta":case"agentTurnEnded":break;case"promptCompleted":case"promptAborted":break;case"turnActiveChanged":{if(!Ry(e,n))break;if(o.sessions=o.sessions.map(s=>s.id===t.sessionId?{...s,mainTurnActive:t.active}:s),t.active)o.turnActiveBySession[t.sessionId]=!0,delete o.turnErrorBySession[t.sessionId],delete o.turnRetryBySession[t.sessionId];else{delete o.turnActiveBySession[t.sessionId],delete o.turnRetryBySession[t.sessionId];const s=t.reason===void 0||t.reason==="completed"?"completed":"failed",r=o.tasksBySession[t.sessionId];r!==void 0&&(o.tasksBySession[t.sessionId]=r.map(l=>l.kind!=="subagent"||l.status!=="running"||l.runInBackground===!0?l:{...l,status:s,subagentPhase:s,completedAt:l.completedAt??new Date().toISOString(),completedAtEstimated:l.completedAt===void 0?!0:l.completedAtEstimated,suspendedReason:void 0}))}break}case"turnRetry":{if(!Ry(e,n))break;t.retry===void 0?delete o.turnRetryBySession[t.sessionId]:o.turnRetryBySession[t.sessionId]=t.retry;break}case"unknown":{const s=t.raw;if(!(s&&s._noop===!0))if(s&&s._agentError){if(Ry(e,n)){if(n.sessionId!==void 0){const r=s.details??{};o.turnErrorBySession[n.sessionId]={code:s.code,message:s.message,name:s.name,retryable:s.retryable,statusCode:typeof r.statusCode=="number"?r.statusCode:void 0,requestId:typeof r.requestId=="string"?r.requestId:void 0}}(n.sessionId===void 0||n.sessionId!==e.activeSessionId)&&(o.warnings=[...o.warnings,RA(s,i.t)])}}else if(s&&s._agentWarning){const r=s.message??s.code??i.t("warnings.agentWarningFallback");o.warnings=[...o.warnings,`${i.t("warnings.noteLabel")}: ${r}`]}else{const r=s?.type??"(unknown)";o.warnings=[...o.warnings,i.t("warnings.unhandledEvent",{type:r})]}break}}return o}function QAe(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const o of n)if(e[o]!==t[o])return!1;return!0}function YAe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n]*)>([\s\S]*?)<\/notification>/g,XAe=/([\w-]+)="([^"]*)"/g,e6e=/]*)>[\s\S]*?<\/output-file>/,t6e=/]*)>([\s\S]*?)<\/output-preview>/,n6e=/^Title: (.*)$/m,i6e=/^Severity: (.*)$/m;function L9(e){return e.replaceAll(""",'"').replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}function ww(e){const t={};for(const n of e.matchAll(XAe))n[1]!==void 0&&n[2]!==void 0&&(t[n[1]]=L9(n[2]));return t}function o6e(e,t,n){const i=ww(e),o=n6e.exec(t)?.[1]?.trim()??"",s=i6e.exec(t)?.[1]?.trim()??"";let r=t.split(` -`).filter(h=>!h.startsWith("Title: ")&&!h.startsWith("Severity: ")).join(` -`);const l=r.search(/^<\w/m);l!==-1&&(r=r.slice(0,l)),r=r.trim();const a=e6e.exec(t),u=a?(()=>{const h=ww(a[1]??""),p=Number(h.bytes);return h.path!==void 0&&h.path!==""?{path:h.path,bytes:Number.isFinite(p)?p:void 0}:void 0})():void 0,c=t6e.exec(t),d=c?(()=>{const h=ww(c[1]??""),p=(c[2]??"").replace(/^\n/,""),m=p.indexOf(` -`),g=L9(m===-1?"":p.slice(m+1)).replace(/\n$/,""),y=Number(h.bytes),b=Number(h.total_bytes);return{text:g,bytes:Number.isFinite(y)?y:void 0,totalBytes:Number.isFinite(b)?b:void 0,truncated:h.truncated==="true"?!0:h.truncated==="false"?!1:void 0}})():void 0;return{id:i.id??"",category:i.category??"",type:i.type??"",sourceKind:i.source_kind??"",sourceId:i.source_id??"",agentId:i.agent_id,title:L9(o),severity:s,body:L9(r),outputFile:u,outputPreview:d,raw:n}}function s6e(e){if(!e.includes("(/^Background (process|agent)$/.test(u.description)&&(u={...u,description:""}),u),r=u6e.exec(n);if(r?.[1]!==void 0&&r[2]!==void 0)return s({status:r[2]==="timed out"?"timed_out":r[2],description:r[1],reason:r[3],rest:o});const l=c6e.exec(n);if(l?.[1]!==void 0)return s({status:"killed",description:l[1],userStopped:l[2]!==void 0,reason:l[3],rest:o});const a=d6e.exec(n);if(a?.[1]!==void 0&&a[2]!==void 0)return s({status:a[2]==="was killed"?"killed":a[2]==="timed out"?"timed_out":a[2],description:a[1],reason:a[3],rest:o})}function h6e(e){if(!_U(e.title))return;const t=f6e(e.body);if(!(t===void 0||t.status!==ab(e)))return t}const p6e=1e6,gF=5e3;function cc(e){return e===""?[]:e.endsWith(` -`)?e.slice(0,-1).split(` -`):e.split(` -`)}function ub(e,t){const n=cc(e),i=cc(t),o=n.length,s=i.length;if(o===0&&s===0)return[];if(o>gF||s>gF||(o+1)*(s+1)>p6e)return null;const r=Array.from({length:o+1},()=>Array.from({length:s+1},()=>0));for(let p=1;p<=o;p++)for(let m=1;m<=s;m++)r[p][m]=n[p-1]===i[m-1]?r[p-1][m-1]+1:Math.max(r[p-1][m],r[p][m-1]);const l=[];let a=o,u=s;for(;a>0||u>0;)a>0&&u>0&&n[a-1]===i[u-1]?(l.push({type:"context",text:n[a-1]}),a--,u--):u>0&&(a===0||r[a][u-1]>=r[a-1][u])?(l.push({type:"add",text:i[u-1]}),u--):(l.push({type:"del",text:n[a-1]}),a--);l.reverse();const c=[];let d=1,h=1;for(const p of l)p.type==="context"?(c.push({type:"context",text:p.text,oldNo:d,newNo:h}),d++,h++):p.type==="add"?(c.push({type:"add",text:p.text,newNo:h}),h++):(c.push({type:"del",text:p.text,oldNo:d}),d++);return c}const vF=500;function yF(e,t){const n=[],i=cc(e),o=cc(t),s=Math.min(i.length,vF),r=Math.min(o.length,vF);for(let l=1;l<=s;l++)n.push({type:"del",text:i[l-1],oldNo:l});i.length>s&&n.push({type:"context",text:`… ${i.length-s} more lines …`});for(let l=1;l<=r;l++)n.push({type:"add",text:o[l-1],newNo:l});return o.length>r&&n.push({type:"context",text:`… ${o.length-r} more lines …`}),n}function IU(e){let t=0,n=0;for(const i of e)i.type==="add"?t++:i.type==="del"&&n++;return{added:t,removed:n}}function Yc(e){const t=e;return t?.kind!=="user"||!Array.isArray(t.skillActivations)?[]:t.skillActivations.flatMap(n=>{if(typeof n!="object"||n===null)return[];const i=n;return typeof i.skillName!="string"?[]:[{name:i.skillName,...typeof i.skillArgs=="string"?{args:i.skillArgs}:{}}]})}function m6e(e){return{content:e.content,skillActivations:Yc(e.metadata?.origin)}}function W0(e,t){return e.length===t.length&&e.every((n,i)=>{const o=t[i];return o!==void 0&&n.name===o.name&&n.args===o.args})}const g6e=/^read[_-]?media(?:file)?$/i,v6e=/^data:([^;]+);base64,(.*)$/s,y6e=/^<(image|video|audio)\s+path="([^"]+)">$/,k6e=/^<(image|video|audio)\s+path="([^"]+)">(?:<\/\1>)?$/,b6e=/Mime type:\s*([^.\s]+)/i,w6e=/Size:\s*(\d+)\s*bytes/i,C6e=/Original dimensions:\s*(\d+)x(\d+)\s*pixels/i,A6e="Image compressed to fit model limits:",x6e=/Image compressed to fit model limits:[\s\S]*?<\/system>/g;function kF(e){return e.includes(A6e)?e.replace(x6e,""):e}function S6e(e){return e.replaceAll(""",'"').replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}function bF(e){const t=k6e.exec(e.trim());return t?{kind:t[1],path:S6e(t[2])}:null}const MU=/^f_(?:[0-9A-Za-z]{26}|[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})$/,_6e=/f_(?:[0-9A-Za-z]{26}|[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})$/;function OA(e){const t=e.split(/[\\/]/).at(-1)??"",n=t.lastIndexOf("."),i=n>0?t.slice(0,n):t;return MU.test(i)?i:void 0}const Uc='Attached file "',TU=" — open it with the Read tool";function I6e(e,t,n,i){const o=`-${e}`,s=i.endsWith(o)?i.slice(0,-o.length):i,r=_6e.exec(s)?.[0];return{name:e,mediaType:t,size:Number(n),fileId:r!==void 0&&MU.test(r)?r:void 0}}const EU="attachmentRecords",M6e=65536;function T6e(e,t,n){const i=t+Uc.length,o=e.slice(i,n),s=o.indexOf('" (');if(s<=0)return!1;const r=o.indexOf(", ",s+3);if(r<=s+3)return!1;let l=i+r+2;if(l>=n||e.charCodeAt(l)<48||e.charCodeAt(l)>57)return!1;for(;l=48&&e.charCodeAt(l)<=57;)l++;return e.startsWith(" bytes): ",l)}function E6e(e,t,n){let i=e.indexOf(Uc,t);for(;i>=0&&i=n?n:s;if(T6e(e,i,r))return i;if(s<0||s>=n)return-1;i=s}return-1}function L6e(e,t){const n=t+Uc.length,i=Math.min(e.length,n+M6e),o=e.slice(n,i),s=o.indexOf('" (');if(s<=0)return null;const r=n+s,l=o.indexOf(", ",s+3);if(l<=s+3)return null;const a=n+l+2;let u=a;for(;u=48&&e.charCodeAt(u)<=57;)u++;if(u===a||!e.startsWith(" bytes): ",u))return null;const c=e.slice(a,u),d=u+9,h=E6e(e,r,i),p=h>=0?Math.min(h,i):i,m=e.slice(d,p),g=o.slice(0,s),y=`-${g}${TU}`;let b=m.lastIndexOf(y);for(;b>=0;){const C=m.slice(0,b),w=Math.max(C.lastIndexOf("/"),C.lastIndexOf("\\"));if(!/\s/.test(C.slice(w+1)))break;b=m.lastIndexOf(y,b-1)}if(b<0)return null;const v=m.slice(0,b+1+g.length);return{start:t,end:d+b+y.length,info:I6e(g,o.slice(s+3,l),c,v)}}function Yx(e){if(!e.includes(TU))return[];const t=[];let n=e.indexOf(Uc);for(;n>=0;){const i=L6e(e,n);n=i?e.indexOf(Uc,i.end):e.indexOf(Uc,n+Uc.length),i&&t.push(i)}return t}function wF(e){const t=Yx(e);if(t.length===0)return e;let n="",i=0;for(const o of t)n+=e.slice(i,o.start),i=o.end;return n+e.slice(i)}function N6e(e){const t=[];for(const o of e.content)o.type==="file"&&t.push({fileId:o.fileId,name:o.name});const n=[...t],i=e.metadata?.[EU];if(Array.isArray(i))for(const o of i){if(typeof o!="object"||o===null)continue;const s=o.fileId,r=o.name,l={fileId:typeof s=="string"&&s.length>0?s:void 0,name:typeof r=="string"&&r.length>0?r:void 0},a=n.findIndex(u=>l.fileId!==void 0?u.fileId===l.fileId:u.fileId===void 0&&u.name===l.name);a>=0?n.splice(a,1):t.push(l)}return t.length>0?t:null}function D6e(e){const t=N6e(e);if(t)return{kind:"paired",records:t};let n=0;for(const s of e.content)if(s.type==="text")for(const r of PA(s.text))n=Math.max(n,r);const i=e.metadata?.origin;for(const s of[i?.skillArgs,i?.commandArgs])if(typeof s=="string")for(const r of PA(s))n=Math.max(n,r);if(n===0)return{kind:"legacy"};let o=0;for(const s of e.content)s.type==="text"&&(o+=Yx(s.text).length);return{kind:"pill",keepLast:n,total:o}}function F6e(e){let t=0;const n=e.kind==="pill"?Math.max(0,e.total-e.keepLast):0;return i=>{const o=Yx(i);if(o.length===0)return{notices:[],text:i};const s=[];for(const a of o){const u=t++;if(e.kind==="legacy")s.push(a);else if(e.kind==="pill")u>=n&&s.push(a);else{const c=a.info.fileId,d=e.records.findIndex(h=>c!==void 0?h.fileId===c:h.fileId===void 0&&h.name===a.info.name);d>=0&&(e.records.splice(d,1),s.push(a))}}if(s.length===0)return{notices:[],text:i};let r="",l=0;for(const a of s)r+=i.slice(l,a.start),l=a.end;return{notices:s.map(a=>a.info),text:r+i.slice(l)}}}const R6e=/(?=0&&e[i]==="\\";)n+=1,i-=1;return n%2===1}function LU(e){let t="",n=0,i=0;for(;i0?t:void 0}return[JSON.stringify(e)]}}function W6e(e,t){if(cr(e)==="task")for(const n of t??[]){const i=/^agent_id:\s*(\S+)\s*$/.exec(n);if(i?.[1])return i[1]}}function q6e(e,t){return{id:e.agentId??e.id,toolCallId:e.parentToolCallId,name:e.description,kind:e.kind,subagentType:e.subagentType,prompt:e.command??t,model:e.model,thinkingEffort:e.thinkingEffort,phase:e.status==="completed"?"completed":e.status==="failed"?"failed":e.status==="cancelled"?"cancelled":e.subagentPhase??"working",status:e.status,summary:e.outputPreview,outputLines:e.outputLines,text:e.text,suspendedReason:e.suspendedReason,swarmIndex:e.swarmIndex}}function NU(e){const t=e.display??{},n=typeof t.kind=="string"?t.kind:"";if(n==="diff"){const i=typeof t.path=="string"?t.path:"";if(Array.isArray(t.diff))return{kind:"diff",path:i,diff:t.diff};const o=typeof t.old_text=="string"?t.old_text:typeof t.before=="string"?t.before:void 0,s=typeof t.new_text=="string"?t.new_text:typeof t.after=="string"?t.after:void 0;if(o!==void 0&&s!==void 0){const r=ub(o,s)??yF(o,s);return{kind:"diff",path:i,diff:r}}return{kind:"diff",path:i,diff:[]}}if(n==="file_io"){const i=typeof t.path=="string"?t.path:"",o=typeof t.operation=="string"?t.operation:"";if(o==="write"&&typeof t.content=="string")return{kind:"file",path:i,content:t.content};if(o==="edit"&&typeof t.before=="string"&&typeof t.after=="string"){const r=ub(t.before,t.after)??yF(t.before,t.after);return{kind:"diff",path:i,diff:r}}const s=typeof t.detail=="string"?t.detail:void 0;return{kind:"fileop",op:o||n,path:i,detail:s}}if(n==="shell"||n==="command"){const i=typeof t.command=="string"?t.command:e.action;return{kind:"shell",command:i,cwd:typeof t.cwd=="string"?t.cwd:void 0,danger:typeof t.danger=="string"?t.danger:Iae(i)}}if(n==="file_content"||n==="file")return{kind:"file",path:typeof t.path=="string"?t.path:"",content:typeof t.content=="string"?t.content:"",language:typeof t.language=="string"?t.language:void 0};if(n==="file_op"||n==="fileop")return{kind:"fileop",op:typeof t.operation=="string"?t.operation:typeof t.op=="string"?t.op:n,path:typeof t.path=="string"?t.path:"",detail:typeof t.detail=="string"?t.detail:void 0};if(n==="url_fetch"||n==="url")return{kind:"url",method:typeof t.method=="string"?t.method:void 0,url:typeof t.url=="string"?t.url:e.action};if(n==="search")return{kind:"search",query:typeof t.query=="string"?t.query:e.action,scope:typeof t.scope=="string"?t.scope:void 0};if(n==="invocation"||n==="agent_call"||n==="skill_call")return{kind:"invocation",kind2:typeof t.kind=="string"?t.kind:n,name:typeof t.name=="string"?t.name:e.toolName,description:typeof t.description=="string"?t.description:void 0};if(n==="todo"||n==="todo_list")return{kind:"todo",items:(Array.isArray(t.items)?t.items:[]).map(s=>{const r=s??{};return{title:typeof r.title=="string"?r.title:"",status:typeof r.status=="string"?r.status:"pending"}})};if(n==="plan_review"){const i=typeof t.plan=="string"?t.plan:"",o=typeof t.path=="string"?t.path:void 0,r=(Array.isArray(t.options)?t.options:[]).map(l=>{const a=l??{},u=typeof a.label=="string"?a.label:"";if(!u)return null;const c=typeof a.description=="string"?a.description:void 0;return{label:u,description:c}}).filter(l=>l!==null);return{kind:"plan_review",plan:i,path:o,options:r.length>0?r:void 0}}return{kind:"generic",summary:e.action}}function DU(e){const t=` -`,n=` -`,i=e.indexOf(t),o=e.lastIndexOf(n);return i>=0&&o>=i+t.length?e.slice(i+t.length,o):U6e(e)}function U6e(e){const t=e.split(` -`);return t.length>=2&&t[0]?.startsWith(""?t.slice(1,-1).join(` -`):e}function V6e(e){const t=e.metadata?.origin;if(t?.kind==="cron_job"||t?.kind==="cron_missed")return t.kind}function K6e(e){const t=e.content.filter(n=>n.type==="text").map(n=>n.text).join(` -`);return DU(t)}function Z6e(e,t){const n=e.metadata?.origin??{},i=K6e(e);return t==="cron_missed"?{text:i,cron:{missedCount:typeof n.count=="number"?n.count:void 0}}:{text:i,cron:{jobId:typeof n.jobId=="string"?n.jobId:void 0,cron:typeof n.cron=="string"?n.cron:void 0,recurring:typeof n.recurring=="boolean"?n.recurring:void 0,coalescedCount:typeof n.coalescedCount=="number"?n.coalescedCount:void 0,stale:typeof n.stale=="boolean"?n.stale:void 0}}}function G6e(e,t,n){const{text:i,cron:o}=Z6e(e,n);return{id:e.id,role:"cron",no:t,text:i,createdAt:e.createdAt,cron:o}}function Q6e(e){const t=e.metadata?.origin,n=t?.kind;return n===void 0||n==="user"?!0:n==="skill_activation"||n==="plugin_command"?t?.trigger==="user-slash":!1}function Y6e(e){const t=e.metadata?.["kimiWeb.steeredPromptIds"];if(Array.isArray(t)){const i=t.filter(o=>typeof o=="string"&&o.length>0);if(i.length>0)return i}if(e.promptId!==void 0&&e.promptId.length>0)return[e.promptId];const n=e.metadata?.["kimiWeb.promptId"];if(typeof n=="string"&&n.length>0)return[n]}function J6e(e){return e.metadata?.origin?.kind==="compaction_summary"}function X6e(e,t){return e===null?!1:e.promptId===void 0||t===void 0||e.promptId===t}function e7e(e){if(!e||e.length===0)return;const t="Plan saved to: ";for(const n of e)if(n.startsWith(t))return n.slice(t.length).trim()}function t7e(e){const t=[];for(const n of e){const i=t.at(-1);n.type==="text"&&i?.type==="text"?i.text+=n.text:n.type==="thinking"&&i?.type==="thinking"?i.thinking+=n.thinking:n.type==="thinking"?t.push({type:"thinking",thinking:n.thinking}):t.push({...n})}return JSON.stringify(t)}function z4(e,t,n,i=!0,o={},s={},r){const l=[];let a=r?.startNo??1;const u=r?.collect,c=new Map;for(const g of t)c.set(g.toolCallId,g);let d=null;function h(g=!1){if(!d)return;const y=d;if(d=null,!g&&y.blocks.length===0&&y.textParts.length===0&&y.thinkingParts.length===0&&y.tools.length===0)return;if(!g||!i)for(let v=0;vN.kind==="tool"&&N.tool.id===w.id);M&&M.kind==="tool"&&(M.tool=w)}const b={id:y.id,role:"assistant",no:a++,text:y.textParts.join(` -`),thinking:y.thinkingParts.length>0?y.thinkingParts.join(` -`):void 0,tools:y.tools.length>0?y.tools:void 0,blocks:y.blocks.length>0?y.blocks:void 0,approval:y.approval,approvalId:y.approvalId,durationMs:y.durationMs,createdAt:y.createdAt,endedAt:y.endedAt,goalContinuation:y.goalContinuation};l.push(b),u?.(b,y.sources)}function p(g,y){let b=null;for(const v of y)if(v.type==="text"){if(v.text){b==="text"?g.textParts[g.textParts.length-1]+=v.text:g.textParts.push(v.text);const C=g.blocks.at(-1);C&&C.kind==="text"?C.text+=(b==="text"?"":` -`)+v.text:g.blocks.push({kind:"text",text:v.text}),b="text"}}else if(v.type==="thinking"){if(v.thinking){b==="thinking"?g.thinkingParts[g.thinkingParts.length-1]+=v.thinking:g.thinkingParts.push(v.thinking);const C=g.blocks.at(-1);if(C&&C.kind==="thinking"){C.thinking+=(b==="thinking"?"":` -`)+v.thinking;const w=[C.startedAt,v.startedAt].filter(T=>T!==void 0).sort()[0],M=C.startedAt!==void 0&&C.durationMs===void 0||v.startedAt!==void 0&&v.durationMs===void 0,N=[C,v].flatMap(T=>T.startedAt!==void 0&&T.durationMs!==void 0?[Date.parse(T.startedAt)+T.durationMs]:[]);C.startedAt=w,C.durationMs=!M&&w!==void 0&&N.length>0?Math.max(...N)-Date.parse(w):void 0}else g.blocks.push({kind:"thinking",thinking:v.thinking,startedAt:v.startedAt,durationMs:v.durationMs});b="thinking"}}else if(v.type==="toolUse"){b=null;const C=c.get(v.toolCallId),w=v.toolName==="ExitPlanMode"?s[v.toolCallId]:void 0,M={id:v.toolCallId,name:v.toolName,arg:typeof v.input=="string"?v.input:JSON.stringify(v.input),agentId:cr(v.toolName)==="task"?v.agentRefs?.find(N=>N.role!=="member")?.agentId??v.agentRefs?.[0]?.agentId:void 0,status:"running",output:v.outputLines,plan:w,planPath:v.toolName==="ExitPlanMode"?w?.path??o[v.toolCallId]?.path:void 0};g.tools.push(M),g.blocks.push({kind:"tool",tool:M}),C&&(g.approval=NU(C),g.approvalId=C.approvalId)}else if(v.type==="toolResult"){b=null;const C=g.tools.findIndex(w=>w.id===v.toolCallId);if(C!==-1){const w=g.tools[C],M=Jx(v.output),N={...w,status:v.isError?"error":"ok",output:M,media:v.isError?void 0:H6e(w.name,v.output),agentId:w.agentId??W6e(w.name,M)};N.name==="ExitPlanMode"&&!N.planPath&&(N.planPath=e7e(N.output)),g.tools[C]=N;const T=g.blocks.find(S=>S.kind==="tool"&&S.tool.id===v.toolCallId);T&&T.kind==="tool"&&(T.tool=N)}}else b=null}function m(g,y){if(g.type==="image"||g.type==="video"){const b=g.type,v=g.source;if(v.kind==="url")return{url:v.url,kind:b};if(v.kind==="base64")return{url:`data:${v.mediaType};base64,${v.data}`,kind:b};if(v.kind==="file"&&n)return{url:n(v.fileId),kind:b,fileId:v.fileId};if(v.kind==="sessionMedia")return{url:r?.getSessionMediaUrl?.(y,v.fileId)??"",kind:b,fileId:v.fileId,sessionId:y}}if(g.type==="file"&&n){if(g.mediaType.startsWith("image/"))return{url:n(g.fileId),kind:"image",fileId:g.fileId};if(g.mediaType.startsWith("video/"))return{url:n(g.fileId),kind:"video",fileId:g.fileId}}}for(const g of e){if(g.role==="system")continue;if(J6e(g)){h();const w=g.metadata?.[Bz],M={id:g.id,role:"compaction",no:a,text:g.content.filter(N=>N.type==="text").map(N=>N.text).join(` -`),compaction:{trigger:w?.trigger,tokensBefore:w?.tokensBefore,tokensAfter:w?.tokensAfter}};l.push(M),u?.(M,[g]);continue}if(g.role==="user"){const w=V6e(g),M=g.metadata?.origin?.kind,N=M==="skill_activation"&&g.metadata?.origin?.trigger!=="user-slash";if(w===void 0&&(M==="injection"||N))continue;if(w===void 0&&(M==="task"||M==="background_task"||M==="task_notification")){const oe=g.content.filter(fe=>fe.type==="text").map(fe=>fe.text).join(` -`),Z=r6e(g.metadata),Q=Z!==void 0?[Z]:s6e(oe);if(Q.length>0){d??={id:g.id,promptId:void 0,textParts:[],thinkingParts:[],tools:[],blocks:[],approval:void 0,approvalId:void 0,seenSigs:new Set,sources:[g],createdAt:g.createdAt};for(const fe of Q)d.blocks.push({kind:"notification",notification:{...fe,createdAt:g.createdAt}})}continue}if(h(),w!==void 0){const oe=G6e(g,a++,w);l.push(oe),u?.(oe,[g]);continue}if(M==="system_trigger"&&g.metadata?.origin?.name==="goal_continuation"){d={id:g.id,promptId:void 0,textParts:[],thinkingParts:[],tools:[],blocks:[],approval:void 0,approvalId:void 0,seenSigs:new Set,sources:[g],createdAt:g.createdAt,goalContinuation:!0};continue}if(!Q6e(g))continue;const T=g.metadata?.origin,S=T?.kind==="skill_activation"&&T?.trigger==="user-slash",x=T?.kind==="plugin_command"&&T?.trigger==="user-slash",A=m6e(g),E=A.skillActivations,I=A.content,R=[];let W=[];const z=F6e(D6e(g)),F=new Set,O=oe=>{const Z={kind:"file",url:oe.fileId&&n?n(oe.fileId):"",fileId:oe.fileId,name:oe.name,mediaType:oe.mediaType,size:oe.size};W.push(Z),F.add(Z)};for(const oe of I){if(oe.type==="text")if(S){const Q=bF(oe.text);if(Q&&(Q.kind==="video"||Q.kind==="image")&&n){const fe=OA(Q.path);if(fe){W.push({url:n(fe),kind:Q.kind,fileId:fe});continue}}for(const fe of z(oe.text).notices)O(fe)}else if(x)R.push(T.commandArgs??"");else{const Q=bF(oe.text);if(Q&&(Q.kind==="video"||Q.kind==="image")&&n){const pe=OA(Q.path);if(pe){W.push({url:n(pe),kind:Q.kind,fileId:pe});continue}}const fe=z(oe.text);if(fe.notices.length>0){for(const X of fe.notices)O(X);if(fe.text.trim().length===0)continue;const pe=kF(fe.text);if(pe!==fe.text&&pe.trim().length===0)continue;R.push(pe);continue}const de=kF(oe.text);if(de!==oe.text&&de.trim().length===0)continue;R.push(de)}const Z=m(oe,g.sessionId);if(Z){W.push({url:Z.url,kind:Z.kind,name:oe.type==="file"?oe.name:void 0,fileId:Z.fileId,sessionId:Z.sessionId});continue}oe.type==="file"&&n&&W.push({kind:"file",url:n(oe.fileId),fileId:oe.fileId,name:oe.name,mediaType:oe.mediaType||void 0,size:oe.size})}const B=new Map;for(const oe of F){if(oe.fileId===void 0)continue;const Z=`${oe.kind}|${oe.fileId}`;B.set(Z,(B.get(Z)??0)+1)}W=W.filter(oe=>{if(F.has(oe)||oe.fileId===void 0)return!0;const Z=`${oe.kind}|${oe.fileId}`,Q=B.get(Z)??0;return Q>0?(B.set(Z,Q-1),!1):!0});const j=S?T?.skillArgs??"":R.join(` -`),$=PA(j),V=$6e(j),ne=W.filter(oe=>oe.kind==="file"),K=W.filter(oe=>oe.kind==="image"||oe.kind==="video"),ee=[...$].some(oe=>oe<=ne.length),ue=[...V].some(oe=>oe<=K.length),ie=ee||ue?W:[];let ye=0,Te=0;const Ee=W.filter(oe=>oe.kind==="file"?(ye+=1,!(ee&&$.has(ye))):oe.kind==="image"||oe.kind==="video"?(Te+=1,!(ue&&V.has(Te))):!0),Me=g.metadata?.["kimiWeb.steeredPromptIds"],G={id:g.id,role:"user",no:a++,text:j,hasUndoAnchor:g.metadata?.["kimiWeb.settledWithoutEcho"]===!0||g.metadata?.["kimiWeb.steered"]===!0?!1:void 0,steered:g.metadata?.["kimiWeb.steered"]===!0||Array.isArray(Me)&&Me.length>0?!0:void 0,promptIds:Y6e(g),attachments:Ee.length>0?Ee:void 0,inlineAttachments:ie.length>0?ie:void 0,skillActivation:S?{name:T.skillName,args:T.skillArgs}:void 0,skillActivations:E.length>0?E.map(oe=>({name:oe.name,args:oe.args})):void 0,pluginCommand:x?{pluginId:T.pluginId,commandName:T.commandName,args:T.commandArgs}:void 0,createdAt:g.createdAt};l.push(G),u?.(G,[g]);continue}if(g.role==="tool"){d&&(d.sources.push(g),p(d,g.content),d.endedAt=g.createdAt);continue}const y=g.promptId;X6e(d,y)?d!==null&&d.promptId===void 0&&y!==void 0&&(d.promptId=y):(h(),d={id:g.id,promptId:y,textParts:[],thinkingParts:[],tools:[],blocks:[],approval:void 0,approvalId:void 0,seenSigs:new Set,sources:[],durationMs:g.durationMs,createdAt:g.createdAt});const v=d;if(v===null)continue;const C=t7e(g.content);v.promptId!==void 0&&v.seenSigs.has(C)||(v.seenSigs.add(C),v.sources.push(g),g.durationMs!==void 0&&(v.durationMs=g.durationMs),p(v,g.content),g.endedAt!==void 0?v.endedAt=g.endedAt:g.id!==v.id&&(v.endedAt=g.createdAt))}return h(!0),l}function FU(e,t,n){return e.state==="running"&&e.frames.at(-1)===t&&!n}function n7e(e,t){if(t.size===0)return;let n=!1;for(const l of t.values())if(l.settledAt===void 0){n=!0;break}if(!n)return;const i=new Date().toISOString(),o=e.items.findLast(l=>l.kind==="turn"&&l.state==="running"),s=o?.kind==="turn"?o.steps.findLast(l=>l.state==="running"):void 0,r=e.interactions.some(l=>l.state==="pending");for(const l of e.items)if(l.kind==="turn")for(const a of l.steps){const u=r&&a===s;for(const c of a.frames){if(c.kind!=="thinking")continue;const d=t.get(c.frameId);d===void 0||d.settledAt!==void 0||FU(a,c,u)||(d.settledAt=i)}}}function i7e(e,t){if(t.size===0)return;const n=new Set;for(const i of e.items)if(i.kind==="turn")for(const o of i.steps)for(const s of o.frames)s.kind==="thinking"&&n.add(s.frameId);for(const i of[...t.keys()])n.has(i)||t.delete(i)}function o7e(e,t,n,i){const o=e.items.filter(h=>h.kind==="turn"),s=o[0]?.turnId,r=o.length===1?s:void 0,l=new Map(e.tasks.map(h=>[h.taskId,h])),a=new Map(e.prompts.map(h=>[h.promptId,h])),u=OU(e.prompts,RU(e.items)),c=e.items.flatMap(h=>h.kind==="turn"?Xx(h,e.attachments,l,h.turnId===s?n?.createdAt:void 0,h.turnId===r?n?.disposedAt:void 0,i?.sessionId,{promptById:a,promptForTurn:u}):[]),d=e.meta.activity==="turn";return z4(c,[],t,d,{},{},{getSessionMediaUrl:i?.getSessionMediaUrl}).map(u7e)}function CF(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n!="object"||n===null)continue;const i=n;if(i.type!=="file")continue;const o=typeof i.fileId=="string"?i.fileId:i.file_id;t.push({fileId:typeof o=="string"?o:void 0,name:typeof i.name=="string"?i.name:void 0})}return t}function AF(e,t){return t.length===0?e:{...e,[EU]:t}}const s7e=new Set(["user","skill_activation","plugin_command"]);function r7e(e){return(e.origin.payload??e.origin)?.kind}function l7e(e){const t=e.content;if(!Array.isArray(t))return;const n=[];for(const i of t)if(typeof i=="object"&&i!==null&&i.type==="text"){const o=i.text;typeof o=="string"&&n.push(o)}return n.join("")}function RU(e){const t=new Set;for(const n of e)if(n.kind==="turn"){for(const i of n.steps)for(const o of i.frames)if(o.kind==="text")for(const s of o.promptIds??[])t.add(s)}return t}function OU(e,t){const n=new Set(t??[]);return i=>{const o=r7e(i);if(o!==void 0&&!s7e.has(o)||i.prompt===void 0&&(i.attachmentIds??[]).length===0)return;const s=wF(i.prompt??"");for(const r of e){if(n.has(r.promptId))continue;const l=l7e(r);if(l!==void 0&&wF(l)===s)return n.add(r.promptId),r}}}function Xx(e,t,n,i,o,s="",r){const l=[],a=new Map(t.map(b=>[b.attachmentId,b])),u=$A([e.startedAt,...e.steps.map(b=>b.startedAt),i])??"",c=xF(e.endedAt)??xF(o),d=e.triggerPromptId??e.turnId,h=e.origin.payload??e.origin,p=(e.attachmentIds??[]).length>0,m=r?.includeOrigin===!0&&Yc(h).length>0;if(e.prompt!==void 0&&e.prompt.length>0||p||m){const b=e.prompt!==void 0&&e.prompt.length>0?[{type:"text",text:e.prompt}]:[];for(const v of e.attachmentIds??[]){const C=SF(a.get(v));C!==void 0&&b.push(C)}l.push({id:`${e.turnId}:input`,sessionId:s,role:"user",content:b,createdAt:u,promptId:d,metadata:AF(r?.includeOrigin===!0||e.origin.kind==="task"&&(e.prompt??"").includes("0;if(v.role==="user"){if(v.taskId!==void 0){if(v.text.length===0&&!C)continue;const A=a7e(v.taskId,v.text,n.get(v.taskId));l.push({id:v.frameId,sessionId:"",role:"user",content:[{type:"text",text:v.text}],createdAt:b.startedAt??u,promptId:d,metadata:{origin:{kind:"task",taskId:v.taskId},[SU]:A}});continue}const w=v.text.length>0?[{type:"text",text:v.text}]:[];for(const A of v.attachmentIds??[]){const E=SF(a.get(A));E!==void 0&&w.push(E)}const M=v.promptIds?.map(A=>r?.promptById?.get(A)).find(A=>A!==void 0),N=[];for(const A of v.promptIds??[])N.push(...CF(r?.promptById?.get(A)?.content));const T=v.origin,S=Yc(T);if(v.text.length===0&&!C&&S.length===0)continue;const x={...S.length>0?{origin:T}:{},...(v.promptIds?.length??0)>0?{"kimiWeb.steeredPromptIds":v.promptIds}:{}};l.push({id:v.frameId,sessionId:s,role:"user",content:w,createdAt:M?.createdAt??b.startedAt??u,promptId:d,metadata:AF(Object.keys(x).length>0?x:void 0,N)});continue}if(v.text.length===0&&!C)continue;l.push({id:v.frameId,sessionId:"",role:"assistant",content:[{type:"text",text:v.text}],createdAt:b.startedAt??u,promptId:d})}else if(v.kind==="thinking"){if(v.text.length===0)continue;const C=r?.pendingInteractionAtByStepId?.get(b.stepId),w=FU(b,v,C!==void 0),M=r?.thinkingTiming,N=M?.get(v.frameId);let T,S;if(N!==void 0)N.settledAt===void 0&&!w&&(N.settledAt=new Date().toISOString()),T=N.startedAt,S=Cw(N.startedAt,N.settledAt);else if(M!==void 0&&w){const x=new Date().toISOString();M.set(v.frameId,{startedAt:x}),T=x}else T=b.startedAt,S=Cw(b.startedAt,$A([b.endedAt,C]));l.push({id:v.frameId,sessionId:"",role:"assistant",content:[{type:"thinking",thinking:v.text,startedAt:T,durationMs:S}],createdAt:b.startedAt??u,promptId:d})}else v.kind==="tool"&&(l.push({id:`${v.frameId}:call`,sessionId:"",role:"assistant",content:[{type:"toolUse",toolCallId:v.toolCallId,toolName:v.name,input:v.input??v.display??{},outputLines:v.state==="running"?Jx(v.output):void 0,agentRefs:v.agentRefs}],createdAt:b.startedAt??u,promptId:d}),v.state!=="running"&&l.push({id:`${v.frameId}:result`,sessionId:"",role:"tool",content:[{type:"toolResult",toolCallId:v.toolCallId,output:v.output??v.error??"",isError:v.state==="error"}],createdAt:b.endedAt??b.startedAt??u,promptId:d}));const g=e.durationMs??Cw(u||void 0,c),y=l.findLastIndex(b=>b.role==="assistant");return y>=0&&(g!==void 0||c!==void 0)&&(l[y]={...l[y],durationMs:g,endedAt:c??l[y].endedAt}),l}function a7e(e,t,n){const[i="",...o]=t.split(` -`),s=n?.state??"info";return{id:`task:${e}:${s}`,category:"task",type:`task.${s}`,sourceKind:n?.kind==="subagent"?"subagent":"background_task",sourceId:e,agentId:n?.agentId,title:i.trim(),severity:s==="completed"?"info":"warning",body:o.join(` -`).trim(),raw:t}}function u7e(e){if(e.createdAt!==""&&e.endedAt!=="")return e;const t={...e};return t.createdAt===""&&delete t.createdAt,t.endedAt===""&&delete t.endedAt,t}function $A(e){let t;for(const n of e){if(n===void 0)continue;const i=Date.parse(n);Number.isFinite(i)&&(t===void 0||i=0?n:void 0}const _F=6e3,BA=256*1024,c7e=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;function IF(e,t){return t===0?e:e-1}function d7e(e,t){const n=cc(t),i=[];let o=0;for(const s of e){if(s.type==="hunk"){const r=c7e.exec(s.text);if(!r)return null;const l=IF(Number(r[1]),r[2]===void 0?1:Number(r[2])),a=IF(Number(r[3]),r[4]===void 0?1:Number(r[4]));if(an.length)return null;for(;o=n.length||n[o]!==s.text)return null;o++,s.type==="context"&&i.push(s.text)}for(;oBA||cc(n).length>_F)return null;const i=d7e(e,n);return i===null||i.length>BA||cc(i).length>_F?null:{before:i,after:n}}const h7e=new Set(["assistantDelta","agentDelta","toolOutput","taskProgress"]);function p7e(e){return h7e.has(e.type)}const m7e=50,g7e=100,zA=32*1024,v7e={requestFrame(e){return typeof requestAnimationFrame=="function"?requestAnimationFrame(e):null},cancelFrame(e){typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(e)},requestTask(e){return setTimeout(e,m7e)},cancelTask(e){clearTimeout(e)}};function y7e(e,t,n={}){const i=n.scheduler??v7e,o=Math.max(1,Math.floor(n.maxItemsPerSlice??g7e)),s=[];let r=0,l=null,a=null,u=0,c=!1;const d=()=>s.length-r,h=()=>{u+=1,l!==null&&(i.cancelFrame(l),l=null),a!==null&&(i.cancelTask(a),a=null)},p=()=>{r===s.length?(s.length=0,r=0):r>=1024&&(s.splice(0,r),r=0)};let m;const g=()=>{if(c||l!==null||a!==null||d()===0)return;const b=++u,v=()=>{b===u&&m()};l=i.requestFrame(v),a=i.requestTask(v)};m=()=>{h();let b=0;for(;!c&&b{if(!c){if(t(b)){const v=s.length>r?s.at(-1):void 0,C=v===void 0?void 0:n.coalesce?.(v,b);C===void 0?s.push(b):s[s.length-1]=C,g();return}if(d()===0){e(b);return}s.push(b),m()}});return y.flush=()=>{if(!c){for(h();!c&&r{if(c||d()===0)return;let v=r;for(let C=r;C{c||(c=!0,h(),s.length=0,r=0)},y}function jA(e){if(e.type==="assistantDelta"){if(e.delta.text!==void 0&&e.delta.thinking===void 0)return{kind:"text",value:e.delta.text};if(e.delta.thinking!==void 0&&e.delta.text===void 0)return{kind:"thinking",value:e.delta.thinking}}}function k7e(e){if(e.appEvent.type!=="assistantDelta")return[e];const t=e.appEvent,n=e.meta.stream,i=jA(t);if(n===void 0||i===void 0||n.kind!==i.kind||i.value.length<=zA)return[e];const o=[];let s=0;for(;ss&&/[\uD800-\uDBFF]/u.test(i.value[r-1])&&/[\uDC00-\uDFFF]/u.test(i.value[r])&&(r-=1);const l=i.value.slice(s,r);o.push({appEvent:{...t,delta:i.kind==="text"?{text:l}:{thinking:l}},meta:{...e.meta,stream:{...n,offset:n.offset+s}}}),s=r}return o}function b7e(e,t){if(e.appEvent.type!=="assistantDelta"||t.appEvent.type!=="assistantDelta")return;const n=e.meta.stream,i=t.meta.stream,o=jA(e.appEvent),s=jA(t.appEvent);if(n===void 0||i===void 0||o===void 0||s===void 0||e.meta.sessionId!==t.meta.sessionId||e.appEvent.sessionId!==t.appEvent.sessionId||e.appEvent.messageId!==t.appEvent.messageId||e.appEvent.contentIndex!==t.appEvent.contentIndex||n.turnId!==i.turnId||n.kind!==i.kind||o.kind!==s.kind||n.kind!==o.kind||i.kind!==s.kind||i.offset!==n.offset+o.value.length||o.value.length+s.value.length>zA)return;const r=o.value+s.value;return{appEvent:{...e.appEvent,delta:o.kind==="text"?{text:r}:{thinking:r}},meta:{...t.meta,stream:{...n}}}}function w7e(e,t){const i=e.items.filter(p=>p.kind==="turn")[0]?.turnId,o=new Map(e.tasks.map(p=>[p.taskId,p])),s=new Map(e.prompts.map(p=>[p.promptId,p])),r=OU(e.prompts,RU(e.items)),l=p=>p.kind==="turn"?p.origin.payload??p.origin:void 0,a=new Set,u=C7e(e.items),c=e.items.flatMap((p,m)=>{if(p.kind==="turn"){const g=u.turnPart.get(m)??p,y=g.startedAt!==void 0||g.steps.some(b=>b.startedAt!==void 0);return MF(g,e.attachments,o,p.turnId===i&&!y&&e.hasMoreOlder!==!0?t.agentCreatedAt:void 0,void 0,t.sessionId,t.pendingInteractionAtByStepId,t.thinkingTiming,s,r)}if(p.kind==="marker"&&p.marker==="compaction"){const g=A7e(p.payload,p.at,t.sessionId,p.markerId,S7e(e.items,m));if(g===void 0)return[];const y=u.continuation.get(p.markerId);return y===void 0?[g]:[g,...MF(y,e.attachments,o,void 0,void 0,t.sessionId,t.pendingInteractionAtByStepId,t.thinkingTiming,s,r,!0,`:${p.markerId}`)]}if(p.kind==="marker"&&p.marker==="cron.fired"){const g=p.payload,y=g?.origin?.jobId,b=typeof g?.prompt=="string"?g.prompt:void 0,v=e.items.slice(m+1).find(w=>{if(w.kind!=="turn"||a.has(w.turnId))return!1;const M=l(w);return M?.kind==="cron_job"&&(y===void 0||M.jobId===y)&&(b===void 0||w.kind==="turn"&&DU(w.prompt??"")===b)});if(v!==void 0&&v.kind==="turn")return a.add(v.turnId),[];const C=x7e(p.payload,p.at,t.sessionId,p.markerId);return C===void 0?[]:[C]}return[]}),d=e.interactions.map(p=>h1(p,t.sessionId)).filter(p=>p!==void 0),h=e.meta.activity==="turn";return z4(c,d,t.getFileUrl,h,t.planReviewByToolCallId??{},t.plansByToolCallId??{},{getSessionMediaUrl:t.getSessionMediaUrl}).map(M7e)}function C7e(e){const t=new Map,n=new Map;for(let i=0;i[]);let a=-1;for(const u of o.steps){for(;a+1=s[a+1].at;)a+=1;a<0?r.push(u):l[a].push(u)}if(r.length!==o.steps.length){t.set(i,{...o,steps:r,endedAt:r.at(-1)?.endedAt,durationMs:void 0});for(let u=0;ug.startedAt),i])??"",promptId:e.turnId,metadata:{origin:h}}]:[],...Xx(e,t,n,i,o,s,{includeOrigin:c!==!0,pendingInteractionAtByStepId:r,thinkingTiming:l,promptById:a,promptForTurn:u})]}function A7e(e,t,n,i,o){const s=e;if(s?.phase!=="completed")return;const r=s.result??{},l={trigger:o,tokensBefore:typeof r.tokensBefore=="number"?r.tokensBefore:void 0,tokensAfter:typeof r.tokensAfter=="number"?r.tokensAfter:void 0};return{id:i,sessionId:n,role:"assistant",content:typeof r.summary=="string"?[{type:"text",text:r.summary}]:[],createdAt:t??"",metadata:{origin:{kind:"compaction_summary"},[Bz]:l}}}function x7e(e,t,n,i){const o=e,s=o?.origin;if(!(s?.kind!=="cron_job"||typeof o?.prompt!="string"))return{id:i,sessionId:n,role:"user",content:[{type:"text",text:o.prompt}],createdAt:t??"",metadata:{origin:s}}}function S7e(e,t){for(let n=t-1;n>=0;n--){const i=e[n];if(i?.kind!=="marker"||i.marker!=="compaction")continue;const o=i.payload;if(o?.phase==="started")return o.trigger==="manual"?"manual":"auto"}return"auto"}function h1(e,t){if(e.interactionKind!=="approval"||e.state!=="pending")return;const n=e.request??{};if(typeof n.toolName!="string"||typeof n.action!="string")return;const i=typeof e.toolCallId=="string"?e.toolCallId:typeof n.toolCallId=="string"?n.toolCallId:void 0;if(i!==void 0)return{approvalId:e.interactionId,sessionId:t,turnId:typeof n.turnId=="number"?n.turnId:void 0,toolCallId:i,toolName:n.toolName,action:n.action,display:n.display,expiresAt:"",createdAt:""}}function Dg(e,t){if(e.interactionKind!=="question"||e.state!=="pending")return;const n=e.request??{};if(!Array.isArray(n.questions))return;const i=typeof e.toolCallId=="string"?e.toolCallId:typeof n.toolCallId=="string"?n.toolCallId:typeof n.tool_call_id=="string"?n.tool_call_id:void 0;return{questionId:e.interactionId,sessionId:t,turnId:typeof n.turnId=="number"?n.turnId:typeof n.turn_id=="number"?n.turn_id:void 0,toolCallId:i,questions:n.questions.map(_7e),createdAt:""}}function _7e(e){const t=Array.isArray(e.options)?e.options:[];return{id:typeof e.id=="string"?e.id:"",question:typeof e.question=="string"?e.question:"",header:typeof e.header=="string"?e.header:void 0,body:typeof e.body=="string"?e.body:void 0,options:t.map(I7e),multiSelect:e.multi_select===!0,allowOther:e.allow_other===!0,otherLabel:typeof e.other_label=="string"?e.other_label:void 0,otherDescription:typeof e.other_description=="string"?e.other_description:void 0}}function I7e(e){const t=e??{};return{id:typeof t.id=="string"?t.id:"",label:typeof t.label=="string"?t.label:"",description:typeof t.description=="string"?t.description:void 0,recommended:t.recommended===!0||t.is_recommended===!0}}function M7e(e){if(e.createdAt!==""&&e.endedAt!=="")return e;const t={...e};return t.createdAt===""&&delete t.createdAt,t.endedAt===""&&delete t.endedAt,t}function T7e(){let e=[];const t=(n,i)=>{const s=w7e(n,i).map((r,l)=>{const a=JSON.stringify(r),u=e[l],c=u!==void 0&&u.fingerprint===a?u.turn:r;return e[l]={turn:c,fingerprint:a},c});return e.length=s.length,s};return t.reset=()=>{e=[]},t}function E7e(e,t,n){const i=D7e(e),o=N7e(e),s=new Map(e.prompts.map(d=>[d.promptId,d])),r=n.filter(d=>{const h=d.metadata?.["kimiWeb.promptId"];if(h===void 0||o===void 0)return!0;const p=s.get(h)?.steeredAt;return p===void 0||p>=o}),l=e.prompts.filter(L7e).filter(d=>!i.has(d.promptId)).filter(d=>o===void 0||d.steeredAt>=o);if(l.length===0)return[...r];l.sort((d,h)=>d.steeredAtt)&&(t=n.startedAt);return t}function D7e(e){const t=new Set;for(const n of e.items)if(n.kind==="turn"){for(const i of n.steps)for(const o of i.frames)if(!(o.kind!=="text"||o.role!=="user"))for(const s of o.promptIds??[])t.add(s)}return t}function F7e(e){return Array.isArray(e)?e.map(t=>D4(t)).filter(t=>t.type!=="text"||t.text.length>0):[]}function R7e(e){return e.startsWith("diff --git")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ ")||e.startsWith("new file mode")||e.startsWith("deleted file mode")||e.startsWith("old mode")||e.startsWith("new mode")||e.startsWith("similarity index")||e.startsWith("dissimilarity index")||e.startsWith("rename from")||e.startsWith("rename to")||e.startsWith("copy from")||e.startsWith("copy to")||e.startsWith("Binary files")}function O7e(e){const t=[];if(!e)return t;let n=0,i=0,o=!1;for(const s of e.split(` -`)){if(s.startsWith("diff --git")){o=!1;continue}if(!o&&R7e(s))continue;if(s.startsWith("@@")){const a=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(s);a&&(n=Number.parseInt(a[1],10),i=Number.parseInt(a[2],10)),o=!0,t.push({type:"hunk",text:s});continue}if(!o||s.startsWith("\\"))continue;const r=s.charAt(0),l=s.slice(1);r==="+"?(t.push({type:"add",text:l,newNo:i}),i+=1):r==="-"?(t.push({type:"del",text:l,oldNo:n}),n+=1):r===" "&&(t.push({type:"context",text:l,oldNo:n,newNo:i}),n+=1,i+=1)}return t}function TF(e){return e?e.split(` -`).map(t=>t.trimEnd()).filter(Boolean).at(-1)??"":""}function P7e(e){return e.suspendedReason||TF(e.text)||TF(e.outputLines?.join(` -`))||e.summary||""}function $7e(e){return e.suspendedReason?e.suspendedReason:e.text?e.text:e.outputLines&&e.outputLines.length>0?e.outputLines.join(` -`):e.summary??""}function B7e(e){return e==="completed"?"completed":e==="failed"?"failed":e==="aborted"?"cancelled":"working"}function EF(e,t){return{id:e.agentId??e.item??`result-${t}`,agentId:e.agentId,name:e.item??`subagent ${t+1}`,activity:e.body.split(` -`)[0]??"",phase:B7e(e.outcome),body:e.body}}function z7e(e,t){return!!(t.agentId&&e.agentId===t.agentId||t.item&&e.name.includes(t.item))}function j7e(e,t){const n=e.map(o=>({id:o.id,agentId:o.agentId,name:o.name,activity:P7e(o),phase:o.phase,body:$7e(o)}));if(!t)return n;const i=t.subagents.filter(o=>(o.outcome==="aborted"||o.state==="not_started")&&!e.some(s=>z7e(s,o))).map((o,s)=>EF(o,s));return n.length>0?[...n,...i]:t.subagents.map((o,s)=>EF(o,s))}const H7e=["queued","working","suspended","completed","failed","cancelled"];function PU(e){return e.status==="completed"?"completed":e.status==="failed"?"failed":e.status==="cancelled"?"cancelled":e.subagentPhase?e.subagentPhase:"working"}function W7e(){return{queued:0,working:0,suspended:0,completed:0,failed:0,cancelled:0}}function q7e(e){const t=new Map;for(const n of e){if(n.kind!=="subagent"||n.swarmIndex===void 0)continue;const i=n.parentToolCallId??"swarm",o=t.get(i)??[];o.push({id:n.id,agentId:n.agentId,name:n.description,subagentType:n.subagentType,model:n.model,thinkingEffort:n.thinkingEffort,phase:PU(n),summary:n.outputPreview,outputLines:n.outputLines,text:n.text,suspendedReason:n.suspendedReason,swarmIndex:n.swarmIndex}),t.set(i,o)}return[...t.entries()].map(([n,i])=>{const o=i.toSorted((r,l)=>r.swarmIndex-l.swarmIndex||r.id.localeCompare(l.id)),s=W7e();for(const r of o)s[r.phase]++;return{id:n,members:o,counts:s}}).filter(n=>n.members.length>1).toSorted((n,i)=>{const o=n.members.at(0)?.swarmIndex??0,s=i.members.at(0)?.swarmIndex??0;return o!==s?o-s:n.id.localeCompare(i.id)})}function U7e(e){let t=0,n=0;for(const i of e){n+=i.members.length;for(const o of H7e)(o==="completed"||o==="failed"||o==="cancelled")&&(t+=i.counts[o])}return{done:t,total:n}}function V7e(e){const t=new Map;for(const n of e){if(n.kind!=="subagent"||!n.parentToolCallId)continue;const i=t.get(n.parentToolCallId)??[];i.push({id:n.id,agentId:n.agentId,name:n.description,subagentType:n.subagentType,model:n.model,thinkingEffort:n.thinkingEffort,phase:PU(n),summary:n.outputPreview,outputLines:n.outputLines,text:n.text,suspendedReason:n.suspendedReason,swarmIndex:n.swarmIndex??Number.MAX_SAFE_INTEGER}),t.set(n.parentToolCallId,i)}for(const[n,i]of t)t.set(n,i.toSorted((o,s)=>o.swarmIndex-s.swarmIndex||o.id.localeCompare(s.id)));return t}function eS(e){const t=e.trim();if(!t.startsWith("{"))return null;try{const n=JSON.parse(t);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function $U(e){for(const t of["path","file_path","filePath","filename"]){const n=e[t];if(typeof n=="string"&&n.length>0)return n}}const s0=100*1024;function BU(e){const t=cr(e.name);if(t!=="edit"&&t!=="multi_edit")return null;const n=eS(e.arg);if(!n)return null;if(t==="edit"){if(n.replace_all===!0)return null;const l=typeof n.old_string=="string"?n.old_string:void 0,a=typeof n.new_string=="string"?n.new_string:void 0;return l===void 0||a===void 0||l.length>s0||a.length>s0?null:ub(l,a)}const i=Array.isArray(n.edits)?n.edits:void 0;if(!i||i.length===0)return null;const o=[];let s=0,r=0;for(const l of i){if(!l||typeof l!="object")return null;const a=l;if(a.replace_all===!0)return null;const u=typeof a.old_string=="string"?a.old_string:void 0,c=typeof a.new_string=="string"?a.new_string:void 0;if(u===void 0||c===void 0||u.length>s0||c.length>s0)return null;const d=ub(u,c);if(d===null)return null;o.length>0&&o.push({type:"hunk",text:"···"});for(const h of d)o.push({...h,oldNo:h.oldNo!==void 0?h.oldNo+s:void 0,newNo:h.newNo!==void 0?h.newNo+r:void 0});s+=cc(u).length,r+=cc(c).length}return o}const K7e=5e3;function Z7e(e){if(cr(e.name)!=="write")return null;const t=eS(e.arg);return!t||typeof t.content!="string"||t.content.length>s0||t.content.split(` -`).length>K7e?null:{content:t.content,path:$U(t)}}function HA(e){const t=eS(e.arg);return t?$U(t):void 0}function G7e(e){switch(e){case"running":return"running";case"completed":return"completed";case"killed":return"cancelled";default:return"failed"}}function Q7e(e,t){return t==="running"?e.stateReason!==void 0?"suspended":"working":t}function Y7e(e){return e==="subagent"?"subagent":e==="shell"?"bash":"tool"}function J7e(e){return zU(e).parents}function zU(e){const t=new Map,n=new Map;for(const i of e.items)if(i.kind==="turn")for(const o of i.steps)for(const s of o.frames)s.kind!=="tool"||s.agentRefs===void 0||s.agentRefs.forEach((r,l)=>{t.set(r.agentId,s.toolCallId),n.set(r.agentId,l)});return{parents:t,swarmIndexes:n}}function X7e(e,t,n){const i=zU(e);let o=i.parents,s=i.swarmIndexes;if(n!==void 0){for(const[u,c]of i.parents)n.parents.set(u,c);for(const[u,c]of i.swarmIndexes)n.swarmIndexes.set(u,c);o=n.parents,s=n.swarmIndexes}const r=e.tasks.map(u=>{const c=G7e(u.state);return{id:u.taskId,agentId:u.agentId,sessionId:t,kind:Y7e(u.kind),description:u.description??"",status:c,createdAt:u.startedAt??"",startedAt:u.startedAt,completedAt:u.endedAt,outputPreview:u.outputTail.length>0?u.outputTail:void 0,text:u.resultSummary,subagentPhase:u.kind==="subagent"?Q7e(u,c):void 0,suspendedReason:c==="running"?u.stateReason:void 0,model:u.model,thinkingEffort:u.thinkingEffort,runInBackground:u.detached,parentToolCallId:u.agentId!==void 0?o.get(u.agentId):void 0,swarmIndex:u.agentId!==void 0?s.get(u.agentId):void 0}}),l=new Map;r.forEach((u,c)=>{u.agentId!==void 0&&u.id===u.agentId&&l.set(u.agentId,c)});const a=new Set;return r.forEach((u,c)=>{if(u.agentId===void 0||u.id===u.agentId)return;const d=l.get(u.agentId);if(d===void 0)return;const h=r[d],p=u.completedAt!==void 0&&h.startedAt!==void 0&&u.completedAt>=h.startedAt,m=h.status==="running"&&u.status!=="running"&&p;r[d]={...h,backgroundTaskId:u.status==="running"||p?u.id:void 0,status:m?u.status:h.status,subagentPhase:m?u.status==="completed"?"completed":u.status==="cancelled"?"cancelled":"failed":h.subagentPhase,description:h.description.length>0?h.description:u.description,model:h.model??u.model,thinkingEffort:h.thinkingEffort??u.thinkingEffort,completedAt:p?u.completedAt??h.completedAt:h.completedAt,outputPreview:p?h.outputPreview??u.outputPreview:h.outputPreview,text:p?h.text??u.text:h.text},a.add(c)}),r.filter((u,c)=>!a.has(c))}function exe(){let e=[],t=null,n=null,i=null,o,s,r=!0;const l=new WeakMap,a=u=>{const{messages:c,approvals:d}=u,h=u.sessionActive??!0,p=u.planReviewByToolCallId??{},m=u.plansByToolCallId??{},g=(S,x)=>l.set(S,x);let y=n!==null;if(y){const S=n,x=Object.keys(p);y=x.length===Object.keys(S).length&&x.every(A=>p[A]===S[A])}let b=i!==null;if(b){const S=i,x=Object.keys(m);b=x.length===Object.keys(S).length&&x.every(A=>m[A]===S[A])}const v=e.length>0&&d===t&&y&&b&&u.getFileUrl===o&&u.getSessionMediaUrl===s;let C=0,w=0,M=1;if(v){let S=-1;for(let x=e.length-1;x>=0;x--)if(e[x].role==="assistant"){S=x;break}for(let x=0;x0?[...e.slice(0,C),...N]:N;return e=T,t=d,n={...p},i={...m},o=u.getFileUrl,s=u.getSessionMediaUrl,r=h,T};return a.reset=()=>{e=[],t=null,n=null,i=null,o=void 0,r=!0},a}function txe(e){const t=new Map;let n=0;for(let i=e.length-1;i>=0;i--){const o=e[i];if(o.role==="compaction"||o.goalContinuation===!0)break;o.role==="user"&&o.hasUndoAnchor!==!1&&(n++,t.set(o.id,n))}return t}const jU=["light","dark","system"],nxe=["small","medium","large","xlarge"],Aw="medium",HU="kimi-web.color-scheme",WA="kimi-web.font-scale",LF="kimi-web.ui-font-size";function qA(e){try{return globalThis.localStorage.getItem(e)}catch{return null}}function tS(e,t){try{globalThis.localStorage.setItem(e,t)}catch{}}function ixe(e){try{globalThis.localStorage.removeItem(e)}catch{}}function oxe(){const e=qA(HU);return e&&jU.includes(e)?e:"system"}const Oy={light:"#ffffff",dark:"#121212"};function sxe(e){if(typeof document>"u"||!document.documentElement)return;document.documentElement.dataset.colorScheme=e;const t=document.querySelectorAll('meta[name="theme-color"]');if(t.length===0)return;const n=e==="dark"?Oy.dark:e==="light"?Oy.light:null;t.forEach(i=>{const s=(i.getAttribute("media")??"").includes("dark")?Oy.dark:Oy.light;i.setAttribute("content",n??s)})}function WU(e){return nxe.includes(e)}function rxe(e){return e<=13?"small":e<=15?"medium":e<=17?"large":"xlarge"}function lxe(){const e=qA(WA);if(e==="xxlarge")return"xlarge";if(e!==null)return WU(e)?e:Aw;const t=qA(LF);if(t===null)return Aw;const n=Number(t),i=Number.isFinite(n)?rxe(n):Aw;return tS(WA,i),ixe(LF),i}function axe(e){typeof document>"u"||!document.documentElement||(document.documentElement.dataset.fontScale=e)}const nS=q(oxe()),iS=q(lxe());let NF=!1;function uxe(){NF||(NF=!0,qe(nS,sxe,{immediate:!0}),qe(iS,axe,{immediate:!0}))}function cxe(e){jU.includes(e)&&(nS.value=e,tS(HU,e))}function dxe(e){WU(e)&&(iS.value=e,tS(WA,e))}function jm(){return uxe(),{colorScheme:nS,fontScale:iS,setColorScheme:cxe,setFontScale:dxe}}const Py=q(!1);let DF=!1;function xw(){const e=document.documentElement.dataset.colorScheme;return e==="dark"?!0:e==="light"?!1:window.matchMedia("(prefers-color-scheme: dark)").matches}function j4(){return!DF&&typeof window<"u"&&typeof document<"u"&&(DF=!0,Py.value=xw(),new MutationObserver(()=>{Py.value=xw()}).observe(document.documentElement,{attributes:!0,attributeFilter:["data-color-scheme"]}),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",()=>{Py.value=xw()})),Py}const qU="kimi-web.sidebar-multi-tab";function fxe(e){try{return globalThis.localStorage.getItem(e)}catch{return null}}function hxe(e,t){try{globalThis.localStorage.setItem(e,t)}catch{}}function pxe(){return fxe(qU)==="1"}const UU=q(pxe());function mxe(e){UU.value=e,hxe(qU,e?"1":"0")}function Hm(){return{sidebarTabs:UU,setSidebarTabs:mxe}}function q0(e){let t="";for(const n of e)n.codePointAt(0)>127||/[A-Za-z0-9\-._~]/.test(n)?t+=n:t+=`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`;return t}function gxe(e){const t=e.split("/").map(q0).join("/");return t.startsWith("//")?`/%2F${t.slice(2)}`:t}function oS(e){return e.replace(/%/g,"%25").replace(/&/g,"%26").replace(//g,"%3E").replace(/([\\[\]])/g,"\\$1").replace(/\n/g,"%0A").replace(/\r/g,"%0D")}function FF(e){return e.replace(/\\([\\[\]])/g,"$1").replace(/%0A/g,` -`).replace(/%0D/g,"\r").replace(/%26/g,"&").replace(/%3C/g,"<").replace(/%3E/g,">").replace(/%25/g,"%")}function vxe(e){return e.replace(/%0A/g,` -`).replace(/%0D/g,"\r").replace(/%26/g,"&").replace(/%3C/g,"<").replace(/%3E/g,">").replace(/%25/g,"%")}function yxe(e,t){const n=t?e.replace(/\\([\\<>])/g,"$1"):e.replace(/\\([\\()])/g,"$1");return U0(n)}function U0(e){try{return decodeURIComponent(e)}catch{return e}}let RF;function UA(e){return RF??=new Intl.Segmenter("und",{granularity:"grapheme"}),[...RF.segment(e)].map(t=>t.segment)}function VU(e,t){const n=UA(e);return n.length<=t?e:`${n.slice(0,t-1).join("")}…`}const cb="kimi-code://skill/";function sS(e){return e?e.startsWith(cb)&&e.length>cb.length?"skill":e.startsWith("#")||e.startsWith("?")||e.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!/^[a-zA-Z]:(?:[\\/]|%5c)/i.test(e)?null:e.endsWith("/")||e.endsWith("\\")||/%5c$/i.test(e)?"folder":"file":null}function I1(e){const t=e.search(/[#?]/);return t>0?e.slice(0,t):e}function KU(e){const t=e.slice(cb.length);return U0(t)}function wp(e){const t=oS(e.name);if(e.kind==="skill")return`[${t}](${cb}${q0(e.name)})`;const n=e.kind==="folder"&&!e.path.endsWith("/")&&!e.path.endsWith("\\")?`${e.path}/`:e.path;return`[${t}](${gxe(n)})`}const N9="kimi-code-composer://attachments/";function Cf(e){return`[${oS(e.name)}](${N9}${e.attId})`}const Lh="kimi-code-composer://quote/",kxe=24;function mm(e){const t=e.split(` -`).map(i=>i.trim()).find(i=>i.length>0)??"",n=VU(t,kxe);return n.length>0?n:"…"}function H4(e){const t=e.source!==void 0&&e.source.length>0?`?source=${q0(e.source)}`:"",n=e.comment!==void 0&&e.comment.length>0?`?comment=${q0(e.comment)}`:"";return`[${oS(mm(e.text))}](${Lh}${q0(e.text)}${t}${n})`}function ZU(e){const t=e.indexOf("?source="),n=e.indexOf("?comment="),i=[t,n].filter(s=>s>=0).sort((s,r)=>s-r)[0]??-1,o={text:U0(i===-1?e:e.slice(0,i))};if(t>=0){const s=n>t?n:e.length;o.source=U0(e.slice(t+8,s))}if(n>=0){const s=t>n?t:e.length;o.comment=U0(e.slice(n+9,s))}return o}const OF=document.createElement("i");function bxe(e){const t="&"+e+";";OF.innerHTML=t;const n=OF.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function dc(e,t,n,i){const o=e.length;let s=0,r;if(t<0?t=-t>o?0:o+t:t=t>o?o:t,n=n>0?n:0,i.length<1e4)r=Array.from(i),r.unshift(t,n),e.splice(...r);else for(n&&e.splice(t,n);s0?(dc(e,e.length,0,t),e):t}const PF={}.hasOwnProperty;function wxe(e){const t={};let n=-1;for(;++n-1&&e.test(String.fromCharCode(n))}}function So(e,t,n,i){const o=i?i-1:Number.POSITIVE_INFINITY;let s=0;return r;function r(a){return Bi(a)?(e.enter(n),l(a)):t(a)}function l(a){return Bi(a)&&s++r))return;const T=t.events.length;let S=T,x,A;for(;S--;)if(t.events[S][0]==="exit"&&t.events[S][1].type==="chunkFlow"){if(x){A=t.events[S][1].end;break}x=!0}for(b(i),N=T;NC;){const M=n[w];t.containerState=M[1],M[0].exit.call(t,e)}n.length=C}function v(){o.write([null]),s=void 0,o=void 0,t.containerState._closeFlow=void 0}}function Dxe(e,t,n){return So(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function BF(e){if(e===null||Gl(e)||Mxe(e))return 1;if(Ixe(e))return 2}function lS(e,t,n){const i=[];let o=-1;for(;++o1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[i][1].end},h={...e[n][1].start};zF(d,-a),zF(h,a),r={type:a>1?"strongSequence":"emphasisSequence",start:d,end:{...e[i][1].end}},l={type:a>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:h},s={type:a>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[n][1].start}},o={type:a>1?"strong":"emphasis",start:{...r.start},end:{...l.end}},e[i][1].end={...r.start},e[n][1].start={...l.end},u=[],e[i][1].end.offset-e[i][1].start.offset&&(u=Ra(u,[["enter",e[i][1],t],["exit",e[i][1],t]])),u=Ra(u,[["enter",o,t],["enter",r,t],["exit",r,t],["enter",s,t]]),u=Ra(u,lS(t.parser.constructs.insideSpan.null,e.slice(i+1,n),t)),u=Ra(u,[["exit",s,t],["enter",l,t],["exit",l,t],["exit",o,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Ra(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,dc(e,i-1,n-i+3,u),n=i+u.length-c-2;break}}for(n=-1;++n0&&Bi(N)?So(e,v,"linePrefix",s+1)(N):v(N)}function v(N){return N===null||Zn(N)?e.check(jF,g,w)(N):(e.enter("codeFlowValue"),C(N))}function C(N){return N===null||Zn(N)?(e.exit("codeFlowValue"),v(N)):(e.consume(N),C)}function w(N){return e.exit("codeFenced"),t(N)}function M(N,T,S){let x=0;return A;function A(z){return N.enter("lineEnding"),N.consume(z),N.exit("lineEnding"),E}function E(z){return N.enter("codeFencedFence"),Bi(z)?So(N,I,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(z):I(z)}function I(z){return z===l?(N.enter("codeFencedFenceSequence"),R(z)):S(z)}function R(z){return z===l?(x++,N.consume(z),R):x>=r?(N.exit("codeFencedFenceSequence"),Bi(z)?So(N,W,"whitespace")(z):W(z)):S(z)}function W(z){return z===null||Zn(z)?(N.exit("codeFencedFence"),T(z)):S(z)}}}function Uxe(e,t,n){const i=this;return o;function o(r){return r===null?n(r):(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s)}function s(r){return i.parser.lazy[i.now().line]?n(r):t(r)}}const Sw={name:"codeIndented",tokenize:Kxe},Vxe={partial:!0,tokenize:Zxe};function Kxe(e,t,n){const i=this;return o;function o(u){return e.enter("codeIndented"),So(e,s,"linePrefix",5)(u)}function s(u){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?r(u):n(u)}function r(u){return u===null?a(u):Zn(u)?e.attempt(Vxe,r,a)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||Zn(u)?(e.exit("codeFlowValue"),r(u)):(e.consume(u),l)}function a(u){return e.exit("codeIndented"),t(u)}}function Zxe(e,t,n){const i=this;return o;function o(r){return i.parser.lazy[i.now().line]?n(r):Zn(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),o):So(e,s,"linePrefix",5)(r)}function s(r){const l=i.events[i.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(r):Zn(r)?o(r):n(r)}}const Gxe={name:"codeText",previous:Yxe,resolve:Qxe,tokenize:Jxe};function Qxe(e){let t=e.length-4,n=3,i,o;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(i=n;++i=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(t,n,i){const o=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-o,Number.POSITIVE_INFINITY);return i&&Fg(this.left,i),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Fg(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Fg(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(r):e.interrupt(i.parser.constructs.flow,n,t)(r)}}function XU(e,t,n,i,o,s,r,l,a){const u=a||Number.POSITIVE_INFINITY;let c=0;return d;function d(b){return b===60?(e.enter(i),e.enter(o),e.enter(s),e.consume(b),e.exit(s),h):b===null||b===32||b===41||VA(b)?n(b):(e.enter(i),e.enter(r),e.enter(l),e.enter("chunkString",{contentType:"string"}),g(b))}function h(b){return b===62?(e.enter(s),e.consume(b),e.exit(s),e.exit(o),e.exit(i),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(l),h(b)):b===null||b===60||Zn(b)?n(b):(e.consume(b),b===92?m:p)}function m(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function g(b){return!c&&(b===null||b===41||Gl(b))?(e.exit("chunkString"),e.exit(l),e.exit(r),e.exit(i),t(b)):c999||p===null||p===91||p===93&&!a||p===94&&!l&&"_hiddenFootnoteSupport"in r.parser.constructs?n(p):p===93?(e.exit(s),e.enter(o),e.consume(p),e.exit(o),e.exit(i),t):Zn(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||Zn(p)||l++>999?(e.exit("chunkString"),c(p)):(e.consume(p),a||(a=!Bi(p)),p===92?h:d)}function h(p){return p===91||p===92||p===93?(e.consume(p),l++,d):d(p)}}function tV(e,t,n,i,o,s){let r;return l;function l(h){return h===34||h===39||h===40?(e.enter(i),e.enter(o),e.consume(h),e.exit(o),r=h===40?41:h,a):n(h)}function a(h){return h===r?(e.enter(o),e.consume(h),e.exit(o),e.exit(i),t):(e.enter(s),u(h))}function u(h){return h===r?(e.exit(s),a(r)):h===null?n(h):Zn(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),So(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===r||h===null||Zn(h)?(e.exit("chunkString"),u(h)):(e.consume(h),h===92?d:c)}function d(h){return h===r||h===92?(e.consume(h),c):c(h)}}function V0(e,t){let n;return i;function i(o){return Zn(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n=!0,i):Bi(o)?So(e,i,n?"linePrefix":"lineSuffix")(o):t(o)}}const rSe={name:"definition",tokenize:aSe},lSe={partial:!0,tokenize:uSe};function aSe(e,t,n){const i=this;let o;return s;function s(p){return e.enter("definition"),r(p)}function r(p){return eV.call(i,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function l(p){return o=rS(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),a):n(p)}function a(p){return Gl(p)?V0(e,u)(p):u(p)}function u(p){return XU(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function c(p){return e.attempt(lSe,d,d)(p)}function d(p){return Bi(p)?So(e,h,"whitespace")(p):h(p)}function h(p){return p===null||Zn(p)?(e.exit("definition"),i.parser.defined.push(o),t(p)):n(p)}}function uSe(e,t,n){return i;function i(l){return Gl(l)?V0(e,o)(l):n(l)}function o(l){return tV(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function s(l){return Bi(l)?So(e,r,"whitespace")(l):r(l)}function r(l){return l===null||Zn(l)?t(l):n(l)}}const cSe={name:"hardBreakEscape",tokenize:dSe};function dSe(e,t,n){return i;function i(s){return e.enter("hardBreakEscape"),e.consume(s),o}function o(s){return Zn(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const fSe={name:"headingAtx",resolve:hSe,tokenize:pSe};function hSe(e,t){let n=e.length-2,i=3,o,s;return e[i][1].type==="whitespace"&&(i+=2),n-2>i&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(i===n-1||n-4>i&&e[n-2][1].type==="whitespace")&&(n-=i+1===n?2:4),n>i&&(o={type:"atxHeadingText",start:e[i][1].start,end:e[n][1].end},s={type:"chunkText",start:e[i][1].start,end:e[n][1].end,contentType:"text"},dc(e,i,n-i+1,[["enter",o,t],["enter",s,t],["exit",s,t],["exit",o,t]])),e}function pSe(e,t,n){let i=0;return o;function o(c){return e.enter("atxHeading"),s(c)}function s(c){return e.enter("atxHeadingSequence"),r(c)}function r(c){return c===35&&i++<6?(e.consume(c),r):c===null||Gl(c)?(e.exit("atxHeadingSequence"),l(c)):n(c)}function l(c){return c===35?(e.enter("atxHeadingSequence"),a(c)):c===null||Zn(c)?(e.exit("atxHeading"),t(c)):Bi(c)?So(e,l,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function a(c){return c===35?(e.consume(c),a):(e.exit("atxHeadingSequence"),l(c))}function u(c){return c===null||c===35||Gl(c)?(e.exit("atxHeadingText"),l(c)):(e.consume(c),u)}}const mSe=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],WF=["pre","script","style","textarea"],gSe={concrete:!0,name:"htmlFlow",resolveTo:kSe,tokenize:bSe},vSe={partial:!0,tokenize:CSe},ySe={partial:!0,tokenize:wSe};function kSe(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function bSe(e,t,n){const i=this;let o,s,r,l,a;return u;function u(K){return c(K)}function c(K){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(K),d}function d(K){return K===33?(e.consume(K),h):K===47?(e.consume(K),s=!0,g):K===63?(e.consume(K),o=3,i.interrupt?t:$):Gu(K)?(e.consume(K),r=String.fromCharCode(K),y):n(K)}function h(K){return K===45?(e.consume(K),o=2,p):K===91?(e.consume(K),o=5,l=0,m):Gu(K)?(e.consume(K),o=4,i.interrupt?t:$):n(K)}function p(K){return K===45?(e.consume(K),i.interrupt?t:$):n(K)}function m(K){const ee="CDATA[";return K===ee.charCodeAt(l++)?(e.consume(K),l===ee.length?i.interrupt?t:I:m):n(K)}function g(K){return Gu(K)?(e.consume(K),r=String.fromCharCode(K),y):n(K)}function y(K){if(K===null||K===47||K===62||Gl(K)){const ee=K===47,ue=r.toLowerCase();return!ee&&!s&&WF.includes(ue)?(o=1,i.interrupt?t(K):I(K)):mSe.includes(r.toLowerCase())?(o=6,ee?(e.consume(K),b):i.interrupt?t(K):I(K)):(o=7,i.interrupt&&!i.parser.lazy[i.now().line]?n(K):s?v(K):C(K))}return K===45||gu(K)?(e.consume(K),r+=String.fromCharCode(K),y):n(K)}function b(K){return K===62?(e.consume(K),i.interrupt?t:I):n(K)}function v(K){return Bi(K)?(e.consume(K),v):A(K)}function C(K){return K===47?(e.consume(K),A):K===58||K===95||Gu(K)?(e.consume(K),w):Bi(K)?(e.consume(K),C):A(K)}function w(K){return K===45||K===46||K===58||K===95||gu(K)?(e.consume(K),w):M(K)}function M(K){return K===61?(e.consume(K),N):Bi(K)?(e.consume(K),M):C(K)}function N(K){return K===null||K===60||K===61||K===62||K===96?n(K):K===34||K===39?(e.consume(K),a=K,T):Bi(K)?(e.consume(K),N):S(K)}function T(K){return K===a?(e.consume(K),a=null,x):K===null||Zn(K)?n(K):(e.consume(K),T)}function S(K){return K===null||K===34||K===39||K===47||K===60||K===61||K===62||K===96||Gl(K)?M(K):(e.consume(K),S)}function x(K){return K===47||K===62||Bi(K)?C(K):n(K)}function A(K){return K===62?(e.consume(K),E):n(K)}function E(K){return K===null||Zn(K)?I(K):Bi(K)?(e.consume(K),E):n(K)}function I(K){return K===45&&o===2?(e.consume(K),F):K===60&&o===1?(e.consume(K),O):K===62&&o===4?(e.consume(K),V):K===63&&o===3?(e.consume(K),$):K===93&&o===5?(e.consume(K),j):Zn(K)&&(o===6||o===7)?(e.exit("htmlFlowData"),e.check(vSe,ne,R)(K)):K===null||Zn(K)?(e.exit("htmlFlowData"),R(K)):(e.consume(K),I)}function R(K){return e.check(ySe,W,ne)(K)}function W(K){return e.enter("lineEnding"),e.consume(K),e.exit("lineEnding"),z}function z(K){return K===null||Zn(K)?R(K):(e.enter("htmlFlowData"),I(K))}function F(K){return K===45?(e.consume(K),$):I(K)}function O(K){return K===47?(e.consume(K),r="",B):I(K)}function B(K){if(K===62){const ee=r.toLowerCase();return WF.includes(ee)?(e.consume(K),V):I(K)}return Gu(K)&&r.length<8?(e.consume(K),r+=String.fromCharCode(K),B):I(K)}function j(K){return K===93?(e.consume(K),$):I(K)}function $(K){return K===62?(e.consume(K),V):K===45&&o===2?(e.consume(K),$):I(K)}function V(K){return K===null||Zn(K)?(e.exit("htmlFlowData"),ne(K)):(e.consume(K),V)}function ne(K){return e.exit("htmlFlow"),t(K)}}function wSe(e,t,n){const i=this;return o;function o(r){return Zn(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s):n(r)}function s(r){return i.parser.lazy[i.now().line]?n(r):t(r)}}function CSe(e,t,n){return i;function i(o){return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),e.attempt(W4,t,n)}}const ASe={name:"htmlText",tokenize:xSe};function xSe(e,t,n){const i=this;let o,s,r;return l;function l($){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume($),a}function a($){return $===33?(e.consume($),u):$===47?(e.consume($),M):$===63?(e.consume($),C):Gu($)?(e.consume($),S):n($)}function u($){return $===45?(e.consume($),c):$===91?(e.consume($),s=0,m):Gu($)?(e.consume($),v):n($)}function c($){return $===45?(e.consume($),p):n($)}function d($){return $===null?n($):$===45?(e.consume($),h):Zn($)?(r=d,O($)):(e.consume($),d)}function h($){return $===45?(e.consume($),p):d($)}function p($){return $===62?F($):$===45?h($):d($)}function m($){const V="CDATA[";return $===V.charCodeAt(s++)?(e.consume($),s===V.length?g:m):n($)}function g($){return $===null?n($):$===93?(e.consume($),y):Zn($)?(r=g,O($)):(e.consume($),g)}function y($){return $===93?(e.consume($),b):g($)}function b($){return $===62?F($):$===93?(e.consume($),b):g($)}function v($){return $===null||$===62?F($):Zn($)?(r=v,O($)):(e.consume($),v)}function C($){return $===null?n($):$===63?(e.consume($),w):Zn($)?(r=C,O($)):(e.consume($),C)}function w($){return $===62?F($):C($)}function M($){return Gu($)?(e.consume($),N):n($)}function N($){return $===45||gu($)?(e.consume($),N):T($)}function T($){return Zn($)?(r=T,O($)):Bi($)?(e.consume($),T):F($)}function S($){return $===45||gu($)?(e.consume($),S):$===47||$===62||Gl($)?x($):n($)}function x($){return $===47?(e.consume($),F):$===58||$===95||Gu($)?(e.consume($),A):Zn($)?(r=x,O($)):Bi($)?(e.consume($),x):F($)}function A($){return $===45||$===46||$===58||$===95||gu($)?(e.consume($),A):E($)}function E($){return $===61?(e.consume($),I):Zn($)?(r=E,O($)):Bi($)?(e.consume($),E):x($)}function I($){return $===null||$===60||$===61||$===62||$===96?n($):$===34||$===39?(e.consume($),o=$,R):Zn($)?(r=I,O($)):Bi($)?(e.consume($),I):(e.consume($),W)}function R($){return $===o?(e.consume($),o=void 0,z):$===null?n($):Zn($)?(r=R,O($)):(e.consume($),R)}function W($){return $===null||$===34||$===39||$===60||$===61||$===96?n($):$===47||$===62||Gl($)?x($):(e.consume($),W)}function z($){return $===47||$===62||Gl($)?x($):n($)}function F($){return $===62?(e.consume($),e.exit("htmlTextData"),e.exit("htmlText"),t):n($)}function O($){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume($),e.exit("lineEnding"),B}function B($){return Bi($)?So(e,j,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)($):j($)}function j($){return e.enter("htmlTextData"),r($)}}const aS={name:"labelEnd",resolveAll:MSe,resolveTo:TSe,tokenize:ESe},SSe={tokenize:LSe},_Se={tokenize:NSe},ISe={tokenize:DSe};function MSe(e){let t=-1;const n=[];for(;++t=3&&(u===null||Zn(u))?(e.exit("thematicBreak"),t(u)):n(u)}function a(u){return u===o?(e.consume(u),i++,a):(e.exit("thematicBreakSequence"),Bi(u)?So(e,l,"whitespace")(u):l(u))}}const Dl={continuation:{tokenize:WSe},exit:USe,name:"list",tokenize:HSe},zSe={partial:!0,tokenize:VSe},jSe={partial:!0,tokenize:qSe};function HSe(e,t,n){const i=this,o=i.events[i.events.length-1];let s=o&&o[1].type==="linePrefix"?o[2].sliceSerialize(o[1],!0).length:0,r=0;return l;function l(p){const m=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:KA(p)){if(i.containerState.type||(i.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(D9,n,u)(p):u(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),a(p)}return n(p)}function a(p){return KA(p)&&++r<10?(e.consume(p),a):(!i.interrupt||r<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):n(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(W4,i.interrupt?n:c,e.attempt(zSe,h,d))}function c(p){return i.containerState.initialBlankLine=!0,s++,h(p)}function d(p){return Bi(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),h):n(p)}function h(p){return i.containerState.size=s+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function WSe(e,t,n){const i=this;return i.containerState._closeFlow=void 0,e.check(W4,o,s);function o(l){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,So(e,t,"listItemIndent",i.containerState.size+1)(l)}function s(l){return i.containerState.furtherBlankLines||!Bi(l)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,r(l)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(jSe,t,r)(l))}function r(l){return i.containerState._closeFlow=!0,i.interrupt=void 0,So(e,e.attempt(Dl,t,n),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function qSe(e,t,n){const i=this;return So(e,o,"listItemIndent",i.containerState.size+1);function o(s){const r=i.events[i.events.length-1];return r&&r[1].type==="listItemIndent"&&r[2].sliceSerialize(r[1],!0).length===i.containerState.size?t(s):n(s)}}function USe(e){e.exit(this.containerState.type)}function VSe(e,t,n){const i=this;return So(e,o,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function o(s){const r=i.events[i.events.length-1];return!Bi(s)&&r&&r[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const qF={name:"setextUnderline",resolveTo:KSe,tokenize:ZSe};function KSe(e,t){let n=e.length,i,o,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){i=n;break}e[n][1].type==="paragraph"&&(o=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const r={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[o][1].type="setextHeadingText",s?(e.splice(o,0,["enter",r,t]),e.splice(s+1,0,["exit",e[i][1],t]),e[i][1].end={...e[s][1].end}):e[i][1]=r,e.push(["exit",r,t]),e}function ZSe(e,t,n){const i=this;let o;return s;function s(u){let c=i.events.length,d;for(;c--;)if(i.events[c][1].type!=="lineEnding"&&i.events[c][1].type!=="linePrefix"&&i.events[c][1].type!=="content"){d=i.events[c][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||d)?(e.enter("setextHeadingLine"),o=u,r(u)):n(u)}function r(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===o?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),Bi(u)?So(e,a,"lineSuffix")(u):a(u))}function a(u){return u===null||Zn(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const GSe={tokenize:QSe};function QSe(e){const t=this,n=e.attempt(W4,i,e.attempt(this.parser.constructs.flowInitial,o,So(e,e.attempt(this.parser.constructs.flow,o,e.attempt(tSe,o)),"linePrefix")));return n;function i(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function o(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const YSe={resolveAll:iV()},JSe=nV("string"),XSe=nV("text");function nV(e){return{resolveAll:iV(e==="text"?e_e:void 0),tokenize:t};function t(n){const i=this,o=this.parser.constructs[e],s=n.attempt(o,r,l);return r;function r(c){return u(c)?s(c):l(c)}function l(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),a}function a(c){return u(c)?(n.exit("data"),s(c)):(n.consume(c),a)}function u(c){if(c===null)return!0;const d=o[c];let h=-1;if(d)for(;++h-1){const l=r[0];typeof l=="string"?r[0]=l.slice(i):r.shift()}s>0&&r.push(e[o].slice(0,s))}return r}function h_e(e,t){let n=-1;const i=[];let o;for(;++n0;if(s||e[c]!==(p?"!":"[")||r===null)continue;const m=e.slice(c+(p?2:1),d-1);let g=e.slice(r.start,r.end),y=!1;g.startsWith("<")&&(y=!0,g=g.slice(1,-1)),!(!m||!g)&&n.push({start:c,end:h,rawText:m,rawDest:g,angle:y,image:p})}return n}function y_e(e,t){const{start:n,end:i,rawText:o,rawDest:s,angle:r,image:l}=e;if(l&&!s.startsWith(Lh))return null;if(s.startsWith(N9)&&s.length>N9.length){const u=FF(o),c=s.slice(N9.length);return{type:"attachment",start:n,end:i,attrs:{attId:c,name:u,kind:t?.(c)??(u.endsWith("/")?"folder":"file")},rawDest:s}}if(s.startsWith(Lh)&&s.length>Lh.length)return{type:"quote",start:n,end:i,attrs:ZU(s.slice(Lh.length)),rawDest:s};const a=sS(s);return a===null?null:a==="skill"?{type:"mention",start:n,end:i,attrs:{kind:a,name:KU(s),path:""},rawDest:s}:{type:"mention",start:n,end:i,attrs:{kind:a,name:FF(o),path:yxe(s,r)},rawDest:s}}const VF=/\[(?:\\.|[^\\[\]\n])*\]\((kimi-code-composer:\/\/quote\/[^\s)]+)\)/g;function k_e(e){const t=[];VF.lastIndex=0;let n;for(;(n=VF.exec(e))!==null;){let i=0;for(let s=n.index-1;s>=0&&e[s]==="\\";s-=1)i+=1;if(i%2===0)continue;const o=n[1];o===void 0||o.length<=Lh.length||t.push({type:"quote",start:n.index-1,end:n.index+n[0].length,attrs:ZU(o.slice(Lh.length)),rawDest:o})}return t}function q4(e,t){const n=[];for(const i of oV(e)){const o=y_e(i,t);o&&n.push(o)}return n.push(...k_e(e)),n.sort((i,o)=>i.start-o.start),n}function Af(e){return q4(e).filter(t=>t.type==="mention").map(({start:t,end:n,attrs:i,rawDest:o})=>({start:t,end:n,attrs:i,rawDest:o}))}function Bl(e){return q4(e).filter(t=>t.type==="attachment").map(({start:t,end:n,attrs:i,rawDest:o})=>({start:t,end:n,attrs:i,rawDest:o}))}function sV(e){return q4(e).filter(t=>t.type==="quote").map(({start:t,end:n,attrs:i,rawDest:o})=>({start:t,end:n,attrs:i,rawDest:o}))}function rV(e,t){const n=q4(e,t);if(n.length===0)return[{type:"text",value:e}];const i=[];let o=0;for(const s of n)s.start>o&&i.push({type:"text",value:e.slice(o,s.start)}),s.type==="mention"?i.push({type:"mention",attrs:s.attrs,rawDest:s.rawDest}):s.type==="attachment"?i.push({type:"attachment",attrs:s.attrs,rawDest:s.rawDest}):i.push({type:"quote",attrs:s.attrs,rawDest:s.rawDest}),o=s.end;return o[a,u+1])),s=new Map(t.mediaAttIds.map((a,u)=>[a,u+1]));let r="",l=0;for(const a of i){r+=e.slice(l,a.start),l=a.end;const{attId:u,name:c,kind:d}=a.attrs,h=d==="folder"?n?.resolveFolder?.(u):void 0;if(h!==void 0){const y=h==="/"||/^[a-zA-Z]:\/$/.test(h)?h.slice(0,-1)||"/":c.endsWith("/")?c.slice(0,-1):c;r+=wp({kind:"folder",name:y,path:h});continue}const p=o.get(u);if(p!==void 0){r+=Cf({attId:String(p),name:c});continue}const m=s.get(u);if(m!==void 0){r+=Cf({attId:`m${m}`,name:c});continue}r+=c}return r+=e.slice(l),r}function KF(e,t,n=0){if(t<=0&&n<=0)return e;const i=Bl(e);if(i.length===0)return e;let o="",s=0;for(const r of i){const{attId:l,name:a,kind:u}=r.attrs;let c;t>0&&/^[1-9]\d*$/.test(l)?c=String(Number(l)+t):n>0&&/^m[1-9]\d*$/.test(l)&&(c=`m${Number(l.slice(1))+n}`),c!==void 0&&(o+=e.slice(s,r.start),s=r.end,o+=Cf({attId:c,name:a}))}return o+=e.slice(s),o}function Ud(e,t){const n=Bl(e);if(n.length===0)return e;let i="",o=0;for(const s of n)i+=e.slice(o,s.start)+(t?.(s.attrs.name)??s.attrs.name),o=s.end;return i+=e.slice(o),i}function ZF(e,t){const n=Bl(e);if(n.length===0)return e;let i="",o=0;for(const s of n)t.has(s.attrs.attId)||(i+=e.slice(o,s.start)+s.attrs.name,o=s.end);return i+=e.slice(o),i}function GA(e){const t=Bl(e);if(t.length===0)return e;let n="",i=0;for(const o of t)n+=e.slice(i,o.start),i=o.end;return n+=e.slice(i),n}let w_e=!1;function uS(e){return e.replaceAll("%","%25").replaceAll(` -`,"%0A").replaceAll("\r","%0D")}function cS(e){const t=[];for(const i of e.split(/(\n{2,})/))if(i!==""){if(/^\n{2,}$/.test(i)){t.push({type:"sep",text:i});continue}t.push({type:"inline",text:i})}const n=[];for(let i=0;i`> ${t}`).join(` -`)}function aV(e){const t=cS(e),n=new Set;return t.forEach((i,o)=>{i.type==="sep"&&i.text===` - -`&&t[o-1]?.type==="quote"&&t[o+1]?.type==="quote"&&n.add(o)}),t.map((i,o)=>{if(n.has(o))return" ";if(i.type!=="quote")return i.text;const s={text:i.text};return i.source!==void 0&&(s.source=i.source),i.comment!==void 0&&(s.comment=i.comment),H4(s)}).join("")}function Dr(e){this.content=e}Dr.prototype={constructor:Dr,find:function(e){for(var t=0;t>1}};Dr.from=function(e){if(e instanceof Dr)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new Dr(t)};function uV(e,t,n){for(let i=0;;i++){if(i==e.childCount||i==t.childCount)return e.childCount==t.childCount?null:n;let o=e.child(i),s=t.child(i);if(o==s){n+=o.nodeSize;continue}if(!o.sameMarkup(s))return n;if(o.isText&&o.text!=s.text){let r=o.text,l=s.text,a=0;for(;r[a]==l[a];a++)n++;return a&&a0&&h>0&&u[d-1]==c[h-1];)d--,h--,n--,i--;return d&&h&&d=56320&&e<57344}function fV(e){return e>=55296&&e<56320}class dn{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let i=0;it&&i(a,o+l,s||null,r)!==!1&&a.content.size){let c=l+1;a.nodesBetween(Math.max(0,t-c),Math.min(a.content.size,n-c),i,o+c)}l=u}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,i,o){let s="",r=!0;return this.nodesBetween(t,n,(l,a)=>{let u=l.isText?l.text.slice(Math.max(t,a)-a,n-a):l.isLeaf?o?typeof o=="function"?o(l):o:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&u||l.isTextblock)&&i&&(r?r=!1:s+=i),s+=u},0),s}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,i=t.firstChild,o=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(i)&&(o[o.length-1]=n.withText(n.text+i.text),s=1);st)for(let s=0,r=0;rt&&((rn)&&(l.isText?l=l.cut(Math.max(0,t-r),Math.min(l.text.length,n-r)):l=l.cut(Math.max(0,t-r-1),Math.min(l.content.size,n-r-1))),i.push(l),o+=l.nodeSize),r=a}return new dn(i,o)}cutByIndex(t,n){return t==n?dn.empty:t==0&&n==this.content.length?this:new dn(this.content.slice(t,n))}replaceChild(t,n){let i=this.content[t];if(i==n)return this;let o=this.content.slice(),s=this.size+n.nodeSize-i.nodeSize;return o[t]=n,new dn(o,s)}addToStart(t){return new dn([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new dn(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;nthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,i=0;;n++){let o=this.child(n),s=i+o.nodeSize;if(s>=t)return s==t?$y(n+1,s):$y(n,i);i=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return dn.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return dn.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return dn.empty;let n,i=0;for(let o=0;othis.type.rank&&(n||(n=t.slice(0,o)),n.push(this),i=!0),n&&n.push(s)}}return n||(n=t.slice()),i||n.push(this),n}removeFromSet(t){for(let n=0;ni.type.rank-o.type.rank),n}}Vi.none=[];class Lv extends Error{}class Cn{constructor(t,n,i){this.content=t,this.openStart=n,this.openEnd=i}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let i=pV(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return i&&new Cn(i,this.openStart,this.openEnd)}removeBetween(t,n){return new Cn(hV(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return Cn.empty;let i=n.openStart||0,o=n.openEnd||0;if(typeof i!="number"||typeof o!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Cn(dn.fromJSON(t,n.content),i,o)}static maxOpen(t,n=!0){let i=0,o=0;for(let s=t.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)i++;for(let s=t.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)o++;return new Cn(t,i,o)}}Cn.empty=new Cn(dn.empty,0,0);function hV(e,t,n){let{index:i,offset:o}=e.findIndex(t),s=e.maybeChild(i),{index:r,offset:l}=e.findIndex(n);if(o==t||s.isText){if(l!=n&&!e.child(r).isText)throw new RangeError("Removing non-flat range");return e.cut(0,t).append(e.cut(n))}if(i!=r)throw new RangeError("Removing non-flat range");return e.replaceChild(i,s.copy(hV(s.content,t-o-1,n-o-1)))}function pV(e,t,n,i,o,s){let{index:r,offset:l}=e.findIndex(t),a=e.maybeChild(r);if(l==t||a.isText)return s&&i<=0&&o<=0&&!s.canReplace(r,r,n)?null:e.cut(0,t).append(n).append(e.cut(t));let u=pV(a.content,t-l-1,n,r==0?i-1:0,r==e.childCount-1?o-1:0,a);return u&&e.replaceChild(r,a.copy(u))}function A_e(e,t,n){if(n.openStart>e.depth)throw new Lv("Inserted content deeper than insertion position");if(e.depth-n.openStart!=t.depth-n.openEnd)throw new Lv("Inconsistent open depths");return mV(e,t,n,0)}function mV(e,t,n,i){let o=e.index(i),s=e.node(i);if(o==t.index(i)&&i=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function K0(e,t,n,i){let o=(t||e).node(n),s=0,r=t?t.index(n):o.childCount;e&&(s=e.index(n),e.depth>n?s++:e.textOffset&&(Kh(e.nodeAfter,i),s++));for(let l=s;lo&&QA(e,t,o+1),r=i.depth>o&&QA(n,i,o+1),l=[];return K0(null,e,o,l),s&&r&&t.index(o)==n.index(o)?(gV(s,r),Kh(Zh(s,vV(e,t,n,i,o+1)),l)):(s&&Kh(Zh(s,fb(e,t,o+1)),l),K0(t,n,o,l),r&&Kh(Zh(r,fb(n,i,o+1)),l)),K0(i,null,o,l),new dn(l)}function fb(e,t,n){let i=[];if(K0(null,e,n,i),e.depth>n){let o=QA(e,t,n+1);Kh(Zh(o,fb(e,t,n+1)),i)}return K0(t,null,n,i),new dn(i)}function x_e(e,t){let n=t.depth-e.openStart,o=t.node(n).copy(e.content);for(let s=n-1;s>=0;s--)o=t.node(s).copy(dn.from(o));return{start:o.resolveNoCache(e.openStart+n),end:o.resolveNoCache(o.content.size-e.openEnd-n)}}class Nv{constructor(t,n,i){this.pos=t,this.path=n,this.parentOffset=i,this.depth=n.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,n=this.index(this.depth);if(n==t.childCount)return null;let i=this.pos-this.path[this.path.length-1],o=t.child(n);return i?t.child(n).cut(i):o}get nodeBefore(){let t=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(t).cut(0,n):t==0?null:this.parent.child(t-1)}posAtIndex(t,n){n=this.resolveDepth(n);let i=this.path[n*3],o=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=t&&this.end(n)>=t)return n;return 0}blockRange(t=this,n){if(t.pos=0;i--)if(t.pos<=this.end(i)&&(!n||n(this.node(i))))return new I_e(this,t,i);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&n<=t.content.size))throw new RangeError("Position "+n+" out of range");let i=[],o=0,s=n;for(let r=t;;){let{index:l,offset:a}=r.content.findIndex(s),u=s-a;if(i.push(r,l,o+a),!u||(r=r.child(l),r.isText))break;s=u-1,o+=a+1}return new Nv(n,i,s)}static resolveCached(t,n){let i=GF.get(t);if(i)for(let s=0;st&&this.nodesBetween(t,n,s=>(i.isInSet(s.marks)&&(o=!0),!o)),o}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),yV(this.marks,t)}contentMatchAt(t){let n=this.type.contentMatch.matchFragment(this.content,0,t);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(t,n,i=dn.empty,o=0,s=i.childCount){let r=this.contentMatchAt(t).matchFragment(i,o,s),l=r&&r.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let a=o;an.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(n=>n.toJSON())),t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let i;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");i=n.marks.map(t.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(n.text,i)}let o=dn.fromJSON(t,n.content),s=t.nodeType(n.type).create(n.attrs,o,i);return s.type.checkAttrs(s.attrs),s}};Gh.prototype.text=void 0;class hb extends Gh{constructor(t,n,i,o){if(super(t,n,null,o),!i)throw new RangeError("Empty text nodes are not allowed");this.text=i}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):yV(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,n){return this.text.slice(t,n)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new hb(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new hb(this.type,this.attrs,t,this.marks)}cut(t=0,n=this.text.length){return t==0&&n==this.text.length?this:this.withText(this.text.slice(t,n))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function yV(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+"("+t+")";return t}class up{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let i=new T_e(t,n);if(i.next==null)return up.empty;let o=kV(i);i.next&&i.err("Unexpected trailing text");let s=O_e(R_e(o));return P_e(s,i),s}matchType(t){for(let n=0;nu.createAndFill()));for(let u=0;u=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function n(i){t.push(i);for(let o=0;o{let s=o+(i.validEnd?"*":" ")+" ";for(let r=0;r"+t.indexOf(i.next[r].next);return s}).join(` -`)}}up.empty=new up(!0);class T_e{constructor(t,n){this.string=t,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function kV(e){let t=[];do t.push(E_e(e));while(e.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function E_e(e){let t=[];do t.push(L_e(e));while(e.next&&e.next!=")"&&e.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function L_e(e){let t=F_e(e);for(;;)if(e.eat("+"))t={type:"plus",expr:t};else if(e.eat("*"))t={type:"star",expr:t};else if(e.eat("?"))t={type:"opt",expr:t};else if(e.eat("{"))t=N_e(e,t);else break;return t}function QF(e){/\D/.test(e.next)&&e.err("Expected number, got '"+e.next+"'");let t=Number(e.next);return e.pos++,t}function N_e(e,t){let n=QF(e),i=n;return e.eat(",")&&(e.next!="}"?i=QF(e):i=-1),e.eat("}")||e.err("Unclosed braced range"),{type:"range",min:n,max:i,expr:t}}function D_e(e,t){let n=e.nodeTypes,i=n[t];if(i)return[i];let o=[];for(let s in n){let r=n[s];r.isInGroup(t)&&o.push(r)}return o.length==0&&e.err("No node type or group '"+t+"' found"),o}function F_e(e){if(e.eat("(")){let t=kV(e);return e.eat(")")||e.err("Missing closing paren"),t}else if(/\W/.test(e.next))e.err("Unexpected token '"+e.next+"'");else{let t=D_e(e,e.next).map(n=>(e.inline==null?e.inline=n.isInline:e.inline!=n.isInline&&e.err("Mixing inline and block content"),{type:"name",value:n}));return e.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function R_e(e){let t=[[]];return o(s(e,0),n()),t;function n(){return t.push([])-1}function i(r,l,a){let u={term:a,to:l};return t[r].push(u),u}function o(r,l){r.forEach(a=>a.to=l)}function s(r,l){if(r.type=="choice")return r.exprs.reduce((a,u)=>a.concat(s(u,l)),[]);if(r.type=="seq")for(let a=0;;a++){let u=s(r.exprs[a],l);if(a==r.exprs.length-1)return u;o(u,l=n())}else if(r.type=="star"){let a=n();return i(l,a),o(s(r.expr,a),a),[i(a)]}else if(r.type=="plus"){let a=n();return o(s(r.expr,l),a),o(s(r.expr,a),a),[i(a)]}else{if(r.type=="opt")return[i(l)].concat(s(r.expr,l));if(r.type=="range"){let a=l;for(let u=0;u{e[r].forEach(({term:l,to:a})=>{if(!l)return;let u;for(let c=0;c{u||o.push([l,u=[]]),u.indexOf(c)==-1&&u.push(c)})})});let s=t[i.join(",")]=new up(i.indexOf(e.length-1)>-1);for(let r=0;r-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:CV(this.attrs,t)}create(t=null,n,i){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Gh(this,this.computeAttrs(t),dn.from(n),Vi.setFrom(i))}createChecked(t=null,n,i){return n=dn.from(n),this.checkContent(n),new Gh(this,this.computeAttrs(t),n,Vi.setFrom(i))}createAndFill(t=null,n,i){if(t=this.computeAttrs(t),n=dn.from(n),n.size){let r=this.contentMatch.fillBefore(n);if(!r)return null;n=r.append(n)}let o=this.contentMatch.matchFragment(n),s=o&&o.fillBefore(dn.empty,!0);return s?new Gh(this,t,n.append(s),Vi.setFrom(i)):null}validContent(t){let n=this.contentMatch.matchFragment(t);if(!n||!n.validEnd)return!1;for(let i=0;i-1}allowsMarks(t){if(this.markSet==null)return!0;for(let n=0;ni[s]=new SV(s,n,r));let o=n.spec.topNode||"doc";if(!i[o])throw new RangeError("Schema is missing its top node type ('"+o+"')");if(!i.text)throw new RangeError("Every schema needs a 'text' type");for(let s in i.text.attrs)throw new RangeError("The text node type should not have attributes");return i}};function $_e(e,t,n){let i=n.split("|");return o=>{let s=o===null?"null":typeof o;if(i.indexOf(s)<0)throw new RangeError(`Expected value of type ${i} for attribute ${t} on type ${e}, got ${s}`)}}class B_e{constructor(t,n,i){this.hasDefault=Object.prototype.hasOwnProperty.call(i,"default"),this.default=i.default,this.validate=typeof i.validate=="string"?$_e(t,n,i.validate):i.validate}get isRequired(){return!this.hasDefault}}class U4{constructor(t,n,i,o){this.name=t,this.rank=n,this.schema=i,this.spec=o,this.attrs=xV(t,o.attrs),this.excluded=null;let s=wV(this.attrs);this.instance=s?new Vi(this,s):null}create(t=null){return!t&&this.instance?this.instance:new Vi(this,CV(this.attrs,t))}static compile(t,n){let i=Object.create(null),o=0;return t.forEach((s,r)=>i[s]=new U4(s,o++,n,r)),i}removeFromSet(t){for(var n=0;n-1}}class z_e{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let o in t)n[o]=t[o];n.nodes=Dr.from(t.nodes),n.marks=Dr.from(t.marks||{}),this.nodes=JF.compile(this.spec.nodes,this),this.marks=U4.compile(this.spec.marks,this);let i=Object.create(null);for(let o in this.nodes){if(o in this.marks)throw new RangeError(o+" can not be both a node and a mark");let s=this.nodes[o],r=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=i[r]||(i[r]=up.parse(r,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?XF(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let o in this.marks){let s=this.marks[o],r=s.spec.excludes;s.excluded=r==null?[s]:r==""?[]:XF(this,r.split(" "))}this.nodeFromJSON=o=>Gh.fromJSON(this,o),this.markFromJSON=o=>Vi.fromJSON(this,o),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,n=null,i,o){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof JF){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(n,i,o)}text(t,n){let i=this.nodes.text;return new hb(i,i.defaultAttrs,t,Vi.setFrom(n))}mark(t,n){return typeof t=="string"&&(t=this.marks[t]),t.create(n)}nodeType(t){let n=this.nodes[t];if(!n)throw new RangeError("Unknown node type: "+t);return n}}function XF(e,t){let n=[];for(let i=0;i-1)&&n.push(r=a)}if(!r)throw new SyntaxError("Unknown mark type: '"+t[i]+"'")}return n}function j_e(e){return e.tag!=null}function H_e(e){return e.style!=null}let _V=class JA{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let i=this.matchedStyles=[];n.forEach(o=>{if(j_e(o))this.tags.push(o);else if(H_e(o)){let s=/[^=]*/.exec(o.style)[0];i.indexOf(s)<0&&i.push(s),this.styles.push(o)}}),this.normalizeLists=!this.tags.some(o=>{if(!/^(ul|ol)\b/.test(o.tag)||!o.node)return!1;let s=t.nodes[o.node];return s.contentMatch.matchType(s)})}parse(t,n={}){let i=new tR(this,n,!1);return i.addAll(t,Vi.none,n.from,n.to),i.finish()}parseSlice(t,n={}){let i=new tR(this,n,!0);return i.addAll(t,Vi.none,n.from,n.to),Cn.maxOpen(i.finish())}matchTag(t,n,i){for(let o=i?this.tags.indexOf(i)+1:0;ot.length&&(l.charCodeAt(t.length)!=61||l.slice(t.length+1)!=n))){if(r.getAttrs){let a=r.getAttrs(n);if(a===!1)continue;r.attrs=a||void 0}return r}}}static schemaRules(t){let n=[];function i(o){let s=o.priority==null?50:o.priority,r=0;for(;r{i(r=nR(r)),r.mark||r.ignore||r.clearMark||(r.mark=o)})}for(let o in t.nodes){let s=t.nodes[o].spec.parseDOM;s&&s.forEach(r=>{i(r=nR(r)),r.node||r.ignore||r.mark||(r.node=o)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new JA(t,JA.schemaRules(t)))}};const IV={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},W_e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},MV={ol:!0,ul:!0},Dv=1,XA=2,Z0=4;function eR(e,t,n){return t!=null?(t?Dv:0)|(t==="full"?XA:0):e&&e.whitespace=="pre"?Dv|XA:n&~Z0}class By{constructor(t,n,i,o,s,r){this.type=t,this.attrs=n,this.marks=i,this.solid=o,this.options=r,this.content=[],this.activeMarks=Vi.none,this.match=s||(r&Z0?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(dn.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let i=this.type.contentMatch,o;return(o=i.findWrapping(t.type))?(this.match=i,o):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&Dv)){let i=this.content[this.content.length-1],o;if(i&&i.isText&&(o=/[ \t\r\n\u000c]+$/.exec(i.text))){let s=i;i.text.length==o[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-o[0].length))}}let n=dn.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(dn.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!IV.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class tR{constructor(t,n,i){this.parser=t,this.options=n,this.isOpen=i,this.open=0,this.localPreserveWS=!1;let o=n.topNode,s,r=eR(null,n.preserveWhitespace,0)|(i?Z0:0);o?s=new By(o.type,o.attrs,Vi.none,!0,n.topMatch||o.type.contentMatch,r):i?s=new By(null,null,Vi.none,!0,null,r):s=new By(t.schema.topNodeType,null,Vi.none,!0,null,r),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,n){t.nodeType==3?this.addTextNode(t,n):t.nodeType==1&&this.addElement(t,n)}addTextNode(t,n){let i=t.nodeValue,o=this.top,s=o.options&XA?"full":this.localPreserveWS||(o.options&Dv)>0,{schema:r}=this.parser;if(s==="full"||o.inlineContext(t)||/[^ \t\r\n\u000c]/.test(i)){if(s)if(s==="full")i=i.replace(/\r\n?/g,` -`);else if(r.linebreakReplacement&&/[\r\n]/.test(i)&&this.top.findWrapping(r.linebreakReplacement.create())){let l=i.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(u)):n=n.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return n}addElementByRule(t,n,i,o){let s,r;if(n.node)if(r=this.parser.schema.nodes[n.node],r.isLeaf)this.insertNode(r.create(n.attrs),i,t.nodeName=="BR")||this.leafFallback(t,i);else{let a=this.enter(r,n.attrs||null,i,n.preserveWhitespace);a&&(s=!0,i=a)}else{let a=this.parser.schema.marks[n.mark];i=i.concat(a.create(n.attrs))}let l=this.top;if(r&&r.isLeaf)this.findInside(t);else if(o)this.addElement(t,i,o);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(a=>this.insertNode(a,i,!1));else{let a=t;typeof n.contentElement=="string"?a=t.querySelector(n.contentElement):typeof n.contentElement=="function"?a=n.contentElement(t):n.contentElement&&(a=n.contentElement),this.findAround(t,a,!0),this.addAll(a,i),this.findAround(t,a,!1)}s&&this.sync(l)&&this.open--}addAll(t,n,i,o){let s=i||0;for(let r=i?t.childNodes[i]:t.firstChild,l=o==null?null:t.childNodes[o];r!=l;r=r.nextSibling,++s)this.findAtPoint(t,s),this.addDOM(r,n);this.findAtPoint(t,s)}findPlace(t,n,i){let o,s;for(let r=this.open,l=0;r>=0;r--){let a=this.nodes[r],u=a.findWrapping(t);if(u&&(!o||o.length>u.length+l)&&(o=u,s=a,!u.length))break;if(a.solid){if(i)break;l+=2}}if(!o)return null;this.sync(s);for(let r=0;r(r.type?r.type.allowsMarkType(u.type):iR(u.type,t))?(a=u.addToSet(a),!1):!0),this.nodes.push(new By(t,n,a,o,null,l)),this.open++,i}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let n=this.open;n>=0;n--){if(this.nodes[n]==t)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Dv)}return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let i=this.nodes[n].content;for(let o=i.length-1;o>=0;o--)t+=i[o].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let i=0;i-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),i=this.options.context,o=!this.isOpen&&(!i||i.parent.type==this.nodes[0].type),s=-(i?i.depth+1:0)+(o?0:1),r=(l,a)=>{for(;l>=0;l--){let u=n[l];if(u==""){if(l==n.length-1||l==0)continue;for(;a>=s;a--)if(r(l-1,a))return!0;return!1}else{let c=a>0||a==0&&o?this.nodes[a].type:i&&a>=s?i.node(a-s).type:null;if(!c||c.name!=u&&!c.isInGroup(u))return!1;a--}}return!0};return r(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let i=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(i&&i.isTextblock&&i.defaultAttrs)return i}for(let n in this.parser.schema.nodes){let i=this.parser.schema.nodes[n];if(i.isTextblock&&i.defaultAttrs)return i}}}function q_e(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let i=t.nodeType==1?t.nodeName.toLowerCase():null;i&&MV.hasOwnProperty(i)&&n?(n.appendChild(t),t=n):i=="li"?n=t:i&&(n=null)}}function U_e(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function nR(e){let t={};for(let n in e)t[n]=e[n];return t}function iR(e,t){let n=t.schema.nodes;for(let i in n){let o=n[i];if(!o.allowsMarkType(e))continue;let s=[],r=l=>{s.push(l);for(let a=0;a{if(s.length||r.marks.length){let l=0,a=0;for(;l=0;o--){let s=this.serializeMark(t.marks[o],t.isInline,n);s&&((s.contentDOM||s.dom).appendChild(i),i=s.dom)}return i}serializeMark(t,n,i={}){let o=this.marks[t.type.name];return o&&F9(zy(i),o(t,n),null,t.attrs)}static renderSpec(t,n,i=null,o){return typeof n=="string"?{dom:t.createTextNode(n)}:F9(t,n,i,o)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new rc(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=oR(t.nodes);return n.text||(n.text=i=>i.text),n}static marksFromSchema(t){return oR(t.marks)}}function oR(e){let t={};for(let n in e){let i=e[n].spec.toDOM;i&&(t[n]=i)}return t}function zy(e){return e.document||window.document}const sR=new WeakMap;function V_e(e){let t=sR.get(e);return t===void 0&&sR.set(e,t=K_e(e)),t}function K_e(e){let t=null;function n(i){if(i&&typeof i=="object")if(Array.isArray(i))if(typeof i[0]=="string")t||(t=[]),t.push(i);else for(let o=0;o-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let r=o.indexOf(" ");r>0&&(n=o.slice(0,r),o=o.slice(r+1));let l,a=n?e.createElementNS(n,o):e.createElement(o),u=t[1],c=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){c=2;for(let d in u)if(u[d]!=null){let h=d.indexOf(" ");h>0?a.setAttributeNS(d.slice(0,h),d.slice(h+1),u[d]):d=="style"&&a.style?a.style.cssText=u[d]:a.setAttribute(d,u[d])}}for(let d=c;dc)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof h=="string")a.appendChild(e.createTextNode(h));else{let{dom:p,contentDOM:m}=F9(e,h,n,i);if(a.appendChild(p),m){if(l)throw new RangeError("Multiple content holes");l=m}}}return{dom:a,contentDOM:l}}const fi=new z_e({nodes:{doc:{content:"block+"},paragraph:{group:"block",content:"inline*",toDOM:()=>["p",0],parseDOM:[{tag:"p"}]},text:{group:"inline"},mention:{group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{kind:{},name:{},path:{default:""}},leafText:e=>wp(e.attrs),toDOM:e=>{const t=e.attrs;return["span",{class:`mention-pill mention-${t.kind}`,"data-mention-path":t.path},t.name]}},attachment:{group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{attId:{},name:{},kind:{}},leafText:e=>Cf(e.attrs),toDOM:e=>{const t=e.attrs;return["span",{class:`attachment-pill attachment-${t.kind}`,"data-attachment-id":t.attId,"data-attachment-kind":t.kind,"data-attachment-name":t.name},t.name]}},quote:{group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{text:{},comment:{default:""},source:{default:""}},leafText:e=>H4(e.attrs),toDOM:e=>{const t=e.attrs,n={class:"quote-pill","data-quote-text":t.text};return typeof t.comment=="string"&&t.comment.length>0&&(n["data-quote-comment"]=t.comment),typeof t.source=="string"&&t.source.length>0&&(n["data-quote-source"]=t.source),["span",n,mm(t.text)]}}}});function TV(e){return fi.nodes.mention.create(e)}function EV(e){return fi.nodes.attachment.create(e)}function LV(e){return fi.nodes.quote.create(e)}function Z_e(e,t){return e?rV(e,t).map(n=>n.type==="mention"?TV(n.attrs):n.type==="attachment"?EV(n.attrs):n.type==="quote"?LV(n.attrs):fi.text(n.value)):[]}function Fv(e,t){const n=e.split(` -`);return fi.node("doc",null,n.map(i=>i?fi.node("paragraph",null,t?.reviveMentions?Z_e(i,t?.attachmentKindFor):fi.text(i)):fi.node("paragraph")))}function Rv(e){return e.textBetween(0,e.content.size,` -`)}const NV=65535,DV=Math.pow(2,16);function G_e(e,t){return e+t*DV}function rR(e){return e&NV}function Q_e(e){return(e-(e&NV))/DV}const FV=1,RV=2,R9=4,OV=8;class e6{constructor(t,n,i){this.pos=t,this.delInfo=n,this.recover=i}get deleted(){return(this.delInfo&OV)>0}get deletedBefore(){return(this.delInfo&(FV|R9))>0}get deletedAfter(){return(this.delInfo&(RV|R9))>0}get deletedAcross(){return(this.delInfo&R9)>0}}class ca{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&ca.empty)return ca.empty}recover(t){let n=0,i=rR(t);if(!this.inverted)for(let o=0;ot)break;let u=this.ranges[l+s],c=this.ranges[l+r],d=a+u;if(t<=d){let h=u?t==a?-1:t==d?1:n:n,p=a+o+(h<0?0:c);if(i)return p;let m=t==(n<0?a:d)?null:G_e(l/3,t-a),g=t==a?RV:t==d?FV:R9;return(n<0?t!=a:t!=d)&&(g|=OV),new e6(p,g,m)}o+=c-u}return i?t+o:new e6(t+o,0,null)}touches(t,n){let i=0,o=rR(n),s=this.inverted?2:1,r=this.inverted?1:2;for(let l=0;lt)break;let u=this.ranges[l+s],c=a+u;if(t<=c&&l==o*3)return!0;i+=this.ranges[l+r]-u}return!1}forEach(t){let n=this.inverted?2:1,i=this.inverted?1:2;for(let o=0,s=0;o=0;n--){let o=t.getMirror(n);this.appendMap(t._maps[n].invert(),o!=null&&o>n?i-o-1:void 0)}}invert(){let t=new Ov;return t.appendMappingInverted(this),t}map(t,n=1){if(this.mirror)return this._map(t,n,!0);for(let i=this.from;is&&a!r.isAtom||!l.type.allowsMarkType(this.mark.type)?r:r.mark(this.mark.addToSet(r.marks)),o),n.openStart,n.openEnd);return js.fromReplace(t,this.from,this.to,s)}invert(){return new ec(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),i=t.mapResult(this.to,-1);return n.deleted&&i.deleted||n.pos>=i.pos?null:new Vd(n.pos,i.pos,this.mark)}merge(t){return t instanceof Vd&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Vd(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Vd(n.from,n.to,t.markFromJSON(n.mark))}}rl.jsonID("addMark",Vd);class ec extends rl{constructor(t,n,i){super(),this.from=t,this.to=n,this.mark=i}apply(t){let n=t.slice(this.from,this.to),i=new Cn(dS(n.content,o=>o.mark(this.mark.removeFromSet(o.marks)),t),n.openStart,n.openEnd);return js.fromReplace(t,this.from,this.to,i)}invert(){return new Vd(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),i=t.mapResult(this.to,-1);return n.deleted&&i.deleted||n.pos>=i.pos?null:new ec(n.pos,i.pos,this.mark)}merge(t){return t instanceof ec&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new ec(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ec(n.from,n.to,t.markFromJSON(n.mark))}}rl.jsonID("removeMark",ec);class Kd extends rl{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return js.fail("No node at mark step's position");let i=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return js.fromReplace(t,this.pos,this.pos+1,new Cn(dn.from(i),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let i=this.mark.addToSet(n.marks);if(i.length==n.marks.length){for(let o=0;oi.pos?null:new va(n.pos,i.pos,o,s,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new va(n.from,n.to,n.gapFrom,n.gapTo,Cn.fromJSON(t,n.slice),n.insert,!!n.structure)}}rl.jsonID("replaceAround",va);function t6(e,t,n){let i=e.resolve(t),o=n-t,s=i.depth;for(;o>0&&s>0&&i.indexAfter(s)==i.node(s).childCount;)s--,o--;if(o>0){let r=i.node(s).maybeChild(i.indexAfter(s));for(;o>0;){if(!r||r.isLeaf)return!0;r=r.firstChild,o--}}return!1}function Y_e(e,t,n,i){let o=[],s=[],r,l;e.doc.nodesBetween(t,n,(a,u,c)=>{if(!a.isInline)return;let d=a.marks;if(!i.isInSet(d)&&c.type.allowsMarkType(i.type)){let h=Math.max(u,t),p=Math.min(u+a.nodeSize,n),m=i.addToSet(d);for(let g=0;ge.step(a)),s.forEach(a=>e.step(a))}function J_e(e,t,n,i){let o=[],s=0;e.doc.nodesBetween(t,n,(r,l)=>{if(!r.isInline)return;s++;let a=null;if(i instanceof U4){let u=r.marks,c;for(;c=i.isInSet(u);)(a||(a=[])).push(c),u=c.removeFromSet(u)}else i?i.isInSet(r.marks)&&(a=[i]):a=r.marks;if(a&&a.length){let u=Math.min(l+r.nodeSize,n);for(let c=0;ce.step(new ec(r.from,r.to,r.style)))}function fS(e,t,n,i=n.contentMatch,o=!0){let s=e.doc.nodeAt(t),r=[],l=t+1;for(let a=0;a=0;a--)e.step(r[a])}function X_e(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function hS(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let i=e.depth,o=0,s=0;;--i){let r=e.$from.node(i),l=e.$from.index(i)+o,a=e.$to.indexAfter(i)-s;if(in;m--)g||i.index(m)>0?(g=!0,c=dn.from(i.node(m).copy(c)),d++):a--;let h=dn.empty,p=0;for(let m=s,g=!1;m>n;m--)g||o.after(m+1)=0;r--){if(i.size){let l=n[r].type.contentMatch.matchFragment(i);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}i=dn.from(n[r].type.create(n[r].attrs,i))}let o=t.start,s=t.end;e.step(new va(o,s,o,s,new Cn(i,0,0),n.length,!0))}function nIe(e,t,n,i,o){if(!i.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=e.steps.length;e.doc.nodesBetween(t,n,(r,l)=>{let a=typeof o=="function"?o(r):o;if(r.isTextblock&&!r.hasMarkup(i,a)&&iIe(e.doc,e.mapping.slice(s).map(l),i)){let u=null;if(i.schema.linebreakReplacement){let p=i.whitespace=="pre",m=!!i.contentMatch.matchType(i.schema.linebreakReplacement);p&&!m?u=!1:!p&&m&&(u=!0)}u===!1&&$V(e,r,l,s),fS(e,e.mapping.slice(s).map(l,1),i,void 0,u===null);let c=e.mapping.slice(s),d=c.map(l,1),h=c.map(l+r.nodeSize,1);return e.step(new va(d,h,d+1,h-1,new Cn(dn.from(i.create(a,null,r.marks)),0,0),1,!0)),u===!0&&PV(e,r,l,s),!1}})}function PV(e,t,n,i){t.forEach((o,s)=>{if(o.isText){let r,l=/\r?\n|\r/g;for(;r=l.exec(o.text);){let a=e.mapping.slice(i).map(n+1+s+r.index);e.replaceWith(a,a+1,t.type.schema.linebreakReplacement.create())}}})}function $V(e,t,n,i){t.forEach((o,s)=>{if(o.type==o.type.schema.linebreakReplacement){let r=e.mapping.slice(i).map(n+1+s);e.replaceWith(r,r+1,t.type.schema.text(` -`))}})}function iIe(e,t,n){let i=e.resolve(t),o=i.index();return i.parent.canReplaceWith(o,o+1,n)}function oIe(e,t,n,i,o){let s=e.doc.nodeAt(t);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let r=n.create(i,null,o||s.marks);if(s.isLeaf)return e.replaceWith(t,t+s.nodeSize,r);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);e.step(new va(t,t+s.nodeSize,t+1,t+s.nodeSize-1,new Cn(dn.from(r),0,0),1,!0))}function O9(e,t,n=1,i){let o=e.resolve(t),s=o.depth-n,r=i&&i[i.length-1]||o.parent;if(s<0||o.parent.type.spec.isolating||!o.parent.canReplace(o.index(),o.parent.childCount)||!r.type.validContent(o.parent.content.cutByIndex(o.index(),o.parent.childCount)))return!1;for(let u=o.depth-1,c=n-2;u>s;u--,c--){let d=o.node(u),h=o.index(u);if(d.type.spec.isolating)return!1;let p=d.content.cutByIndex(h,d.childCount),m=i&&i[c+1];m&&(p=p.replaceChild(0,m.type.create(m.attrs)));let g=i&&i[c]||d;if(!d.canReplace(h+1,d.childCount)||!g.type.validContent(p))return!1}let l=o.indexAfter(s),a=i&&i[0];return o.node(s).canReplaceWith(l,l,a?a.type:o.node(s+1).type)}function sIe(e,t,n=1,i){let o=e.doc.resolve(t),s=dn.empty,r=dn.empty;for(let l=o.depth,a=o.depth-n,u=n-1;l>a;l--,u--){s=dn.from(o.node(l).copy(s));let c=i&&i[u];r=dn.from(c?c.type.create(c.attrs,r):o.node(l).copy(r))}e.step(new Ar(t,t,new Cn(s.append(r),n,n),!0))}function BV(e,t){let n=e.resolve(t),i=n.index();return lIe(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(i,i+1)}function rIe(e,t){t.content.size||e.type.compatibleContent(t.type);let n=e.contentMatchAt(e.childCount),{linebreakReplacement:i}=e.type.schema;for(let o=0;o=0;o--){let s=i.index(o);if(i.node(o).canReplaceWith(s,s,n))return i.before(o+1);if(s>0)return null}if(i.parentOffset==i.parent.content.size)for(let o=i.depth-1;o>=0;o--){let s=i.indexAfter(o);if(i.node(o).canReplaceWith(s,s,n))return i.after(o+1);if(s=0;r--){let l=r==i.depth?0:i.pos<=(i.start(r+1)+i.end(r+1))/2?-1:1,a=i.index(r)+(l>0?1:0),u=i.node(r),c=!1;if(s==1)c=u.canReplace(a,a,o);else{let d=u.contentMatchAt(a).findWrapping(o.firstChild.type);c=d&&u.canReplaceWith(a,a,d[0])}if(c)return l==0?i.pos:l<0?i.before(r+1):i.after(r+1)}return null}function pS(e,t,n=t,i=Cn.empty){if(t==n&&!i.size)return null;let o=e.resolve(t),s=e.resolve(n);return zV(o,s,i)?new Ar(t,n,i):new dIe(o,s,i).fit()}function zV(e,t,n){return!n.openStart&&!n.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),n.content)}class dIe{constructor(t,n,i){this.$from=t,this.$to=n,this.unplaced=i,this.frontier=[],this.placed=dn.empty;for(let o=0;o<=t.depth;o++){let s=t.node(o);this.frontier.push({type:s.type,match:s.contentMatchAt(t.indexAfter(o))})}for(let o=t.depth;o>0;o--)this.placed=dn.from(t.node(o).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let u=this.findFittable();u?this.placeNodes(u):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,i=this.$from,o=this.close(t<0?this.$to:i.doc.resolve(t));if(!o)return null;let s=this.placed,r=i.depth,l=o.depth;for(;r&&l&&s.childCount==1;)s=s.firstChild.content,r--,l--;let a=new Cn(s,r,l);return t>-1?new va(i.pos,t,this.$to.pos,this.$to.end(),a,n):a.size||i.pos!=this.$to.pos?new Ar(i.pos,o.pos,a):null}findFittable(){let t=this.unplaced.openStart;for(let n=this.unplaced.content,i=0,o=this.unplaced.openEnd;i1&&(o=0),s.type.spec.isolating&&o<=i){t=i;break}n=s.content}for(let n=1;n<=2;n++)for(let i=n==1?t:this.unplaced.openStart;i>=0;i--){let o,s=null;i?(s=Tw(this.unplaced.content,i-1).firstChild,o=s.content):o=this.unplaced.content;let r=o.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:u}=this.frontier[l],c,d=null;if(n==1&&(r?u.matchType(r.type)||(d=u.fillBefore(dn.from(r),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:i,frontierDepth:l,parent:s,inject:d};if(n==2&&r&&(c=u.findWrapping(r.type)))return{sliceDepth:i,frontierDepth:l,parent:s,wrap:c};if(s&&u.matchType(s.type))break}}}openMore(){let{content:t,openStart:n,openEnd:i}=this.unplaced,o=Tw(t,n);return!o.childCount||o.firstChild.isLeaf?!1:(this.unplaced=new Cn(t,n+1,Math.max(i,o.size+n>=t.size-i?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:i}=this.unplaced,o=Tw(t,n);if(o.childCount<=1&&n>0){let s=t.size-n<=n+o.size;this.unplaced=new Cn(r0(t,n-1,1),n-1,s?n-1:i)}else this.unplaced=new Cn(r0(t,n,1),n,i)}placeNodes({sliceDepth:t,frontierDepth:n,parent:i,inject:o,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let g=0;g1||a==0||g.content.size)&&(d=y,c.push(jV(g.mark(h.allowedMarks(g.marks)),u==1?a:0,u==l.childCount?p:-1)))}let m=u==l.childCount;m||(p=-1),this.placed=l0(this.placed,n,dn.from(c)),this.frontier[n].match=d,m&&p<0&&i&&i.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let g=0,y=l;g1&&o==this.$to.end(--i);)++o;return o}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:i,type:o}=this.frontier[n],s=n=0;l--){let{match:a,type:u}=this.frontier[l],c=Ew(t,l,u,a,!0);if(!c||c.childCount)continue e}return{depth:n,fit:r,move:s?t.doc.resolve(t.after(n+1)):t}}}}close(t){let n=this.findCloseLevel(t);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=l0(this.placed,n.depth,n.fit)),t=n.move;for(let i=n.depth+1;i<=t.depth;i++){let o=t.node(i),s=o.type.contentMatch.fillBefore(o.content,!0,t.index(i));this.openFrontierNode(o.type,o.attrs,s)}return t}openFrontierNode(t,n=null,i){let o=this.frontier[this.depth];o.match=o.match.matchType(t),this.placed=l0(this.placed,this.depth,dn.from(t.create(n,i))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(dn.empty,!0);n.childCount&&(this.placed=l0(this.placed,this.frontier.length,n))}}function r0(e,t,n){return t==0?e.cutByIndex(n,e.childCount):e.replaceChild(0,e.firstChild.copy(r0(e.firstChild.content,t-1,n)))}function l0(e,t,n){return t==0?e.append(n):e.replaceChild(e.childCount-1,e.lastChild.copy(l0(e.lastChild.content,t-1,n)))}function Tw(e,t){for(let n=0;n1&&(i=i.replaceChild(0,jV(i.firstChild,t-1,i.childCount==1?n-1:0))),t>0&&(i=e.type.contentMatch.fillBefore(i).append(i),n<=0&&(i=i.append(e.type.contentMatch.matchFragment(i).fillBefore(dn.empty,!0)))),e.copy(i)}function Ew(e,t,n,i,o){let s=e.node(t),r=o?e.indexAfter(t):e.index(t);if(r==s.childCount&&!n.compatibleContent(s.type))return null;let l=i.fillBefore(s.content,!0,r);return l&&!fIe(n,s.content,r)?l:null}function fIe(e,t,n){for(let i=n;i0;h--,p--){let m=o.node(h).type.spec;if(m.defining||m.definingAsContext||m.isolating)break;r.indexOf(h)>-1?l=h:o.before(h)==p&&r.splice(1,0,-h)}let a=r.indexOf(l),u=[],c=i.openStart;for(let h=i.content,p=0;;p++){let m=h.firstChild;if(u.push(m),p==i.openStart)break;h=m.content}for(let h=c-1;h>=0;h--){let p=u[h],m=hIe(p.type);if(m&&!p.sameMarkup(o.node(Math.abs(l)-1)))c=h;else if(m||!p.type.isTextblock)break}for(let h=i.openStart;h>=0;h--){let p=(h+c+1)%(i.openStart+1),m=u[p];if(m)for(let g=0;g=0&&(e.replace(t,n,i),!(e.steps.length>d));h--){let p=r[h];p<0||(t=o.before(p),n=s.after(p))}}function HV(e,t,n,i,o){if(ti){let s=o.contentMatchAt(0),r=s.fillBefore(e).append(e);e=r.append(s.matchFragment(r).fillBefore(dn.empty,!0))}return e}function mIe(e,t,n,i){if(!i.isInline&&t==n&&e.doc.resolve(t).parent.content.size){let o=uIe(e.doc,t,i.type);o!=null&&(t=n=o)}e.replaceRange(t,n,new Cn(dn.from(i),0,0))}function gIe(e,t,n){let i=e.doc.resolve(t),o=e.doc.resolve(n);if(i.parent.isTextblock&&o.parent.isTextblock&&i.start()!=o.start()&&i.parentOffset==0&&o.parentOffset==0){let r=i.sharedDepth(n),l=!1;for(let a=i.depth;a>r;a--)i.node(a).type.spec.isolating&&(l=!0);for(let a=o.depth;a>r;a--)o.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);for(let a=o.depth;a>0&&n==o.start(a);a--)n=o.before(a);i=e.doc.resolve(t),o=e.doc.resolve(n)}}let s=WV(i,o);for(let r=0;r0&&(a||i.node(l-1).canReplace(i.index(l-1),o.indexAfter(l-1))))return e.delete(i.before(l),o.after(l))}for(let r=1;r<=i.depth&&r<=o.depth;r++)if(t-i.start(r)==i.depth-r&&n>i.end(r)&&o.end(r)-n!=o.depth-r&&i.start(r-1)==o.start(r-1)&&i.node(r-1).canReplace(i.index(r-1),o.index(r-1)))return e.delete(i.before(r),n);e.delete(t,n)}function WV(e,t){let n=[],i=Math.min(e.depth,t.depth);for(let o=i;o>=0;o--){let s=e.start(o);if(st.pos+(t.depth-o)||e.node(o).type.spec.isolating||t.node(o).type.spec.isolating)break;(s==t.start(o)||o==e.depth&&o==t.depth&&e.parent.inlineContent&&t.parent.inlineContent&&o&&t.start(o-1)==s-1)&&n.push(o)}return n}class Y1 extends rl{constructor(t,n,i){super(),this.pos=t,this.attr=n,this.value=i}apply(t){let n=t.nodeAt(this.pos);if(!n)return js.fail("No node at attribute step's position");let i=Object.create(null);for(let s in n.attrs)i[s]=n.attrs[s];i[this.attr]=this.value;let o=n.type.create(i,null,n.marks);return js.fromReplace(t,this.pos,this.pos+1,new Cn(dn.from(o),0,n.isLeaf?0:1))}getMap(){return ca.empty}invert(t){return new Y1(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new Y1(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Y1(n.pos,n.attr,n.value)}}rl.jsonID("attr",Y1);class Pv extends rl{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let o in t.attrs)n[o]=t.attrs[o];n[this.attr]=this.value;let i=t.type.create(n,t.content,t.marks);return js.ok(i)}getMap(){return ca.empty}invert(t){return new Pv(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Pv(n.attr,n.value)}}rl.jsonID("docAttr",Pv);let gm=class extends Error{};gm=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n};gm.prototype=Object.create(Error.prototype);gm.prototype.constructor=gm;gm.prototype.name="TransformError";class vIe{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new Ov}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new gm(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let i=0;i{t=Math.min(t,l),n=Math.max(n,a)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,i=Cn.empty){let o=pS(this.doc,t,n,i);return o&&this.step(o),this}replaceWith(t,n,i){return this.replace(t,n,new Cn(dn.from(i),0,0))}delete(t,n){return this.replace(t,n,Cn.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,i){return pIe(this,t,n,i),this}replaceRangeWith(t,n,i){return mIe(this,t,n,i),this}deleteRange(t,n){return gIe(this,t,n),this}lift(t,n){return eIe(this,t,n),this}join(t,n=1){return aIe(this,t,n),this}wrap(t,n){return tIe(this,t,n),this}setBlockType(t,n=t,i,o=null){return nIe(this,t,n,i,o),this}setNodeMarkup(t,n,i=null,o){return oIe(this,t,n,i,o),this}setNodeAttribute(t,n,i){return this.step(new Y1(t,n,i)),this}setDocAttribute(t,n){return this.step(new Pv(t,n)),this}addNodeMark(t,n){return this.step(new Kd(t,n)),this}removeNodeMark(t,n){let i=this.doc.nodeAt(t);if(!i)throw new RangeError("No node at position "+t);if(n instanceof Vi)n.isInSet(i.marks)&&this.step(new cp(t,n));else{let o=i.marks,s,r=[];for(;s=n.isInSet(o);)r.push(new cp(t,s)),o=s.removeFromSet(o);for(let l=r.length-1;l>=0;l--)this.step(r[l])}return this}split(t,n=1,i){return sIe(this,t,n,i),this}addMark(t,n,i){return Y_e(this,t,n,i),this}removeMark(t,n,i){return J_e(this,t,n,i),this}clearIncompatible(t,n,i){return fS(this,t,n,i),this}}const Lw=Object.create(null);class to{constructor(t,n,i){this.$anchor=t,this.$head=n,this.ranges=i||[new yIe(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n=0;s--){let r=n<0?p1(t.node(0),t.node(s),t.before(s+1),t.index(s),n,i):p1(t.node(0),t.node(s),t.after(s+1),t.index(s)+1,n,i);if(r)return r}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new ya(t.node(0))}static atStart(t){return p1(t,t,0,0,1)||new ya(t)}static atEnd(t){return p1(t,t,t.content.size,t.childCount,-1)||new ya(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let i=Lw[n.type];if(!i)throw new RangeError(`No selection type ${n.type} defined`);return i.fromJSON(t,n)}static jsonID(t,n){if(t in Lw)throw new RangeError("Duplicate use of selection JSON ID "+t);return Lw[t]=n,n.prototype.jsonID=t,n}getBookmark(){return ti.between(this.$anchor,this.$head).getBookmark()}}to.prototype.visible=!0;class yIe{constructor(t,n){this.$from=t,this.$to=n}}let lR=!1;function aR(e){!lR&&!e.parent.inlineContent&&(lR=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+e.parent.type.name+")"))}class ti extends to{constructor(t,n=t){aR(t),aR(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let i=t.resolve(n.map(this.head));if(!i.parent.inlineContent)return to.near(i);let o=t.resolve(n.map(this.anchor));return new ti(o.parent.inlineContent?o:i,i)}replace(t,n=Cn.empty){if(super.replace(t,n),n==Cn.empty){let i=this.$from.marksAcross(this.$to);i&&t.ensureMarks(i)}}eq(t){return t instanceof ti&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new V4(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new ti(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,i=n){let o=t.resolve(n);return new this(o,i==n?o:t.resolve(i))}static between(t,n,i){let o=t.pos-n.pos;if((!i||o)&&(i=o>=0?1:-1),!n.parent.inlineContent){let s=to.findFrom(n,i,!0)||to.findFrom(n,-i,!0);if(s)n=s.$head;else return to.near(n,i)}return t.parent.inlineContent||(o==0?t=n:(t=(to.findFrom(t,-i,!0)||to.findFrom(t,i,!0)).$anchor,t.pos0?0:1);o>0?r=0;r+=o){let l=t.child(r);if(l.isAtom){if(!s&&Yn.isSelectable(l))return Yn.create(e,n-(o<0?l.nodeSize:0))}else{let a=p1(e,l,n+o,o<0?l.childCount:0,o,s);if(a)return a}n+=l.nodeSize*o}return null}function uR(e,t,n){let i=e.steps.length-1;if(i{r==null&&(r=c)}),e.setSelection(to.near(e.doc.resolve(r),n))}const cR=1,jy=2,dR=4;class bIe extends vIe{constructor(t){super(t.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(t){return this.storedMarks=t,this.updated|=jy,this}ensureMarks(t){return Vi.sameSet(this.storedMarks||this.selection.$from.marks(),t)||this.setStoredMarks(t),this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&jy)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~jy,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,n=!0){let i=this.selection;return n&&(t=t.mark(this.storedMarks||(i.empty?i.$from.marks():i.$from.marksAcross(i.$to)||Vi.none))),i.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,n,i){let o=this.doc.type.schema;if(n==null)return t?this.replaceSelectionWith(o.text(t),!0):this.deleteSelection();{if(i==null&&(i=n),!t)return this.deleteRange(n,i);let s=this.storedMarks;if(!s){let r=this.doc.resolve(n);s=i==n?r.marks():r.marksAcross(this.doc.resolve(i))}return this.replaceRangeWith(n,i,o.text(t,s)),!this.selection.empty&&this.selection.to==n+t.length&&this.setSelection(to.near(this.selection.$to)),this}}setMeta(t,n){return this.meta[typeof t=="string"?t:t.key]=n,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=dR,this}get scrolledIntoView(){return(this.updated&dR)>0}}function fR(e,t){return!t||!e?e:e.bind(t)}class a0{constructor(t,n,i){this.name=t,this.init=fR(n.init,i),this.apply=fR(n.apply,i)}}const wIe=[new a0("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new a0("selection",{init(e,t){return e.selection||to.atStart(t.doc)},apply(e){return e.selection}}),new a0("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,i){return i.selection.$cursor?e.storedMarks:null}}),new a0("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}})];class Nw{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=wIe.slice(),n&&n.forEach(i=>{if(this.pluginsByKey[i.key])throw new RangeError("Adding different instances of a keyed plugin ("+i.key+")");this.plugins.push(i),this.pluginsByKey[i.key]=i,i.spec.state&&this.fields.push(new a0(i.key,i.spec.state,i))})}}class Nh{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,n=-1){for(let i=0;ii.toJSON())),t&&typeof t=="object")for(let i in t){if(i=="doc"||i=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let o=t[i],s=o.spec.state;s&&s.toJSON&&(n[i]=s.toJSON.call(o,this[o.key]))}return n}static fromJSON(t,n,i){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let o=new Nw(t.schema,t.plugins),s=new Nh(o);return o.fields.forEach(r=>{if(r.name=="doc")s.doc=Gh.fromJSON(t.schema,n.doc);else if(r.name=="selection")s.selection=to.fromJSON(s.doc,n.selection);else if(r.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(t.schema.markFromJSON));else{if(i)for(let l in i){let a=i[l],u=a.spec.state;if(a.key==r.name&&u&&u.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[r.name]=u.fromJSON.call(a,t,n[l],s);return}}s[r.name]=r.init(t,s)}}),s}}function qV(e,t,n){for(let i in e){let o=e[i];o instanceof Function?o=o.bind(t):i=="handleDOMEvents"&&(o=qV(o,t,{})),n[i]=o}return n}class d2{constructor(t){this.spec=t,this.props={},t.props&&qV(t.props,this,this.props),this.key=t.key?t.key.key:UV("plugin")}getState(t){return t[this.key]}}const Dw=Object.create(null);function UV(e){return e in Dw?e+"$"+ ++Dw[e]:(Dw[e]=0,e+"$")}class gS{constructor(t="key"){this.key=UV(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}function G0(e){return e.isText?e.text.length:e.type===fi.nodes.attachment?Cf(e.attrs).length:e.type===fi.nodes.quote?H4(e.attrs).length:wp(e.attrs).length}function CIe(e,t){if(!t.parent.isTextblock)return tc(e,t.pos);if(t.textOffset>0)return tc(e,t.pos-t.textOffset);const n=t.nodeBefore;return n&&n.isText?tc(e,t.pos-n.nodeSize):tc(e,t.pos)}function Jc(e,t){let n=Math.max(0,t),i=-1;return e.forEach((o,s)=>{if(i!==-1)return;let r=0;if(o.forEach(l=>{r+=G0(l)}),n>r){n-=r+1;return}o.forEach((l,a)=>{if(i!==-1)return;const u=s+1+a,c=G0(l);if(n<=c){l.isText?i=u+n:i=n===0?u:u+1;return}n-=c}),i===-1&&(i=s+1+o.content.size)}),i===-1?e.content.size-1:i}function tc(e,t){let n=0,i=-1;return e.forEach((o,s)=>{if(i!==-1)return;const r=s+o.nodeSize;if(t>r){o.forEach(a=>{n+=G0(a)}),n+=1;return}let l=0;o.forEach((a,u)=>{if(i!==-1)return;const c=s+1+u;if(a.isText){const d=c+a.nodeSize;if(t<=d){i=n+l+Math.max(0,t-c);return}l+=a.text.length}else{const d=c+1;if(t<=d){i=n+l+(t<=c?0:G0(a));return}l+=G0(a)}}),i===-1&&(i=n+l)}),i===-1?n:i}function AIe(e){const t=[];return e.forEach(n=>{n.forEach(i=>{!i.isText&&i.type===fi.nodes.mention&&i.attrs.kind==="skill"&&t.push({name:i.attrs.name})})}),t}function hR(e){return(t,n)=>{const i=t.selection.$head,o=e?i.start():i.end();return n&&n(t.tr.setSelection(ti.create(t.doc,t.selection.$anchor.pos,o)).scrollIntoView()),!0}}var pb=200,Sr=function(){};Sr.prototype.append=function(t){return t.length?(t=Sr.from(t),!this.length&&t||t.length=n?Sr.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Sr.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Sr.prototype.forEach=function(t,n,i){n===void 0&&(n=0),i===void 0&&(i=this.length),n<=i?this.forEachInner(t,n,i,0):this.forEachInvertedInner(t,n,i,0)};Sr.prototype.map=function(t,n,i){n===void 0&&(n=0),i===void 0&&(i=this.length);var o=[];return this.forEach(function(s,r){return o.push(t(s,r))},n,i),o};Sr.from=function(t){return t instanceof Sr?t:t&&t.length?new VV(t):Sr.empty};var VV=(function(e){function t(i){e.call(this),this.values=i}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(o,s){return o==0&&s==this.length?this:new t(this.values.slice(o,s))},t.prototype.getInner=function(o){return this.values[o]},t.prototype.forEachInner=function(o,s,r,l){for(var a=s;a=r;a--)if(o(this.values[a],l+a)===!1)return!1},t.prototype.leafAppend=function(o){if(this.length+o.length<=pb)return new t(this.values.concat(o.flatten()))},t.prototype.leafPrepend=function(o){if(this.length+o.length<=pb)return new t(o.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(t.prototype,n),t})(Sr);Sr.empty=new VV([]);var xIe=(function(e){function t(n,i){e.call(this),this.left=n,this.right=i,this.length=n.length+i.length,this.depth=Math.max(n.depth,i.depth)+1}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(i){return il&&this.right.forEachInner(i,Math.max(o-l,0),Math.min(this.length,s)-l,r+l)===!1)return!1},t.prototype.forEachInvertedInner=function(i,o,s,r){var l=this.left.length;if(o>l&&this.right.forEachInvertedInner(i,o-l,Math.max(s,l)-l,r+l)===!1||s=s?this.right.slice(i-s,o-s):this.left.slice(i,s).append(this.right.slice(0,o-s))},t.prototype.leafAppend=function(i){var o=this.right.leafAppend(i);if(o)return new t(this.left,o)},t.prototype.leafPrepend=function(i){var o=this.left.leafPrepend(i);if(o)return new t(o,this.right)},t.prototype.appendInner=function(i){return this.left.depth>=Math.max(this.right.depth,i.depth)+1?new t(this.left,new t(this.right,i)):new t(this,i)},t})(Sr);const SIe=500;class hu{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let i=this.items.length;for(;;i--)if(this.items.get(i-1).selection){--i;break}let o,s;n&&(o=this.remapping(i,this.items.length),s=o.maps.length);let r=t.tr,l,a,u=[],c=[];return this.items.forEach((d,h)=>{if(!d.step){o||(o=this.remapping(i,h+1),s=o.maps.length),s--,c.push(d);return}if(o){c.push(new Hu(d.map));let p=d.step.map(o.slice(s)),m;p&&r.maybeStep(p).doc&&(m=r.mapping.maps[r.mapping.maps.length-1],u.push(new Hu(m,void 0,void 0,u.length+c.length))),s--,m&&o.appendMap(m,s)}else r.maybeStep(d.step);if(d.selection)return l=o?d.selection.map(o.slice(s)):d.selection,a=new hu(this.items.slice(0,i).append(c.reverse().concat(u)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:r,selection:l}}addTransform(t,n,i,o){let s=[],r=this.eventCount,l=this.items,a=!o&&l.length?l.get(l.length-1):null;for(let c=0;cIIe&&(l=_Ie(l,u),r-=u),new hu(l.append(s),r)}remapping(t,n){let i=new Ov;return this.items.forEach((o,s)=>{let r=o.mirrorOffset!=null&&s-o.mirrorOffset>=t?i.maps.length-o.mirrorOffset:void 0;i.appendMap(o.map,r)},t,n),i}addMaps(t){return this.eventCount==0?this:new hu(this.items.append(t.map(n=>new Hu(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let i=[],o=Math.max(0,this.items.length-n),s=t.mapping,r=t.steps.length,l=this.eventCount;this.items.forEach(h=>{h.selection&&l--},o);let a=n;this.items.forEach(h=>{let p=s.getMirror(--a);if(p==null)return;r=Math.min(r,p);let m=s.maps[p];if(h.step){let g=t.steps[p].invert(t.docs[p]),y=h.selection&&h.selection.map(s.slice(a+1,p));y&&l++,i.push(new Hu(m,g,y))}else i.push(new Hu(m))},o);let u=[];for(let h=n;hSIe&&(d=d.compress(this.items.length-i.length)),d}emptyItemCount(){let t=0;return this.items.forEach(n=>{n.step||t++}),t}compress(t=this.items.length){let n=this.remapping(0,t),i=n.maps.length,o=[],s=0;return this.items.forEach((r,l)=>{if(l>=t)o.push(r),r.selection&&s++;else if(r.step){let a=r.step.map(n.slice(i)),u=a&&a.getMap();if(i--,u&&n.appendMap(u,i),a){let c=r.selection&&r.selection.map(n.slice(i));c&&s++;let d=new Hu(u.invert(),a,c),h,p=o.length-1;(h=o.length&&o[p].merge(d))?o[p]=h:o.push(d)}}else r.map&&i--},this.items.length,0),new hu(Sr.from(o.reverse()),s)}}hu.empty=new hu(Sr.empty,0);function _Ie(e,t){let n;return e.forEach((i,o)=>{if(i.selection&&t--==0)return n=o,!1}),e.slice(n)}class Hu{constructor(t,n,i,o){this.map=t,this.step=n,this.selection=i,this.mirrorOffset=o}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new Hu(n.getMap().invert(),n,this.selection)}}}class Rd{constructor(t,n,i,o,s){this.done=t,this.undone=n,this.prevRanges=i,this.prevTime=o,this.prevComposition=s}}const IIe=20;function MIe(e,t,n,i){let o=n.getMeta(Qh),s;if(o)return o.historyState;n.getMeta(ZV)&&(e=new Rd(e.done,e.undone,null,0,-1));let r=n.getMeta("appendedTransaction");if(n.steps.length==0)return e;if(r&&r.getMeta(Qh))return r.getMeta(Qh).redo?new Rd(e.done.addTransform(n,void 0,i,P9(t)),e.undone,pR(n.mapping.maps),e.prevTime,e.prevComposition):new Rd(e.done,e.undone.addTransform(n,void 0,i,P9(t)),null,e.prevTime,e.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(r&&r.getMeta("addToHistory")===!1)){let l=n.getMeta("composition"),a=e.prevTime==0||!r&&e.prevComposition!=l&&(e.prevTime<(n.time||0)-i.newGroupDelay||!TIe(n,e.prevRanges)),u=r?Fw(e.prevRanges,n.mapping):pR(n.mapping.maps);return new Rd(e.done.addTransform(n,a?t.selection.getBookmark():void 0,i,P9(t)),hu.empty,u,n.time,l??e.prevComposition)}else return(s=n.getMeta("rebased"))?new Rd(e.done.rebased(n,s),e.undone.rebased(n,s),Fw(e.prevRanges,n.mapping),e.prevTime,e.prevComposition):new Rd(e.done.addMaps(n.mapping.maps),e.undone.addMaps(n.mapping.maps),Fw(e.prevRanges,n.mapping),e.prevTime,e.prevComposition)}function TIe(e,t){if(!t)return!1;if(!e.docChanged)return!0;let n=!1;return e.mapping.maps[0].forEach((i,o)=>{for(let s=0;s=t[s]&&(n=!0)}),n}function pR(e){let t=[];for(let n=e.length-1;n>=0&&t.length==0;n--)e[n].forEach((i,o,s,r)=>t.push(s,r));return t}function Fw(e,t){if(!e)return null;let n=[];for(let i=0;i{let o=Qh.getState(n);if(!o||(e?o.undone:o.done).eventCount==0)return!1;if(i){let s=EIe(o,n,e);s&&i(t?s.scrollIntoView():s)}return!0}}const QV=GV(!1,!0),n6=GV(!0,!0);function NIe(e,t,n){const i=Jc(e.doc,n.start),o=Jc(e.doc,n.end),s=Rv(e.doc),r=n.start>0?s.charAt(n.start-1):"",l=s.charAt(n.end),a=[];(r==="!"||r==="\\")&&a.push(fi.text(" ")),a.push(TV(t)),(l===""||!/\s/.test(l))&&a.push(fi.text(" "));const u=e.tr.replaceWith(i,o,a);return u.setSelection(ti.create(u.doc,i+a.reduce((c,d)=>c+d.nodeSize,0))),u.scrollIntoView()}function DIe(e,t,n){const i=Jc(e.doc,n.start),o=Jc(e.doc,n.end),s=e.tr.insertText(t,i,o);return s.setSelection(ti.create(s.doc,i+t.length)),KV(s.scrollIntoView())}function FIe(e,t,n){const i=n?n.start:tc(e.doc,e.selection.from),o=n?n.end:tc(e.doc,e.selection.to),s=Jc(e.doc,i),r=Jc(e.doc,o),l=Rv(e.doc),a=i>0?l.charAt(i-1):"",u=l.charAt(o),c=[];(a==="!"||a==="\\")&&c.push(fi.text(" ")),c.push(EV(t)),(u===""||!/\s/.test(u))&&c.push(fi.text(" "));const d=e.tr.replaceWith(s,r,c);return d.setSelection(ti.create(d.doc,s+c.reduce((h,p)=>h+p.nodeSize,0))),d.scrollIntoView()}function RIe(e,t,n){const i=e.selection.to,o=Rv(e.doc),s=tc(e.doc,i),r=s>0?o.charAt(s-1):"",l=o.charAt(s),a=[];r!==""&&!/\s/.test(r)&&a.push(fi.text(" ")),a.push(LV(n!==void 0&&n.length>0?{...t,comment:n}:t)),(l===""||!/\s/.test(l))&&a.push(fi.text(" "));const u=e.tr.replaceWith(i,i,a);return u.setSelection(ti.create(u.doc,i+a.reduce((c,d)=>c+d.nodeSize,0))),u.scrollIntoView()}function Hy(e,t){return Cn.maxOpen(Fv(e.replace(/\r\n?/g,` -`),t).content)}function gR(e){const t=typeof e.source=="string"&&e.source.length>0?`from: ${uS(e.source)} -`:"",n=typeof e.comment=="string"&&e.comment.length>0?` - -${e.comment}`:"";return`${t}${lV(e.text)}${n}`}function YV(e){const t=i=>i.isText?i.text??"":i.type===fi.nodes.mention?wp(i.attrs):i.type===fi.nodes.attachment?i.attrs.name:i.type===fi.nodes.quote?gR(i.attrs):i.textBetween(0,i.content.size,""),n=[];return e.content.forEach(i=>{if(i.type===fi.nodes.mention||i.type===fi.nodes.attachment||i.type===fi.nodes.quote)n.push(t(i));else{let o="",s=!1;i.forEach(r=>{if(r.type===fi.nodes.quote){const a=gR(r.attrs);o=o.length>0?`${o.replace(/ +$/,"")} - -${a}`:a,s=!0;return}let l=t(r);s&&(l=l.replace(/^ /,""),o+=` - -`,s=!1),o+=l}),n.push(o)}}),n.join(` -`)}const i6=` - - - - -`,JV=` - - - - -`,XV='',eK=` - - - -`,tK=` - - -`,nK='',iK=` - - -`,oK=` - - -`,sK=` - - -`,OIe='',PIe='',$Ie='',BIe='',zIe='',jIe={sm:14,md:16,lg:20},HIe={file:i6,folder:JV,skill:XV,copy:eK,check:tK,"external-link":nK,target:iK,"file-edit":oK,close:sK,attachment:OIe,image:PIe,video:$Ie,fullscreen:BIe,quote:zIe};function Al(e,t="md"){const n=jIe[t];return HIe[e].replace(/]*>/,i=>i.replace(/\s(?:width|height)="[^"]*"/g,"")).replace(/^
    `;case"th_open":return`${t}`;default:return null}if(n.length===1&&n[0][0]==="style"){if(e.type==="td_open")return`${t}`;if(e.type==="th_open")return`${t}`}return null}function pL(e){const t=e.attrs;return!t||t.length===0?"":t.length===1?``:t.length===2?``:``}function N1e(e){switch(e.type){case"text":case"text_special":case"softbreak":case"hardbreak":case"html_inline":case"code_inline":case"image":return!0;default:return!1}}function mL(e){switch(e.type){case"text":case"text_special":case"softbreak":case"hardbreak":case"html_inline":case"code_inline":return!0;default:return!1}}function nb(e,t){if(e.hidden)return"";const n=e.attrs,i=e.nesting,o=e.tag;if(!n||n.length===0)return i===0?t?`<${o} />`:`<${o}>`:i===-1?``:`<${o}>`;let s=(i===-1?"`}const F1e={langPrefix:"language-",xhtmlOut:!1,breaks:!1},Sy=Object.prototype.hasOwnProperty,yi={code_inline(e,t){return Ev(e[t])},code_block(e,t){return gA(e[t])},fence(e,t,n,i,o){const s=e[t],r=s.info?LH(s.info).trim():"",{langName:l,langAttrs:a}=zH(r),u=n.highlight,c=Pi(s.content);if(!u)return O0(s,c,r,l,n);const d=u(s.content,l,a);return B4(d)?d.then(f=>O0(s,f||c,r,l,n)):O0(s,d||c,r,l,n)},image(e,t,n,i,o){const s=e[t],r=o.renderInlineAsText(s.children||[],n,i),l=s.attrIndex("alt");return l>=0&&s.attrs?s.attrs[l][1]=r:s.attrs?s.attrs.push(["alt",r]):s.attrs=[["alt",r]],nb(s,n.xhtmlOut===!0)},hardbreak(e,t,n){return n.xhtmlOut?`
    +`:`
    +`},softbreak(e,t,n){return n.breaks?n.xhtmlOut?`
    +`:`
    +`:` +`},text(e,t){return Pi(e[t].content)},text_special(e,t){return Pi(e[t].content)},html_block(e,t){return e[t].content},html_inline(e,t){return e[t].content}};function gL(e,t,n){const i=e.info?LH(e.info).trim():"",{langName:o,langAttrs:s}=zH(i),r=t.highlight,l=Pi(e.content);if(!r)return O0(e,l,i,o,t);const a=r(e.content,o,s);if(B4(a))throw new TypeError('Renderer rule "fence" returned a Promise. Use renderAsync() instead.');return O0(e,a||l,i,o,t)}function V3(e,t,n,i){switch(e.type){case"text":return t.text===yi.text?e.content.length===0?"":Pi(e.content):null;case"text_special":return t.text_special===yi.text_special?e.content.length===0?"":Pi(e.content):null;case"softbreak":return t.softbreak===yi.softbreak?i:null;case"hardbreak":return t.hardbreak===yi.hardbreak?n:null;case"html_inline":return t.html_inline===yi.html_inline?e.content:null;case"code_inline":return t.code_inline===yi.code_inline?Ev(e):null;default:return null}}function D1e(e,t,n,i,o){const s=e[0];switch(s.type){case"text":if(o.text===yi.text)return s.content.length===0?"":Pi(s.content);break;case"text_special":if(o.text_special===yi.text_special)return s.content.length===0?"":Pi(s.content);break;case"softbreak":if(o.softbreak===yi.softbreak)return t.breaks?t.xhtmlOut?`
    +`:`
    +`:` +`;break;case"hardbreak":if(o.hardbreak===yi.hardbreak)return t.xhtmlOut?`
    +`:`
    +`;break;case"html_inline":if(o.html_inline===yi.html_inline)return s.content;break;case"code_inline":if(o.code_inline===yi.code_inline)return Ev(s);break}const r=o[s.type];if(!r)return nb(s,t.xhtmlOut===!0);const l=r(e,0,t,n,i);return typeof l=="string"?l:D9(l,s.type)}var R1e=class{rules;baseOptions;normalizedBase;constructor(e={}){this.baseOptions={...e},this.normalizedBase=this.buildNormalizedBase(),this.rules={...yi}}set(e){return this.baseOptions={...this.baseOptions,...e},this.normalizedBase=this.buildNormalizedBase(),this}render(e,t,n){if(!Array.isArray(e))throw new TypeError("render expects token array as first argument");if(e.length===1)return this.renderSingleToken(e,e[0],t,n);const i=this.mergeOptions(t),o=n??{},s=this.rules,r=i.xhtmlOut===!0;let l,a,u,c,d,f,h="",m="",g=!1,y="";for(let k=0;k0&&e[k-1].hidden?` +`:"";if(C==="list_item_open"&&(!v.attrs||v.attrs.length===0)&&k+3${this.renderInlineTokens(S.children||[],i,o)}`,k+=3;continue}}if(k+2 +`,k+=2;continue}}}if(C==="inline"){const E=v.children||[];if(E.length===1){g||(l=s.text,a=s.text_special,u=s.softbreak,c=s.hardbreak,d=s.html_inline,f=s.code_inline,h=i.xhtmlOut?`
    +`:`
    +`,m=i.breaks?h:` +`,g=!0);const S=E[0];switch(S.type){case"text":if(l===yi.text){y+=Pi(S.content);continue}break;case"text_special":if(a===yi.text_special){y+=Pi(S.content);continue}break;case"softbreak":if(u===yi.softbreak){y+=m;continue}break;case"hardbreak":if(c===yi.hardbreak){y+=h;continue}break;case"html_inline":if(d===yi.html_inline){y+=S.content;continue}break;case"code_inline":if(f===yi.code_inline){y+=Ev(S);continue}break}}y+=this.renderInlineTokens(E,i,o);continue}const M=s[C];if(!M){const E=v.attrs;if(!v.hidden){if(!E||E.length===0)switch(C){case"hr":y+=r?`
    +`:`
    +`;continue;case"heading_open":y+=`<${v.tag}>`;continue;case"heading_close":y+=` +`;continue;case"paragraph_open":y+=`${w}

    `;continue;case"paragraph_close":y+=`

    +`;continue;case"list_item_open":{const S=e[k+1];y+=w+(S&&(S.type==="inline"||S.hidden||S.nesting===-1&&S.tag==="li")?"
  • ":`
  • +`);continue}case"list_item_close":y+=`
  • +`;continue;case"bullet_list_open":y+=`${w}
      +`;continue;case"bullet_list_close":y+=`
    +`;continue;case"blockquote_open":y+=w+(e[k+1]&&e[k+1].nesting===-1&&e[k+1].tag==="blockquote"?"
    ":`
    +`);continue;case"blockquote_close":y+=`
    +`;continue;case"ordered_list_open":y+=`${w}
      +`;continue;case"ordered_list_close":y+=`
    +`;continue;case"table_open":y+=`${w} +`;continue;case"table_close":y+=`
    +`;continue;case"thead_open":y+=`${w}
    `;continue;case"td_close":y+=``;continue;case"th_close":y+=``;continue}if(C==="th_open"&&S[0]==="style"){y+=`${w}`;continue}}}y+=this.renderToken(e,k,i);continue}if(C==="code_block"&&M===yi.code_block){y+=gA(v);continue}if(C==="fence"&&M===yi.fence){y+=gL(v,i);continue}if(C==="html_block"&&M===yi.html_block){y+=v.content;continue}const L=M(e,k,i,o,this);typeof L=="string"?y+=L:y+=D9(L,v.type)}return y}async renderAsync(e,t,n){if(!Array.isArray(e))throw new TypeError("render expects token array as first argument");const i=this.mergeOptions(t),o=n??{},s=this.rules;let r="";for(let l=0;l0&&e[t-1].hidden?` +`:"",c=a?`> +`:">";if(!l||l.length===0)return s===0?n.xhtmlOut?`${u}<${r} /${c}`:`${u}<${r}${c}`:s===-1?`${u}(n||(n={...t}),n);if(Sy.call(e,"highlight")&&e.highlight!==t.highlight&&(i().highlight=e.highlight),Sy.call(e,"langPrefix")){const o=e.langPrefix;o!==t.langPrefix&&(i().langPrefix=o)}if(Sy.call(e,"xhtmlOut")){const o=e.xhtmlOut;o!==t.xhtmlOut&&(i().xhtmlOut=o)}if(Sy.call(e,"breaks")){const o=e.breaks;o!==t.breaks&&(i().breaks=o)}return n||t}buildNormalizedBase(){return Object.freeze({...F1e,...this.baseOptions})}renderSingleToken(e,t,n,i){const o=this.rules,s=t.type;if(s==="code_block"&&o.code_block===yi.code_block)return gA(t);if(s==="html_block"&&o.html_block===yi.html_block)return t.content;const r=this.mergeOptions(n),l=i??{};if(s==="inline")return this.renderInlineTokens(t.children||[],r,l);const a=o[s];if(!a)return t.block?this.renderToken(e,0,r):nb(t,r.xhtmlOut===!0);if(s==="fence"&&a===yi.fence)return gL(t,r);const u=a(e,0,r,l,this);return typeof u=="string"?u:D9(u,s)}renderInlineTokens(e,t,n){if(!e||e.length===0)return"";const i=this.rules;if(e.length===1)return D1e(e,t,n,this,i);const o=t.xhtmlOut===!0,s=o?`
    +`:`
    +`,r=t.breaks?s:` +`,l=i.text,a=i.text_special,u=i.softbreak,c=i.hardbreak,d=i.html_inline,f=i.code_inline,h=i.link_open,m=i.link_close,g=i.em_open,y=i.em_close,k=i.strong_open,v=i.strong_close;let C="";for(let w=0;w`;if(u===yi.softbreak&&w+3`,w+=1;continue}if(M.type==="em_open"&&!g&&!y&&w+2${x}`,w+=2;continue}}}if(M.type==="strong_open"&&!k&&!v&&w+2${x}`,w+=2;continue}}}switch(M.type){case"text":if(l===yi.text){const S=M.content.length===0?"":Pi(M.content);if(d===yi.html_inline&&w+1=4)return!0;continue}if(l===9){if(r+=4-r%4,s++,r>=4)return!0;continue}break}if(s0&&u<=6){if(a=3)return!0;break}default:if(l>=48&&l<=57){let a=s+1;for(;a57)break;a++}if(a=Z,!Y&&se!==void 0&&(he=Mo(e),Y=he>=se)),Y){const U=this.parseFullDocument(e,O,n,he,!1);return this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",ts(O,{area:"stream",path:"stream-full",reason:"skip-cache-large-one-shot",unbounded:!!Bc(O)?.unbounded}),U.tokens}else if(z){const U=(ge,ae,Ce)=>geCe?Ce:ge;he===void 0&&(he=Mo(e));const Q=le&&!te?fL(e.length,he,n.options):null,ue=Q?.maxChunkChars??(W?U(Math.ceil(e.length/$),8e3,64e3):K??1e4),me=Q?.maxChunkLines??(W?U(Math.ceil(he/$),150,700):ne??200),pe=Q?.maxChunks??(W?U(Math.ceil(e.length/64e3),$,32):G),ee=e.length>0&&e.charCodeAt(e.length-1)===10,re=P&&e.length>=this.IMPLICIT_STREAM_CHUNK_MIN_CHARS&&Q?.strategy!=="plain";if((F||re)&&(e.length>=ue*2||he>=me*2)&&ee){const ge=tb(n,e,O,{maxChunkChars:ue,maxChunkLines:me,fenceAware:Q?.fenceAware??ie,maxChunks:pe});return this.cache={src:e,tokens:ge,env:O,lineCount:he,lastSegment:void 0,globalStateReason:kl(e)},this.updateCacheLineCount(this.cache,he),this.recordChunkedParseResult(O,F?"explicit-initial-large-doc":"default-initial-large-doc"),ge}}const J=this.parseFullDocument(e,O,n,he);return he=J.lineCount,this.cache={src:e,tokens:J.tokens,env:O,lineCount:he,lastSegment:void 0,globalStateReason:kl(e)},this.updateCacheLineCount(this.cache,he),this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",ts(O,{area:"stream",path:"stream-full",reason:"initial-parse",unbounded:!!Bc(O)?.unbounded}),J.tokens}if(e===o.src)return this.stats.total+=1,this.stats.cacheHits+=1,this.stats.lastMode="cache",ts(o.env,{area:"stream",path:"stream-cache",reason:"same-source"}),o.tokens;const s=e.startsWith(o.src)?e.slice(o.src.length):null;let r=o.globalStateReason;r===void 0&&(r=kl(o.src),o.globalStateReason=r);const l=r?null:s!==null?this.detectGlobalStateForAppend(o,s):kl(e),a=r||l;if(a){const O=i??o.env;ad(O);const H=kl(e),R=this.parseFullDocument(e,O,n),F=R.tokens,P=R.lineCount;return this.cache={src:e,tokens:F,env:O,lineCount:P,lastSegment:void 0,globalStateReason:H},this.updateCacheLineCount(this.cache,P),this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",ts(O,{area:"stream",path:"stream-full",reason:`global-state:${a}`,unbounded:!!Bc(O)?.unbounded}),F}const u=n.options?.streamOptimizationMinSize??this.MIN_SIZE_FOR_OPTIMIZATION;if(o.src.length5e3?H=8:c.length>1e3?H=6:c.length>200&&(H=4),H=Math.min(H,O);let R=null;const F=n.options?.streamContextParseStrategy??"chars",P=n.options?.streamContextParseMinChars??200,z=n.options?.streamContextParseMinLines??2;let W;const $=()=>(W===void 0&&(W=Mo(c)),W),K=this.canDirectlyParseAppend(o),ne=K&&this.shouldUseUnboundedAppend(e,o,c);let G=!1;if(!K)switch(F){case"lines":G=$()>=z;break;case"constructs":if(c.length>=P){G=!0;break}if(B1e(c)){G=!0;break}G=$()>=z;break;case"chars":default:G=c.length>=P}if(H>0&&G){const ie=this.getTailLines(o.src,H)+c;try{const _e=this.core.parse(ie,o.env,n).tokens,Z=_e.findIndex(se=>se.map&&typeof se.map[1]=="number"&&se.map[1]>H);if(Z!==-1){const se=_e.slice(Z),he=O-H;he!==0&&this.shiftTokenLines(se,he),R={tokens:se}}}catch{R=null}}else R=null;if(!R){const ie=O;if(ne)R={tokens:D0(n,c,o.env,{mode:"stream"})},ie>0&&this.shiftTokenLines(R.tokens,ie);else{const _e=this.core.parse(c,o.env,n);ie>0&&this.shiftTokenLines(_e.tokens,ie),R=_e}}let te=0;if(o.tokens.length>0&&R.tokens.length>0){const ie=o.tokens[o.tokens.length-1],_e=R.tokens[0];try{ie.type==="inline"&&_e.type==="inline"&&(_e.children&&_e.children.length>0&&(ie.children||(ie.children=[]),this.appendTokens(ie.children,_e.children)),ie.content=(ie.content||"")+(_e.content||""),te=1)}catch{te=0}}const le=o.tokens.length;if(R.tokens.length>te){const ie=o.tokens,_e=R.tokens,Z=Math.min(ie.length,_e.length-te);let se=0;for(let he=Z;he>0;he--){let Y=!0;for(let J=0;J0&&(te+=se),_e.length>te&&this.appendTokens(o.tokens,_e,te)}if(o.src=e,o.globalStateReason=null,o.lineCount=O+(W??$()),o.tokens.length>le){const ie=this.getLastSegment(o.tokens,e,le,o.tokens.length,e.length-c.length,O);ie?o.lastSegment=ie:o.lastSegment=void 0}else o.lastSegment=void 0;return this.stats.total+=1,this.stats.appendHits+=1,ne&&(this.stats.unboundedAppendHits=(this.stats.unboundedAppendHits||0)+1),this.stats.lastMode="append",ts(o.env,{area:"stream",path:ne?"stream-unbounded-append":"stream-append",reason:ne?"large-delta":"safe-append",unbounded:ne}),o.tokens}const d=i??o.env,f=this.tryTailSegmentReparse(e,o,d,n);if(f)return this.stats.total+=1,this.stats.tailHits+=1,this.stats.lastMode="tail",ts(d,{area:"stream",path:"stream-tail",reason:"tail-reparse"}),f;const h=!!n.__explicitStreamChunkFallbackSetting,m=typeof n.__canUseImplicitLargeInputStrategy=="function"?n.__canUseImplicitLargeInputStrategy():!0,g=!!n.options?.streamChunkedFallback,y=!h&&!c&&m,k=g||y,v=n.options?.streamChunkAdaptive!==!1,C=n.options?.streamChunkTargetChunks??8,w=n.options?.streamChunkSizeChars,M=n.options?.streamChunkSizeLines,L=n.options?.streamChunkMaxChunks,E=!!n.__explicitStreamChunkConfig,S=n.options?.autoTuneChunks!==!1,x=n.options?.streamChunkFenceAware??!0;let A=c&&o.lineCount!==void 0?o.lineCount+Mo(c):void 0;if(k){A===void 0&&(A=Mo(e));const O=($,K,ne)=>$ne?ne:$,H=S&&!E?fL(e.length,A,n.options):null,R=H?.maxChunkChars??(v?O(Math.ceil(e.length/C),8e3,64e3):w??1e4),F=H?.maxChunkLines??(v?O(Math.ceil(A/C),150,700):M??200),P=H?.maxChunks??(v?O(Math.ceil(e.length/64e3),C,32):L),z=e.length>0&&e.charCodeAt(e.length-1)===10,W=y&&e.length>=this.IMPLICIT_STREAM_CHUNK_MIN_CHARS&&H?.strategy!=="plain";if((g||W)&&(e.length>=R*2||A>=F*2)&&z){const $=tb(n,e,d,{maxChunkChars:R,maxChunkLines:F,fenceAware:H?.fenceAware??x,maxChunks:P});return this.cache={src:e,tokens:$,env:d,lineCount:A,lastSegment:void 0,globalStateReason:kl(e)},this.updateCacheLineCount(this.cache,A),this.recordChunkedParseResult(d,g?"explicit-fallback-large-doc":"default-fallback-large-doc"),$}}const T=this.parseFullDocument(e,d,n,A),I=T.tokens;return A=T.lineCount,this.cache={src:e,tokens:I,env:d,lineCount:A,lastSegment:void 0,globalStateReason:kl(e)},this.updateCacheLineCount(this.cache,A),this.stats.total+=1,this.stats.fullParses+=1,this.stats.lastMode="full",ts(d,{area:"stream",path:"stream-full",reason:"fallback-full",unbounded:!!Bc(d)?.unbounded}),I}recordChunkedParseResult(e,t){const n=Bc(e)?.chunk,i=n?.fallback?String(n.fallbackReason||"global-state"):null;if(this.stats.total+=1,i){this.stats.fullParses+=1,this.stats.lastMode="full",ts(e,{area:"stream",path:"stream-full",reason:`global-state:${i}`,unbounded:!!Bc(e)?.unbounded});return}this.stats.chunkedParses=(this.stats.chunkedParses||0)+1,this.stats.lastMode="chunked",ts(e,{area:"stream",path:"stream-chunked",chunked:!0,reason:t})}parseFullDocument(e,t,n,i,o=!0){const s=kl(e);u2(t)&&ad(t);const r=typeof n.__canUseImplicitLargeInputStrategy!="function"||n.__canUseImplicitLargeInputStrategy()?PH(n,e.length,i):"no";if(r==="yes"){const a=D0(n,e,t);return ts(t,{area:"stream",path:"stream-full",reason:"auto-unbounded-char-threshold",unbounded:!0}),{tokens:a,lineCount:i??(o?Mo(e):0)}}let l=i;if(r==="need-lines"&&(l=Mo(e),OH(n,e.length,l))){const a=D0(n,e,t);return ts(t,{area:"stream",path:"stream-full",reason:"auto-unbounded-line-threshold",unbounded:!0}),{tokens:a,lineCount:l}}return l===void 0&&(l=o?Mo(e):0),{tokens:im(t,s,()=>this.core.parse(e,t,n).tokens),lineCount:l}}shouldUseUnboundedAppend(e,t,n){return!n||e.length=this.MIN_UNBOUNDED_APPEND_CHARS?!0:Mo(n)>=this.MIN_UNBOUNDED_APPEND_LINES}getAppendedSegment(e,t,n){if(n===null||n===void 0&&!t.startsWith(e)||!e.endsWith(` +`))return null;const i=n??t.slice(e.length);if(!i)return null;const o=i.length;if(i.charCodeAt(o-1)!==10)return null;let s=0,r=-1;for(let a=0;a=2));a++);if(s<2)return null;const l=(r===-1?i:i.slice(0,r)).trim();if(l.length===0)return null;if(/^[-=]+$/.test(l)){const a=e.slice(0,-1),u=a.lastIndexOf(` +`);if(a.slice(u+1).trim().length>0)return null}return this.endsInsideOpenFence(e)||this.mayContainReferenceDefinition(i)?null:i}tryTailSegmentReparse(e,t,n,i){const o=this.ensureLastSegment(t);if(!o||o.srcOffset<=0&&o.tokenStart<=0)return null;const s=t.src.slice(0,o.srcOffset);if(!e.startsWith(s))return null;const r=t.src.slice(o.srcOffset),l=e.slice(o.srcOffset);if(l===r)return null;const a=e.startsWith(t.src)?e.slice(t.src.length):null;if(a){const u=this.tryContainerTailAppendMerge(e,t,n,i,o,a);if(u)return u}if(this.mayContainReferenceDefinition(r)||this.mayContainReferenceDefinition(l))return null;try{const u=this.core.parse(l,n,i),c=this.getLastSegment(u.tokens,l);return o.lineStart>0&&this.shiftTokenLines(u.tokens,o.lineStart),t.src=e,t.env=n,t.globalStateReason=null,t.globalStateCarry=void 0,t.tokens.length=o.tokenStart,this.appendTokens(t.tokens,u.tokens),t.lineCount=o.lineStart+Mo(l),c?t.lastSegment={tokenStart:o.tokenStart+c.tokenStart,tokenEnd:o.tokenStart+c.tokenEnd,lineStart:o.lineStart+c.lineStart,lineEnd:o.lineStart+c.lineEnd,srcOffset:o.srcOffset+c.srcOffset}:t.lastSegment=null,t.tokens}catch{return null}}getTailLines(e,t){if(t<=0)return"";let n=t;for(let i=e.length-1;i>=0;i--)if(e.charCodeAt(i)===10&&(n--,n===0))return e.slice(i+1);return e}endsInsideOpenFence(e){const n=e.length>4e3?e.length-4e3:0,i=e.slice(n),o=i.length;let s=null,r=0;for(;r<=o;){let l=i.indexOf(` +`,r);l===-1&&(l=o);let a=r;for(;a=3&&(s?s.marker===u&&d>=s.length&&(s=null):s={marker:u,length:d})}}if(l===o)break;r=l+1}return s!==null}peek(){return this.cache?.tokens??P1e}getStats(){return{...this.stats}}appendTokens(e,t,n=0,i=t.length){for(let o=n;oK3?n.slice(n.length-K3):n,i&&(e.globalStateReason=i),i}ensureLastSegment(e){return e.lastSegment!==void 0||(e.lastSegment=this.getLastSegment(e.tokens,e.src)),e.lastSegment}getLastSegment(e,t,n=0,i=e.length,o,s){if(i<=n)return null;let r=Number.POSITIVE_INFINITY,l=-1,a=0;for(let u=i-1;u>=n;u--){const c=e[u];if(c.map&&(c.map[0]l&&(l=c.map[1])),c.nesting<0){a+=-c.nesting;continue}if(c.nesting>0){if(a-=c.nesting,c.level===0&&a<=0){const d=Number.isFinite(r)?r:c.map?.[0]??0,f=l>=d?l:c.map?.[1]??d;return{tokenStart:u,tokenEnd:i,lineStart:d,lineEnd:f,srcOffset:this.getLineStartOffset(t,d,o,s)}}continue}if(c.level===0&&a===0){const d=Number.isFinite(r)?r:c.map?.[0]??0,f=l>=d?l:c.map?.[1]??d;return{tokenStart:u,tokenEnd:i,lineStart:d,lineEnd:f,srcOffset:this.getLineStartOffset(t,d,o,s)}}}return null}getLineStartOffset(e,t,n,i){if(n!==void 0&&i!==void 0&&t>=i)return this.getLineStartOffsetFrom(e,n,t-i);if(t<=0)return 0;let o=t,s=-1;for(;o>0;){if(s=e.indexOf(` +`,s+1),s===-1)return e.length;o--}return s+1}getLineStartOffsetFrom(e,t,n){if(n<=0)return t;let i=n,o=t-1;for(;i>0;){if(o=e.indexOf(` +`,o+1),o===-1)return e.length;i--}return o+1}mayContainReferenceDefinition(e){return e.includes("]:")?/(?:^|\n)[ \t]{0,3}\[[^\]\n]+\]:/.test(e):!1}canDirectlyParseAppend(e){if(!this.endsWithBlankLine(e.src))return!1;const t=this.ensureLastSegment(e);if(!t)return!1;switch(e.tokens[t.tokenStart]?.type){case"paragraph_open":case"heading_open":case"fence":case"code_block":case"html_block":case"hr":case"table_open":return!0;default:return!1}}tryContainerTailAppendMerge(e,t,n,i,o,s){if(!s||this.mayContainReferenceDefinition(s))return null;const r=t.tokens[o.tokenStart];switch(r?.type){case"bullet_list_open":case"ordered_list_open":return this.tryListTailAppendMerge(e,t,n,i,o,s,r);case"table_open":return this.tryTableTailAppendMerge(e,t,n,i,o,s,r);default:return null}}tryListTailAppendMerge(e,t,n,i,o,s,r){if(t.src.length===0||t.src.charCodeAt(t.src.length-1)!==10)return null;const l=o.lineEnd-o.lineStart,a=t.src.length-o.srcOffset;if(l0&&this.shiftTokenLines(d,f);const h=this.getListParagraphMode(t.tokens,o.tokenStart,t.tokens.length,r.level),m=this.getListParagraphMode(c,0,c.length,0);(h==="loose"||m==="loose"||this.endsWithBlankLine(t.src)||(c[0]?.map?.[0]??0)>0)&&(this.setListParagraphVisibility(t.tokens,o.tokenStart,t.tokens.length,r.level,!1),this.setListParagraphVisibility(d,0,d.length,r.level,!1)),t.tokens.splice(t.tokens.length-1,0,...d),t.src=e,t.env=n,t.globalStateReason=null;const g=f+Mo(s);t.lineCount=g;const y=this.getDocLineCount(e,g);return r.map&&(r.map[1]=y),t.lastSegment={tokenStart:o.tokenStart,tokenEnd:t.tokens.length,lineStart:o.lineStart,lineEnd:y,srcOffset:o.srcOffset},t.tokens}tryTableTailAppendMerge(e,t,n,i,o,s,r){if(t.src.length===0||t.src.charCodeAt(t.src.length-1)!==10||/(?:^|\n)[ \t]*\n/.test(s))return null;const l=o.lineEnd-o.lineStart,a=t.src.length-o.srcOffset;if(l=0?d.slice(f.tbodyOpenIndex+1,f.tbodyCloseIndex):d.slice(f.tbodyOpenIndex,f.tbodyCloseIndex+1);if(m.length===0)return null;const g=o.lineEnd-2;g!==0&&this.shiftTokenLines(m,g);const y=h.tbodyCloseIndex>=0?h.tbodyCloseIndex:h.tableCloseIndex,k=t.lineCount??Mo(t.src);t.tokens.splice(y,0,...m),t.src=e,t.env=n,t.globalStateReason=null;const v=k+Mo(s);t.lineCount=v;const C=this.getDocLineCount(e,v);if(r.map&&(r.map[1]=C),h.tbodyOpenIndex>=0){const w=t.tokens[h.tbodyOpenIndex];w?.map&&(w.map[1]=C)}return t.lastSegment={tokenStart:o.tokenStart,tokenEnd:t.tokens.length,lineStart:o.lineStart,lineEnd:C,srcOffset:o.srcOffset},t.tokens}getTableHeaderContext(e){const t=e.indexOf(` +`);if(t<0)return null;const n=e.indexOf(` +`,t+1);return n<0?null:e.slice(0,n+1)}getTableBodySection(e,t,n,i){if(t<0||t>=n||e[t]?.type!=="table_open")return null;let o=-1;for(let l=n-1;l>t;l--){const a=e[l];if(a.type==="table_close"&&a.level===i){o=l;break}}if(o<0)return null;let s=-1,r=-1;for(let l=t+1;l=0){for(let l=o-1;l>s;l--){const a=e[l];if(a.type==="tbody_close"&&a.level===i+1){r=l;break}}if(r<0)return null}return{tableCloseIndex:o,tbodyOpenIndex:s,tbodyCloseIndex:r}}isSingleTopLevelContainer(e,t,n,i){if(e.length<2)return!1;const o=e[0],s=e[e.length-1];if(o.type!==t||s.type!==n||o.level!==0||s.level!==0||i!==void 0&&o.markup!==i)return!1;let r=0;for(let l=0;l0&&l0||a.nesting<0)&&(r+=a.nesting)}return r===0}getListParagraphMode(e,t,n,i){let o=!1,s=!1;const r=i+2;for(let l=t;l=0;){const i=e.charCodeAt(n);if(i===32||i===9){n--;continue}return i===10}return!0}getDocLineCount(e,t=Mo(e)){return e.length===0?0:e.charCodeAt(e.length-1)===10?t:t+1}shiftTokenLines(e,t){if(t===0)return;let n=null;for(let i=0;i=0;s--)n.push(o.children[s]);for(;n.length>0;){const s=n.pop();if(s.map&&(s.map[0]+=t,s.map[1]+=t),s.children)for(let r=s.children.length-1;r>=0;r--)n.push(s.children[r])}}}}};const yL={default:T1e,zero:E1e,commonmark:M1e};function H1e(e){return{core:e.core.ruler.version,block:e.block.ruler.version,inline:e.inline.ruler.version,inline2:e.inline.ruler2.version}}function W1e(e,t){return e.core.ruler.version!==t.core||e.block.ruler.version!==t.block||e.inline.ruler.version!==t.inline||e.inline.ruler2.version!==t.inline2}function kL(e){return e.experimental?{...e,...e.experimental}:e}function Ea(e,t){if(!e)return!1;if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0)return!0;const n=e.experimental;return!!n&&Object.prototype.hasOwnProperty.call(n,t)&&n[t]!==void 0}function bL(e,t,n){for(let i=0;i=4?n.quotes=[S[0],S[1],S[2],S[3]]:n.quotes=["“","”","‘","’"]}let r=bL(s?.options,o,["fullChunkSizeChars","fullChunkSizeLines","fullChunkMaxChunks"]),l=bL(s?.options,o,["streamChunkSizeChars","streamChunkSizeLines","streamChunkMaxChunks"]),a=wL(s?.options,o,"fullChunkedFallback"),u=wL(s?.options,o,"streamChunkedFallback"),c=!1,d=null,f=null;const h=new Fpe;let m=null;const g=()=>(m||(m=new O1e(n)),m);let y=null;const k=()=>(y||(y=new j1e(h)),y);let v=null;const C=()=>(v||(v=new Kj({fuzzyLink:!0})),v),w=S=>!c&&!!d&&!W1e(S,d),M=(S,x)=>i==="default"&&!c&&m===null&&f!==null&&S.parse===f&&w(S)&&!S.stream.enabled&&x<(S.options.autoUnboundedThresholdChars??4e6)&&S.options.html===!1&&S.options.xhtmlOut===!1&&S.options.breaks===!1&&S.options.langPrefix==="language-"&&S.options.linkify===!1&&S.options.typographer===!1&&S.options.highlight===null,L=(S,x)=>i==="default"&&!c&&w(S)&&!S.stream.enabled&&!S.options.fullChunkedFallback&&x<(S.options.autoUnboundedThresholdChars??4e6)&&S.options.html===!1&&S.options.linkify===!1&&S.options.typographer===!1,E={core:h,block:h.block,inline:h.inline,get linkify(){const S=C();return Object.defineProperty(this,"linkify",{value:S,writable:!0,configurable:!0}),S},get renderer(){const S=g();return Object.defineProperty(this,"renderer",{value:S,writable:!0,configurable:!0}),S},options:n,__explicitFullChunkConfig:r,__explicitStreamChunkConfig:l,__explicitFullChunkFallbackSetting:a,__explicitStreamChunkFallbackSetting:u,__canUseImplicitLargeInputStrategy(){return w(this)},set(S){const x=kL(S);return this.options={...this.options,...x},(Ea(S,"fullChunkSizeChars")||Ea(S,"fullChunkSizeLines")||Ea(S,"fullChunkMaxChunks"))&&(r=!0,this.__explicitFullChunkConfig=!0),(Ea(S,"streamChunkSizeChars")||Ea(S,"streamChunkSizeLines")||Ea(S,"streamChunkMaxChunks"))&&(l=!0,this.__explicitStreamChunkConfig=!0),Ea(S,"fullChunkedFallback")&&(a=!0,this.__explicitFullChunkFallbackSetting=!0),Ea(S,"streamChunkedFallback")&&(u=!0,this.__explicitStreamChunkFallbackSetting=!0),m&&m.set(x),typeof x.stream=="boolean"&&(this.stream.enabled=x.stream,y&&(y.reset(),y.resetStats())),this},configure(S){const x=typeof S=="string"?yL[S]:S;if(!x)throw new Error("Wrong `markdown-it` preset, can't be empty");if(x.options&&this.set(x.options),x.components){const A=x.components;A.core?.rules&&this.core.ruler.enableOnly(A.core.rules),A.block?.rules&&this.block.ruler.enableOnly(A.block.rules),A.inline?.rules&&this.inline.ruler.enableOnly(A.inline.rules),A.inline2?.rules&&this.inline.ruler2.enableOnly(A.inline2.rules)}return this},enable(S,x){const A=Array.isArray(S)?S:[S],T=[this.core?.ruler,this.block?.ruler,this.inline?.ruler,this.inline?.ruler2],I=new Set;for(const O of T){if(!O)continue;const H=O.enable(A,!0);for(let R=0;R!I.has(H));if(O.length)throw new Error(`Rules manager: invalid rule name ${O.join(", ")}`)}return this},disable(S,x){const A=Array.isArray(S)?S:[S],T=[this.core?.ruler,this.block?.ruler,this.inline?.ruler,this.inline?.ruler2],I=new Set;for(const O of T){if(!O)continue;const H=O.disable(A,!0);for(let R=0;R!I.has(H));if(O.length)throw new Error(`Rules manager: invalid rule name ${O.join(", ")}`)}return this},use(S,...x){const A=typeof S=="function"?S:S&&typeof S.default=="function"?S.default:void 0;if(!A)throw new TypeError("MarkdownIt.use: plugin must be a function");const T=[this,...x],I=S;return c=!0,A.apply(I,T),this},render(S,x){let A;if(M(this,S.length)){x!==void 0&&(Ur(x),A=R3("render"));const O=A?l1():0,H=A?uL(S,A):aL(S);if(A&&(A.attemptMs=l1()-O,H===null&&(A.fallbackReason="unsupported-stock-subset"),Dg(x,A)),H!==null)return x!==void 0&&ts(x,{area:"render",path:"stock-fast",reason:"stock-subset"}),H}const T=x??{},I=this.parse(S,T);return A&&Dg(T,A),g().render(I,this.options,T)},async renderAsync(S,x){let A;if(M(this,S.length)){x!==void 0&&(Ur(x),A=R3("render"));const O=A?l1():0,H=A?uL(S,A):aL(S);if(A&&(A.attemptMs=l1()-O,H===null&&(A.fallbackReason="unsupported-stock-subset"),Dg(x,A)),H!==null)return x!==void 0&&ts(x,{area:"render",path:"stock-fast",reason:"stock-subset"}),H}const T=x??{},I=this.parse(S,T);return A&&Dg(T,A),g().renderAsync(I,this.options,T)},renderIterable(S,x={}){const A=this.parseIterable(S,x);return g().render(A,this.options,x)},async renderAsyncIterable(S,x={}){const A=await this.parseAsyncIterable(S,x);return g().renderAsync(A,this.options,x)},renderInline(S,x={}){const A=this.parseInline(S,x);return g().render(A,this.options,x)},validateLink:AH,normalizeLink:xH,normalizeLinkText:SH,utils:ufe,helpers:{...Yfe},parse(S,x){if(typeof S!="string")throw new TypeError("Input data should be a String");if(x!==void 0&&Ur(x),L(this,S.length)){const O=x===void 0?void 0:R3("parse"),H=O?l1():0,R=Upe(S,O);if(O&&(O.attemptMs=l1()-H,R===null&&(O.fallbackReason="unsupported-stock-subset"),Dg(x,O)),R!==null)return x!==void 0&&ts(x,{area:"parse",path:"stock-fast",reason:"stock-subset"}),R}const A=x??{};let T;if(!this.stream.enabled&&!this.options.fullChunkedFallback&&w(this)){const O=PH(this,S.length);if(O==="yes"){const H=D0(this,S,A);return ts(x,{area:"parse",path:"auto-unbounded",unbounded:!0,reason:"char-threshold"}),H}O==="need-lines"&&(T=Mo(S))}if(!this.stream.enabled){const O=S.length,H=this.options.autoTuneChunks!==!1,R=r,F=!a&&w(this),P=!!this.options.fullChunkedFallback,z=F&&O>=2e5;let W;(P||z||T!==void 0)&&(W=T??Mo(S));const $=(P||z)&&H&&!R?I1e(O,W,this.options):null;if(P||z){const K=W??0;if(P?O>=(this.options.fullChunkThresholdChars??2e4)||K>=(this.options.fullChunkThresholdLines??400):z){if($&&$.strategy!=="plain"){const ne=tb(this,S,A,{maxChunkChars:$.maxChunkChars,maxChunkLines:$.maxChunkLines,fenceAware:$.fenceAware,maxChunks:$.maxChunks});return x&&CL(x,P?"explicit-full-chunk":"default-large-string"),ne}if(P){const ne=(Y,J,U)=>YU?U:Y,G=this.options.fullChunkAdaptive!==!1,te=this.options.fullChunkTargetChunks??8,le=ne(Math.ceil(O/te),8e3,64e3),ie=ne(Math.ceil(K/te),150,700),_e=G?le:this.options.fullChunkSizeChars??1e4,Z=G?ie:this.options.fullChunkSizeLines??200,se=G?ne(Math.ceil(O/64e3),te,32):this.options.fullChunkMaxChunks,he=tb(this,S,A,{maxChunkChars:_e,maxChunkLines:Z,fenceAware:this.options.fullChunkFenceAware??!0,maxChunks:se});return x&&CL(x,"explicit-full-chunk"),he}}}if(T!==void 0&&w(this)&&OH(this,O,W??T)){const K=D0(this,S,A);return ts(x,{area:"parse",path:"auto-unbounded",unbounded:!0,reason:"line-threshold"}),K}}const I=kl(S);return ts(x,{area:"parse",path:"plain",reason:"default-plain"}),im(A,I,()=>h.parse(S,A,this).tokens)},parseIterable(S,x={}){return Ur(x),A1e(this,S,x)},parseAsyncIterable(S,x={}){return Ur(x),x1e(this,S,x)},parseIterableToSink(S,x,A={}){return Ur(A),S1e(this,S,x,A)},parseAsyncIterableToSink(S,x,A={}){return Ur(A),_1e(this,S,x,A)},parseInline(S,x={}){if(typeof S!="string")throw new TypeError("Input data should be a String");Ur(x),u2(x)&&ad(x);const A=h.createState(S,x,this);return A.inlineMode=!0,h.process(A),A.tokens}};if(E.stream={enabled:!!n.stream,parse(S,x){return E.stream.enabled?k().parse(S,x,E):E.parse(S,x??{})},reset(){k().reset()},peek(){return y?y.peek():[]},stats(){return y?y.getStats():{total:0,cacheHits:0,appendHits:0,unboundedAppendHits:0,tailHits:0,fullParses:0,resets:0,chunkedParses:0,lastMode:"idle"}},resetStats(){y&&y.resetStats()}},s?.components){const S=s.components;S.core?.rules&&E.core.ruler.enableOnly(S.core.rules),S.block?.rules&&E.block.ruler.enableOnly(S.block.rules),S.inline?.rules&&E.inline.ruler.enableOnly(S.inline.rules),S.inline2?.rules&&E.inline.ruler2.enableOnly(S.inline2.rules)}return d=H1e(E),f=E.parse,E}var U1e=q1e;const HH=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],V1e=["a","abbr","b","bdi","bdo","button","cite","code","data","del","dfn","em","font","i","ins","kbd","label","mark","q","s","samp","small","span","strong","sub","sup","time","u","var"],WH=["article","aside","blockquote","details","div","figcaption","figure","footer","header","h1","h2","h3","h4","h5","h6","li","main","nav","ol","p","pre","section","summary","table","tbody","td","th","thead","tr","ul"],K1e=["svg","g","path"],Z1e=["address","audio","body","canvas","caption","colgroup","datalist","dd","dialog","dl","dt","fieldset","form","head","hgroup","html","iframe","legend","map","menu","meter","noscript","object","optgroup","option","output","picture","progress","rp","rt","ruby","script","select","style","template","textarea","tfoot","title","video"],G1e=["onclick","onerror","onload","onmouseover","onmouseout","onmousedown","onmouseup","onkeydown","onkeyup","onfocus","onblur","onsubmit","onreset","onchange","onselect","ondblclick","ontouchstart","ontouchend","ontouchmove","ontouchcancel","onwheel","onscroll","oncopy","oncut","onpaste","oninput","oninvalid","onsearch","innerhtml","outerhtml","textcontent","innertext","srcdoc","ping"],Q1e=["action","data","href","src","srcset","poster","xlink:href","formaction"],Y1e=["script"],J1e=["pre","iframe","picture","script","style","table","tbody","td","tfoot","th","thead","textarea","tr","title","video"],Sf=new Set(HH),qH=new Set(WH),Lv=new Set([...HH,...V1e,...WH,...K1e]),UH=new Set([...Lv,...Z1e]),X1e=new Set(G1e),eme=new Set(Q1e),f2=new Set(Y1e),VH=new Set(J1e);function KH(e){let t="";for(const n of e){const i=n.charCodeAt(0);i<=31||i>=127&&i<=159||/\s/u.test(n)||(t+=n)}return t}const tme={amp:"&",bsol:"\\",colon:":",newline:` +`,sol:"/",tab:" "};function ZH(e){return e.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z][a-z0-9]+));?/gi,(t,n,i,o)=>{const s=n??i;if(s){const r=Number.parseInt(s,n?10:16);try{return Number.isFinite(r)?String.fromCodePoint(r):""}catch{return""}}return tme[String(o??"").toLowerCase()]??t})}const _y=new Set(["http","https","mailto","tel"]),nme=new Set(["javascript","vbscript","data","file","ftp","blob","filesystem","intent","chrome","chrome-extension","moz-extension","ms-browser-extension","view-source"]),fh=new Set(["http","https"]);function GH(e){return e.match(/^([a-z][a-z0-9+.-]*):/i)?.[1]?.toLowerCase()??""}const ime=/^https?:\/\//i;function ome(e){if(!ime.test(e))return!1;for(const t of e){const n=t.charCodeAt(0);if(t==="&"||n<=32||n>=127&&n<=159||n>127&&/\s/u.test(t))return!1}return!0}function sme(e,t,n){if(!P0(t,n)||!e.startsWith("file:///"))return!1;const i=e.charAt(8);return i!=="/"&&i!=="\\"}function P0(e,t){return e?(e==="a"||e==="area")&&(!t||t==="href"||t==="xlink:href"):!t||t==="href"}function rme(e,t){return t==="href"||t==="xlink:href"?P0(e,t)?_y:fh:t==="src"||t==="srcset"||t==="poster"||t==="action"||t==="formaction"||t==="data"?fh:(P0(e,t),_y)}function ip(e,t={}){if(ome(e))return!1;const n=KH(ZH(e)).toLowerCase(),i=String(t.tagName??"").toLowerCase(),o=String(t.attrName??"").toLowerCase();if(!n)return!1;if(n.startsWith("data:")){const r=/^data:image\/(?:png|gif|jpe?g|webp|avif|bmp);/i.test(n);return i==="img"&&o==="src"?!r:!0}if(/^[\\/]{2}/.test(n))return!0;if(n.startsWith("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("#")||n.startsWith("?"))return!1;const s=GH(n);return s?s==="file"?!sme(n,i,o):P0(i,o)?nme.has(s):!rme(i,o).has(s):!1}function lme(e){const t=ZH(String(e??"")).trim();if(!t||t.startsWith("#")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../")||t.startsWith("?"))return!1;const n=GH(KH(t).toLowerCase());return n==="http"||n==="https"}function ame(e,t={}){const n=String(e??"").trim();return n?ip(n,t)?"":n:""}function AL(e){return ame(e,{tagName:"img",attrName:"src"})}function ume(e,t,n){function i(f){return f.trim().split(" ",2)[0]===t}function o(f,h,m,g,y){return f[h].nesting===1&&f[h].attrJoin("class",t),y.renderToken(f,h,m,g,y)}n=n||{};const s=3,r=n.marker||":",l=r.charCodeAt(0),a=r.length,u=n.validate||i,c=n.render||o;function d(f,h,m,g){let y,k=!1,v=f.bMarks[h]+f.tShift[h],C=f.eMarks[h];if(l!==f.src.charCodeAt(v))return!1;for(y=v+1;y<=C&&r[(y-v)%a]===f.src[y];y++);const w=Math.floor((y-v)/a);if(w=m||(v=f.bMarks[E]+f.tShift[E],C=f.eMarks[E],v=4)){for(y=v+1;y<=C&&r[(y-v)%a]===f.src[y];y++);if(!(Math.floor((y-v)/a)=2){const r=Number(s[0]),l=Number(s[1]);Number.isFinite(r)&&Number.isFinite(l)&&(o.map=[r+t,Math.min(l+t,n)])}Array.isArray(o.children)&&QH(o.children,t,n)}}function dme(e){["admonition","info","warning","error","tip","danger","note","caution"].forEach(t=>{e.use(ume,t,{render(n,i){return n[i].nesting===1?`
    `:`
    +`}})}),e.block.ruler.before("fence","vmr_container_fallback",(t,n,i,o)=>{const s=t,r=s.bMarks[n]+s.tShift[n],l=s.eMarks[n],a=s.src.slice(r,l),u=a.match(/^:::\s*([^\s{]+)/);if(!u)return!1;const c=u[1];if(!c.trim())return!1;const d=a.slice(u[0].length).trim();let f,h;const m=d.indexOf("{"),g=m>=0?d.slice(m).trimStart():void 0;if(m===-1)f=d||void 0;else{if(f=d.slice(0,m).trim()||void 0,g?.startsWith("{")){let L=0,E=-1;for(let S=0;S0&&(h=g.slice(0,E))}h||(f=d||void 0)}if(o)return!0;const y=!!s.env.__markstreamFinal;let k=n+1,v=!1;for(;k<=i;){const L=s.bMarks[k]+s.tShift[k],E=s.eMarks[k];if(s.src.slice(L,E).trim()===":::"){v=!0;break}k++}v||(k=i);const C=s.push("vmr_container_open","div",1);if(C.attrSet("class",`vmr-container vmr-container-${c}`),C.map=[n,v?k:i],C.meta={...C.meta??{},unclosed:!v&&!y},f&&C.attrSet("data-args",f),h)try{const L=JSON.parse(h);for(const[E,S]of Object.entries(L)){const x=S!=null&&typeof S=="object";C.attrSet(`data-${E}`,x?JSON.stringify(S):String(S))}}catch{const L=cme(h);if(L)for(const[E,S]of Object.entries(L)){const x=S!=null&&typeof S=="object";C.attrSet(`data-${E}`,x?JSON.stringify(S):String(S))}else C.attrSet("data-attrs",h)}const w=[];for(let L=n+1;LL.trim().length>0)){let L=w.join(` +`);L.endsWith(` +`)||(L+=` +`),L.endsWith(` + +`)||(L+=` +`);const E=s.tokens[s.tokens.length-1];E&&(E.raw=L);const S=[];s.md.block.parse(L,s.md,s.env,S),QH(S,n+1,n+1+w.length),s.tokens.push(...S)}const M=s.push("vmr_container_close","div",-1);return v||(M.hidden=!0,M.map=[i,i]),s.line=v?k+1:k,!0},{alt:["paragraph","reference","blockquote","list"]})}function Au(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function No(e){let t=!1,n=!1;for(let i=0;i")return i}return-1}function $4(e){const t=[],n=/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;let i;for(;(i=n.exec(e))!==null;){const o=i[1];if(!o)continue;const s=i[2]||i[3]||i[4]||"";t.push([o,s])}return t}const fme=/^[a-z][a-z0-9_-]*$/;function xL(e){return fme.test(String(e??"").trim().toLowerCase())}function Va(e){const t=String(e??"").trim();if(!t)return"";if(!t.startsWith("<"))return xL(t)?t.toLowerCase():"";let n=1;for(;n]/.test(s)?"":xL(o)?o:""}function Np(e){if(!e||e.length===0)return[];const t=new Set,n=[];for(const i of e){const o=Va(i);!o||t.has(o)||(t.add(o),n.push(o))}return n}function hme(...e){const t=new Set,n=[];for(const i of e)for(const o of Np(i))t.has(o)||(t.add(o),n.push(o));return n}function pme(e){const t=Np(e);return{key:t.join(","),tags:t}}function YH(e){return Va(e)}function mme(e,t){const n=String(e??""),i=Va(t);if(!i)return!1;const o=Au(i),s=n.match(new RegExp(String.raw`^\s*<\s*${o}(?:\s[^>]*)?(\s*\/)?>`,"i"));return s?s[1]?!0:new RegExp(String.raw`<\s*\/\s*${o}\s*>`,"i").test(n):!1}function JH(e,t){const n=Va(t);return!!n&&!Lv.has(n)&&!mme(e,n)}function gme(e,t){const n=String(e??""),i=Va(t);if(!i)return n;const o=Au(i),s=new RegExp(String.raw`^\s*<\s*${o}(?:\s[^>]*)?>\s*`,"i"),r=new RegExp(String.raw`\s*<\s*\/\s*${o}\s*>\s*$`,"i");return n.replace(s,"").replace(r,"")}const XH=Sf,vme=Lv,eW=new Set(qH);eW.delete("details");const yme=/<([A-Z][\w-]*)(?=[\s/>]|$)/gi,kme=/<\/\s*([A-Z][\w-]*)(?=[\s/>]|$)/gi,vA=/^<\s*(?:\/\s*)?([A-Z][\w-]*)/i,bme=/^<\s*([A-Z][\w:-]*)(?=[\s/>]|$)/i;function ib(e){return(e.match(vA)?.[1]??"").toLowerCase()}function kx(e){return/^\s*<\s*\//.test(e)}function bx(e,t){return XH.has(t)||/\/\s*>\s*$/.test(e)}function wme(e,t){let n=0;for(let i=0;i0&&n--;continue}bx(o,s)||n++}}return n}function SL(e,t,n=0){const i=new RegExp(String.raw`<\s*(\/?)\s*${Au(t)}(?=[\s>/])[^>]*>`,"gi");i.lastIndex=Math.max(0,n);let o=0,s;for(;(s=i.exec(e))!==null;){const r=s[0]??"",l=!!s[1],a=!l&&/\/\s*>$/.test(r);if(l){if(o===0)return{start:s.index,end:s.index+r.length};o--;continue}a||o++}return null}function Ame(e,t){const n=new RegExp(String.raw`<\s*(\/?)\s*${Au(t)}(?=[\s>/])[^>]*>`,"gi");let i=0,o;for(;(o=n.exec(e))!==null;){const s=o[0]??"",r=!!o[1],l=!r&&/\/\s*>$/.test(s);if(r){i>0&&i--;continue}l||i++}return i}function ob(e){const t=e;return String(t.raw??t.content??t.markup??"")}function xme(e){const t=e;return t.meta||(t.meta={}),t.meta}function Z3(e,t,n){const i=xme(e);i.markstreamCustomHtmlRaw=t,i.markstreamCustomHtmlInner=n}function Sme(e,t){if(!t.size)return;const n=Array.from(t,h=>new RegExp(String.raw`<\s*${Au(h)}(?=[\s>/])`,"i")),i=[];let o=!1;const s=h=>h?n.some(m=>m.test(h)):!1,r=h=>{if(!(!h||!i.length))for(const m of i)m.raw+=h,m.inner+=h},l=()=>{!i.length||!o||(r(` +`),o=!1)},a=h=>{r(h)},u=h=>{for(let g=0;g{const m=i[i.length-1]?.tag;if(!m)return null;const g=new RegExp(String.raw`^\s*<\s*\/\s*${Au(m)}\s*>`,"i");return h.match(g)?.[0]??null},d=h=>!!c(h),f=(h,m,g)=>{const y=g??(h.type==="html_inline"?ib(m):"");if(!(y&&t.has(y))){r(m);return}const k=kx(m),v=!k&&bx(m,y);if(k){if(!i.length||i[i.length-1].tag!==y){r(m);return}u(m);return}if(r(m),v){Z3(h,m,"");return}i.push({tag:y,token:h,raw:m,inner:""})};for(const h of e){if(h.type==="inline"&&Array.isArray(h.children)){const m=String(h.content??"");if(d(m)?o=!1:l(),!i.length&&!s(m)){o=!1;continue}let g=0,y=!0;for(const k of h.children){const v=ob(k),C=k.type==="html_inline"?ib(v):"",w=C&&t.has(C);let M=v;if(y&&m&&v&&(i.length||w)){const L=m.indexOf(v,g);if(L!==-1)a(m.slice(g,L)),M=m.slice(L,L+v.length),g=L+v.length;else{if(i.length&&!w)continue;y=!1}}f(k,M,C)}y&&m&&g0;continue}if(i.length&&typeof h.content=="string"){const m=ob(h),g=h.type==="html_block"?c(m):null;if(g){u(`${o?` +`:""}${g}`),o=i.length>0;continue}if(!h.content)continue;l(),r(h.content),o=!0}}for(const h of i)Z3(h.token,h.raw,h.inner)}function _me(e){return/^\s*<\s*[!?]/.test(e)}function Ime(e){const t=new Set(vme);if(e&&Array.isArray(e))for(const n of e){const i=String(n??"").trim();if(!i)continue;const o=i.match(/^[<\s/]*([A-Z][\w-]*)/i);o&&t.add(o[1].toLowerCase())}return t}function _L(e,t){if(t.has(e))return!0;for(const n of t)if(n.startsWith(e))return!0;return!1}function Mme(e,t){let n=null;for(const s of e.matchAll(yme)){const r=s.index??-1;if(r<0)continue;const l=(s[1]??"").toLowerCase();_L(l,t)&&No(e.slice(r))===-1&&(!n||r")&&(!n||s")&&(!n||s{const h=f,m=new Set(n),g=Array.isArray(h.env?.__markstreamCustomHtmlTags)?h.env.__markstreamCustomHtmlTags:[];for(const C of g){const w=Va(String(C??""));w&&m.add(w)}const y=Ime(Array.from(m)),k=new Set(Lme);for(const C of m)k.add(C);return{autoCloseInlineTagSet:k,commonHtmlTags:y,customTagSet:m,shouldMergeHtmlBlockTag:C=>m.has(C)||!y.has(C)||eW.has(C)}},o=f=>{if(f.type==="html_block")return String(f.content??"");if(f.type!=="inline"||!Array.isArray(f.children)||f.children.length!==1)return"";const h=f.children[0];return h?.type!=="html_block"?"":String(f.content??h.content??"")},s=(f,h)=>{f.type="html_block",f.content=h,f.raw=h,f.children=[]},r=f=>f.replace(/^(?:\r?\n)+/,""),l=f=>/^(?: {4}|\t)/.test(f),a=f=>f.replace(/^(?: {4}|\t)/gm,""),u=(f,h)=>{const m=r(f);if(!/\S/.test(m))return[];if(l(m))return[{type:"code_block",content:a(m),raw:m}];const g=m.replace(/^[\t ]+/,"");if(!g)return[];if(g.startsWith("<"))return[{type:"html_block",content:g}];const y={type:"inline",tag:"",nesting:0,content:g,children:[{type:"text",content:g,raw:g}]};return h==="paragraph"?[{type:"paragraph_open",tag:"p",nesting:1},y,{type:"paragraph_close",tag:"p",nesting:-1}]:h==="text"?[{type:"text",content:g,raw:g}]:[y]},c=(f,h,m)=>f[h-1]?.type==="paragraph_open"&&f[h+1]?.type==="paragraph_close"?"inline":m,d=(f,h)=>{const m=r(h);return!/\S/.test(m)||f.type!=="inline"||!Array.isArray(f.children)?!1:(f.content=`${String(f.content??"")}${m}`,f.children.push({type:"text",content:m,raw:m}),!0)};e.core.ruler.after("inline","fix_html_inline_streaming",f=>{const h=f.tokens??[],{commonHtmlTags:m,customTagSet:g}=i(f);for(const y of h){const k=y;if(k.type!=="inline"||!Array.isArray(k.children))continue;const v=String(k.content??""),C=k.children.length?k.children:v.includes("<")?[{type:"text",content:v,raw:v}]:null;if(C)try{const w=Eme(C,m);if(k.children=w.children,w.pendingBuffer){const M=v.lastIndexOf(w.pendingBuffer);if(M!==-1){const L=v.slice(0,M);k.content=L,typeof k.raw=="string"&&(k.raw=L)}}}catch(w){console.error("[applyFixHtmlInlineTokens] failed to fix streaming html inline",w)}}Sme(h,g)}),e.core.ruler.push("fix_html_inline_tokens",f=>{const h=f.tokens??[],{autoCloseInlineTagSet:m,customTagSet:g,shouldMergeHtmlBlockTag:y}=i(f),k=[];for(let v=0;v0){const[M,L]=k[k.length-1];if(v!==L){if(C.type==="paragraph_open"||C.type==="paragraph_close"){h.splice(v,1),v--;continue}const E=String(C.content??C.raw??"");if(E){const S=h[L],x=`${String(S.content||"")} +${E}`,A=No(x),T=A===-1?null:SL(x,M,A+1);if(T){const I=x.slice(0,T.end),O=x.slice(T.end);S.content=I,S.loading=!1,h.splice(v,1),k.pop();const H=d(S,O)?[]:u(O,c(h,v,"paragraph"));H.length&&h.splice(v,0,...H),v--;continue}S.content=x,S.loading!==!1&&(S.loading=!0)}h.splice(v,1),v--;continue}}const w=o(C);if(w){if(_me(w))continue;const M=(w.match(/<\s*(?:\/\s*)?([^\s>/]+)/)?.[1]??"").toLowerCase(),L=/^\s*<\s*\//.test(w);if(!M||!y(M))continue;if(s(C,w),!L)M&&!new RegExp(`^\\s*<\\s*${M}\\b[^>]*\\/\\s*>`,"i").test(w)&&Ame(w,M)>0&&k.push([M,v]);else if(k.length>0&&M&&k[k.length-1][0]===M){const[,E]=k[k.length-1],S=h[E];S.content=`${String(S.content||"")} +${w}`,S.loading=!1,k.pop(),h.splice(v,1),v--}continue}else if(k.length>0){if(C.type==="paragraph_open"||C.type==="paragraph_close"){h.splice(v,1),v--;continue}const M=C.content||"",L=new RegExp(`<\\s*\\/\\s*${k[k.length-1][0]}\\s*>`,"i").test(M);if(M){const[,E]=k[k.length-1],S=h[E];S.content=`${S.content||""} +${M}`,S.loading!==!1&&(S.loading=!L)}L&&k.pop(),h.splice(v,1),v--}else continue}if(g.size>0){const v=new Map,C=new Map,w=E=>{let S=v.get(E);return S||(S=new RegExp(`<\\s*${E}\\b`,"i"),v.set(E,S)),S},M=E=>{let S=C.get(E);return S||(S=new RegExp(`<\\s*\\/\\s*${E}\\s*>`,"i"),C.set(E,S)),S},L=[];for(let E=0;E0){const T=L[L.length-1],I=h[T.index],O=S.type==="html_block"?M(T.tag).exec(x):null;if(O){const F=O.index+O[0].length,P=x.slice(0,F),z=x.slice(F);I.content=`${String(I.content??"")} +${P}`,Array.isArray(I.children)&&I.children.push({type:"html_inline",content:``,raw:``}),L.pop();const W=d(I,z)?[]:u(z,c(h,E,"paragraph"));W.length?h.splice(E,1,...W):(h.splice(E,1),E--);continue}if(S.type!=="inline")continue;const H=Array.isArray(S.children)?S.children:[],R=wme(H,T.tag);if(R!==-1){const F=H.slice(0,R+1),P=H.slice(R+1),z=F.map(W=>String(W?.content??W?.raw??"")).join("");if(I.content=`${String(I.content??"")} +${z}`,Array.isArray(I.children)&&I.children.push(...F),P.length){const W=P.map($=>String($.content??$.raw??"")).join("");if(W.trim()){const $=W.replace(/^\s+/,"");if(d(I,W))h.splice(E,1),E--;else if($.startsWith("<"))h.splice(E,1,{type:"html_block",content:$});else{const K=u(W,c(h,E,"paragraph"));h.splice(E,1,...K)}}else h.splice(E,1),E--}else h.splice(E,1),E--;L.pop();continue}I.content=`${String(I.content??"")} +${x}`,Array.isArray(I.children)&&I.children.push(...H),h.splice(E,1),E--;continue}if(S.type!=="inline")continue;const A=Array.isArray(S.children)?S.children:[];for(const T of g)if((A.length?Cme(A,T):w(T).test(x)&&!M(T).test(x)?1:0)>0){L.push({tag:T,index:E});break}}}{let v=0;for(let C=0;C0?v--:(h.splice(C,1),C--))}}for(let v=0;v/]+)/)?.[1]??"").toLowerCase();if(S.startsWith("!")||S.startsWith("?")){C.loading=!1;continue}if(g.has(S)){const R=String(C.content??""),F=No(R),P=F===-1?null:SL(R,S,F+1);C.loading=P?!1:C.loading!==void 0?C.loading:!0;const z=P?.start??-1,W=P?P.end-P.start:0;if(z!==-1){const $=R.slice(0,z+W);let K="";F!==-1&&F]+)))?/g;let A;for(;(A=x.exec(C.content||""))!==null;)A[1],A[2]||A[3]||A[4];const T=String(C.content??""),I=new RegExp(`<\\/\\s*${S}\\s*>`,"i").exec(T),O=I?I.index:-1,H=I?I[0].length:0;if(O!==-1){const R=T.slice(0,O+H),F=(T.slice(O+H)||"").replace(/^\s+/,"");C.children=[{type:"html_block",content:R,tag:S,loading:!1}],C.content=R,C.raw=R,F&&h.splice(v+1,0,F.startsWith("<")?{type:"html_block",content:F}:{type:"text",content:F,raw:F})}else C.children=[{type:"html_block",content:C.content,tag:S,loading:!0}];continue}if(!C||C.type!=="inline")continue;if(C.children.length===2&&C.children[0].type==="html_inline"){const S=(C.children[0].content?.match(/<([^\s>/]+)/)?.[1]??"").toLowerCase(),x=C.children[1],A=String(x?.content??"").match(/^<\s*\/\s*([^\s>]+)/)?.[1]?.toLowerCase()??"";if(x?.type==="html_inline"&&A===S)continue;m.has(S)?(C.children[0].loading=!0,C.children[0].tag=S,C.children.push({type:"html_inline",tag:S,loading:!0,content:``})):C.children=[{type:"html_block",loading:!0,tag:S,content:String(C.children[0]?.content??"")+String(C.children[1]?.content??"")}];continue}else if(C.children.length===3&&C.children[0].type==="html_inline"&&C.children[2].type==="html_inline"){const S=(C.children[0].content?.match(/<([^\s>/]+)/)?.[1]??"").toLowerCase();if(m.has(S))continue;C.children=[{type:"html_block",loading:!1,tag:S,content:C.children.map(x=>x.content).join("")}];continue}if(!C.content?.startsWith("<")||C.children?.length!==1)continue;const w=String(C.content),M=C,L=M.children[0];if(L?.type!=="html_inline"){/^<\s*(?:\/\s*)?[A-Z][\w:-]*\s*$/i.test(w)&&(M.children.length=0);continue}const E=String(L.content??w).match(bme)?.[1]?.toLowerCase()??"";if(E){if(/\/\s*>\s*$/.test(w)||XH.has(E)){M.children=[{type:"html_inline",content:w}];continue}M.children.length=0}}})}function Fme(e){const t=e.trim();return!t||/^&[a-z0-9#]+;/i.test(t)?!1:!!(/^(?:const|let|var|function|class|import|export|if|for|while|return|await|async|yield|try|catch|throw|new|typeof|instanceof|switch|case|break|continue|def|ruby|perl|print|echo|true|false|null|undefined|NaN|Infinity|this)\b/.test(t)||/[a-z_$][\w$]*(?:\.[a-z_$][\w$]*|\['[^']*'\]|\["[^"]*"\]|\[\d+\])*\s*\(/i.test(t)||/[a-z_$][\w$]*(?:\.[a-z_$][\w$]*|\['[^']*'\]|\["[^"]*"\]|\[[\d+\]])+/i.test(t)||/\w+\s*(?:===?|!==?|<=?|>=?|\+\+|--|&&|\|\||\?\.)/.test(t)||/^(?:!!|\+\+|--)\s*\w/.test(t)||/[\w$]+\s*(?:\+=|-=|\*=|\/=|%=|\*\*=|=)/.test(t)||/^(?:https?:\/\/|ftp:\/\/|file:\/\/|\/\/|www\.)/i.test(t)||/`[^`]*\$\{[^}]*\}[^`]*`/.test(t)||/<\/?[A-Z][a-zA-Z0-9]*/.test(t)||/<[a-z][a-z0-9]*\s[^>]+>/.test(t)||/^(["'`]).*\1\s*[;,]?$/.test(t)||/^\[[\s\S]*\]$/.test(t)||/^\{[\s\S]*\}$/.test(t)||/^\(\s*\)$/.test(t)||/[\w$]+(?:\s*[+\-*/%<>=!&|^~:]+\s*[\w$]+|\s*\.\s*[\w$]+)/.test(t)||/=>|->|::/.test(t)||/^@[\w.$]+$/.test(t)||/^(?:0x[0-9a-fA-F]+|0b[01]+|0o[0-7]+|\d+(?:\.\d*)?(?:px|em|rem|%|vh|vw|deg|s|ms)?)$/.test(t)||/^\$[\w$]+\s*[=:]/.test(t)||/\|\s*\w+|\w+\s*\|/.test(t)||/^(?:git|npm|yarn|pnpm|bun|pip|cargo|go|rust|python|node|java|mvn|gradle|docker|kubectl)\s+/.test(t)||/(?:console|window|document|Math|JSON|Date|Array|Object|String|Number|Boolean)\.[a-zA-Z]/.test(t)||/^(?:\/\/|#|\/\*|\*\/|)/.test(t)||/^(?:<<<|<<\s*['"]?\w+['"]?)/.test(t))}function Dme(e,t={}){t.enabled!==!1&&e.core.ruler.after("inline","fix_indented_code_block",n=>{const i=n.tokens??[];for(let o=0;oa.trim().length>0);if(l.length===1&&!Fme(l[0]??"")){const a=l[0]??"",u=s.level??0;i.splice(o,1,{type:"paragraph_open",tag:"p",nesting:1,level:u},{type:"inline",tag:"",nesting:0,level:u,content:a,children:[{type:"text",content:a,level:u+1,raw:a}],block:!0},{type:"paragraph_close",tag:"p",nesting:-1,level:u}),o+=2}}})}const tW=/\.([a-z0-9]{1,15})$/i,Rme=/[_()[\]{}<>]/u,Ome=/^(?:https?:\/\/|ftp:\/\/|mailto:|www\.)/i,Pme=/[?#@]/u,Bme=/[\\/]/u,$me=/^[\p{L}\p{N}./\\-]+$/u,zme=/^[A-Za-z0-9-]{1,63}$/u,jme=/^xn--[a-z0-9-]{2,59}$/i,Hme=/^(?:[A-Z]{1,6}|\d{1,8})$/u,Wme=/^(?=.{1,12}$)[A-Z0-9]+(?:[-.][A-Z0-9]+)*$/iu,qme=/文件名\s*[::]?|附件\s*[::]?|路径\s*[::]?|路徑\s*[::]?|文件列表\s*[::]?|文档列表\s*[::]?|文檔列表\s*[::]?|\bfile\s*names?\b\s*[::]?|\battachments?\b\s*[::]?|\bpaths?\b\s*[::]?|\bfile\s+lists?\b\s*[::]?|\bdocument\s+lists?\b\s*[::]?/iu,Ume=/文件名\s*[::]?|文件\s*[::]?|附件\s*[::]?|档案\s*[::]?|檔案\s*[::]?|文档\s*[::]?|文檔\s*[::]?|资料\s*[::]?|資料\s*[::]?|路径\s*[::]?|路徑\s*[::]?|\bfile\s*name\b\s*[::]?|\battachments?\b\s*[::]?|\bfiles?\b\s*[::]?|\bdocuments?\b\s*[::]?|\bdocs?\b\s*[::]?|\bpaths?\b\s*[::]?/iu,Vme=/股票代码|股票代碼|证券代码|證券代碼|(?:代码|代碼|交易所|后缀|後綴|市场|市場)(?=$|[\s::/|,,、()()])|\btickers?\b|\bsymbols?\b|\bexchanges?\b/iu,Kme=2e3,Zme=512,Gme={},Qme=new Set(["ai","md","py","rs","sh","zip"]),nW=new Set(["as","bj","de","hk","l","ln","ny","pa","sh","ss","sz","t","us"]),Yme=new Set([...nW,"at","ax","cn","co","it","jp","ks","mc","mx","nz","pl","sa","si","to","tw"]),Jme=new Set(["com","dev","io","page","site"]),Xme=new Set(["app","apk","dmg","exe","ipa","lock","log","markdown","webmanifest"]),ege=new Set(["7z","ai","astro","avi","bash","bz2","c","cjs","cpp","cs","csv","doc","docx","fish","flac","gif","go","gz","h","hpp","html","java","jpeg","jpg","js","json","jsx","kt","md","mdx","mjs","mov","mp3","mp4","pdf","php","png","ppt","pptx","ps1","py","rar","rb","rs","sh","sql","svg","swift","svelte","tar","tgz","toml","ts","tsx","txt","vue","wav","webp","xls","xlsx","xml","yaml","yml","zip","zsh"]),jh=new Map;function IL(e,t){if(!e||e.length>Zme)return t;for(jh.set(e,t);jh.size>Kme;){const n=jh.keys().next().value;if(!n)break;jh.delete(n)}return t}function Nv(e){return e?.filename===!0||e?.explicitFilename===!0||e?.marketTicker===!0}function G3(e,t){const n={filename:e?.filename||t?.filename,explicitFilename:e?.explicitFilename||t?.explicitFilename,marketTicker:e?.marketTicker||t?.marketTicker};return Nv(n)?n:void 0}function ML(e,t){if(!Nv(t))return e;const n=e?.__linkifyDemotionContext;return{...e,__linkifyDemotionContext:{filename:n?.filename||t?.filename,explicitFilename:n?.explicitFilename||t?.explicitFilename,marketTicker:n?.marketTicker||t?.marketTicker}}}function TL(e){const t=h2(e);return Nv(t)?t:void 0}function tge(e){return e.replace(/^[\s>*_`[\]((【《"'“‘]+/u,"").replace(/[\s<*_`\]))】》"'.。;;,,、::!?!?]+$/u,"")}function EL(e,t){if(!Nv(t))return;const n=String(e??"").trim().split(/\s+/u).map(tge).filter(Boolean);if(n.length===0)return;const i={};return t?.filename&&n.every(o=>sb(o,{filename:!0,explicitFilename:t.explicitFilename}))&&(i.filename=!0),t?.explicitFilename&&i.filename&&(i.explicitFilename=!0),t?.marketTicker&&n.every(o=>sb(o,{marketTicker:!0}))&&(i.marketTicker=!0),Nv(i)?i:void 0}function qf(e,t=!1){let n;return{options(i){return t||i==null?ML(e,n):ML(e,G3(TL(i),EL(i,n)))},remember(i){const o=TL(i);n=t?G3(n,o):G3(o,EL(i,n))},reset(){n=void 0}}}function LL(e){return zme.test(e)&&!e.startsWith("-")&&!e.endsWith("-")}function nge(e){const t=e.split(".");if(t.length<2)return!1;const n=t[t.length-1]?.toLowerCase()??"";return LL(n)||jme.test(n)?t.every(LL):!1}function iW(e){return Array.from(e).some(t=>t.charCodeAt(0)>127)}function ige(e){return e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split(/[/?#]/,1)[0]??""}function oge(e){return e.split(".").some(t=>t.toLowerCase().startsWith("xn--"))}function oW(e,t,n){const i=ige(t);return iW(e)&&oge(i)&&String(n??"").toLowerCase().includes(i.toLowerCase())}function sge(e){if(!e)return!1;if(e.includes("文件")||e.includes("附件")||e.includes("路径")||e.includes("路徑")||e.includes("文档")||e.includes("文檔")||e.includes("档案")||e.includes("檔案")||e.includes("资料")||e.includes("資料")||e.includes("股票")||e.includes("证券")||e.includes("證券")||e.includes("代码")||e.includes("代碼")||e.includes("交易所")||e.includes("后缀")||e.includes("後綴")||e.includes("市场")||e.includes("市場"))return!0;const t=e.toLowerCase();return t.includes("file")||t.includes("attachment")||t.includes("document")||t.includes("doc")||t.includes("path")||t.includes("ticker")||t.includes("symbol")||t.includes("exchange")}function h2(e){const t=String(e??""),n=jh.get(t);return n?(jh.delete(t),jh.set(t,n),n):sge(t)?IL(t,{explicitFilename:qme.test(t),filename:Ume.test(t),marketTicker:Vme.test(t)}):IL(t,Gme)}function rge(e){return nge(e.split(/[\\/]/)[0]??"")}function lge(e){const t=e.replace(/[^a-z]/gi,"");return t.length>=2&&t===t.toUpperCase()}function age(e){if(Rme.test(e)||!$me.test(e))return!0;if(Bme.test(e))return!rge(e);const t=e.replace(tW,"");return iW(t)?!0:t.split(".").filter(Boolean).some(lge)}function uge(e,t,n){if(!(n?Yme:nW).has(t))return!1;const i=e.slice(0,-(t.length+1));return i===""?e.startsWith("."):(n?Wme:Hme).test(i)}function sb(e,t={}){if(!e||Ome.test(e)||Pme.test(e))return!1;const n=e.match(tW);if(!n)return!1;const i=String(n[1]??"").toLowerCase();return uge(e,i,t.marketTicker===!0)?!0:ege.has(i)?!Qme.has(i)||t.filename?!0:age(e):!!(t.explicitFilename&&Jme.has(i)||t.filename&&Xme.has(i))}const sW=new WeakMap,rW=new WeakSet;function yA(e,t){return sW.set(e,t),e}function cge(e){return sW.get(e)}function dge(e){rW.add(e)}function fge(e){return e===void 0||rW.has(e)}const NL=["!"];function FL(e){return e==="linkify"||e==="autolink"?e:"recovery"}function gl(e){return{type:"text",content:e,raw:e}}function hh(e,t){t===1?e.push({type:"em_open",tag:"em",nesting:1}):t===2?e.push({type:"strong_open",tag:"strong",nesting:1}):t===3&&(e.push({type:"strong_open",tag:"strong",nesting:1}),e.push({type:"em_open",tag:"em",nesting:1}))}function ph(e,t){t===1?e.push({type:"em_close",tag:"em",nesting:-1}):t===2?e.push({type:"strong_close",tag:"strong",nesting:-1}):t===3&&(e.push({type:"em_close",tag:"em",nesting:-1}),e.push({type:"strong_close",tag:"strong",nesting:-1}))}function Ed(e,t,n,i="recovery"){let o="";if(t.includes('"')){const s=t.split('"');t=s[0].trim(),o=s[1].trim()}return yA({type:"link",loading:n,href:t,title:o,text:e,children:[{type:"text",content:e,raw:e}],raw:`[${e}](${t})`},i)}function hge(e,t){if(!(!e||!t)&&(e.href=String(e.href??"")+t,e.text=String(e.text??"")+t,e.raw=`[${e.text}](${e.href})`,Array.isArray(e.children)&&e.children.length)){const n=e.children[e.children.length-1];n?.type==="text"?(n.content=String(n.content??"")+t,n.raw=String(n.raw??"")+t):e.children.push(gl(t))}}function DL(e,t){let n=-1;for(const i of t){const o=e.indexOf(i);o!==-1&&(n===-1||on?.[0]==="href")?.[1];return typeof t=="string"?t:""}function mge(e,t){if(!e)return;e.attrs=Array.isArray(e.attrs)?e.attrs:[];const n=e.attrs.findIndex(i=>i?.[0]==="href");n>=0?e.attrs[n][1]=t:e.attrs.push(["href",t])}function RL(e,t,n){let i="";for(let o=t+1;o{const n=t.tokens??[];for(let i=0;ir.type==="code_inline"),i=new Map;let o=0;for(let r=0;r0&&u?OL(u):-1;if(c!==-1&&u)for(const d of u.slice(c))d==="("?o++:d===")"&&o>0&&o--}a!==-1&&(r=a);continue}if(!(l.type!=="text"||typeof l.content!="string"))for(const a of l.content)a==="("?o++:a===")"&&o>0&&o--}const s=h2(t);for(let r=0;r<=e.length-1;r++){r<0&&(r=0);const l=e[r];if(!l)break;if(l.type==="link_open"&&(l.markup==="linkify"||l.markup==="autolink")){let a=-1;for(let u=r+1;u0){const m=OL(u);m!==-1&&(d===-1||m=g.content.length){h-=g.content.length;continue}if(h<0)break;const y=g.content[h],k=g.content.slice(0,h);let v=g.content.slice(h);for(let M=m+1;M0&&(e.splice(m+1,C),a=m+1);let w=c;if(y==="!"&&f!==-1)w=c.slice(0,f);else if(v){const M=encodeURI(v);if(M&&c.endsWith(M))w=c.slice(0,c.length-M.length);else{const L=y?encodeURI(y):"",E=L?c.indexOf(L):-1;E!==-1&&(w=c.slice(0,E))}}w!==c&&mge(l,w),v&&e.splice(a+1,0,gl(v));break}}}if(!n){if(l?.type==="em_open"&&e[r-1]?.type==="text"&&e[r-1].content?.endsWith("*")){const a=e[r-1].content?.replace(/(\*+)$/,"")||"";e[r-1].content=a,l.type="strong_open",l.tag="strong",l.markup="**";for(let u=r+1;ud[0]==="href")?.[1]||"";if(e[r+3]?.type==="text"){const d=(e[r+3]?.content??"").indexOf(")"),f=d===-1;d===-1&&(c+=e[r+3]?.content?.slice(0,d)||"",e[r+3].content=""),a.push(Ed(u,c,f,"linkify"));const h=e[r+3].content?.replace(/^\)\**/,"");h&&a.push(gl(h)),e.splice(r-4,8,...a)}else a.push(yA({type:"link",loading:!0,href:c,title:"",text:u,children:[{type:"text",content:c,raw:c}],raw:`[${u}](${c})`},"linkify")),e.splice(r-4,7,...a);continue}else if(e[r-1].content==="]("&&e[r-3]?.type==="text"&&e[r-3].content?.endsWith(")"))if(e[r-2]?.type==="strong_open"){const[a,u]=e[r-3].content?.split("[**")||[];e[r+1].content=u||"",e[r-3].content=a||"",e[r-1].content=""}else if(e[r-2]?.type==="em_open"){const[a,u]=e[r-3].content?.split("[*")||[];e[r+1].content=u||"",e[r-3].content=a||"",e[r-1].content=""}else{const[a,u]=e[r-3].content?.split("[")||[];e[r+1].content=u||"",e[r-3].content=a||"",e[r-1].content=""}}if(l.type==="link_close"&&l.nesting===-1&&e[r-2]?.type==="link_open"&&e[r+1]?.type==="text"&&e[r-1]?.type==="text"){const a=e[r-1].content||"",u=e[r-2].attrs||[],c=u.find(k=>k[0]==="href")?.[1]||"",d=u.find(k=>k[0]==="title")?.[1]||"";let f=3,h=2;const m=(e[r-3]?.content||"").match(/^(\*+)$/),g=[];if(m){h+=1;const k=m[1].length;hh(g,k)}if(l.markup!=="linkify"&&e[r+1].type==="text"&&e[r+1]?.content?.startsWith("](")){f+=1;for(let k=r+1;ky[0]==="href")?.[1];e[r+5]?.type==="text"&&e[r+5].content==="."?(f=(g||f)+e[r+5].content,e[r+5].content=""):f=g||f,h+=3}let m=!0;if(l.nesting===-1&&(d=d.replace(/\*+$/,"")),e[r+2]?.type==="text"){const g=(e[r+2]?.content??"").indexOf(")");m=g===-1,g===-1&&(f+=e[r+2]?.content?.slice(0,g)||"",e[r+2].content="")}a.push(Ed(d,f,m)),ph(a,2),e.splice(r-2,h,...a)}if(l.type==="text"&&/\*+\[[^\]]*$/.test(l.content||"")&&e[r+1]?.type==="strong_open"&&e[r+2]?.type==="text"&&e[r+2].content==="]("&&e[r+3]?.type==="link_open"&&e[r+5]?.type==="link_close"&&e[r+6]?.type==="text"&&e[r+6].content===")"&&e[r+7]?.type==="strong_close"){const a=(l.content||"").match(/^(\*+)\[(.*)$/);if(a){const u=(a[2]||"")+a[1];let c=e[r+3]?.attrs?.find(f=>f[0]==="href")?.[1]||"";!c&&e[r+4]?.type==="text"&&(c=e[r+4].content||"");const d=[];hh(d,2),d.push(Ed(u,c,!1)),ph(d,2),e.splice(r,9,...d),r-=d.length-1;continue}}}}if(n)return e;for(let r=0;r{const n=t.tokens??[];for(let i=0;i{const n=t.tokens??[];for(let i=0;i=0&&e[m].type==="text"&&e[m].content==="";)m--;const g=e[m];let y=c+1;for(;y=0&&e[m].type==="text"&&e[m].content==="";)m--;const g=e[m];let y=c+1;for(;y{const n=t;try{const i=Ege(n.tokens??[],!!n.env?.__markstreamFinal,n.src??"");Array.isArray(i)&&(n.tokens=i)}catch(i){console.error("[applyFixTableTokens] failed to fix table tokens",i)}})}function PL(){return[{type:"table_open",tag:"table",attrs:null,map:null,children:null,content:"",markup:"",info:"",level:0,loading:!0,meta:null},{type:"thead_open",tag:"thead",attrs:null,block:!0,level:1,children:null},{type:"tr_open",tag:"tr",attrs:null,block:!0,level:2,children:null}]}function BL(){return[{type:"tr_close",tag:"tr",attrs:null,block:!0,level:2,children:null},{type:"thead_close",tag:"thead",attrs:null,block:!0,level:1,children:null},{type:"table_close",tag:"table",attrs:null,map:null,children:null,content:"",markup:"",info:"",level:0,meta:null}]}function $L(e){return[{type:"th_open",tag:"th",attrs:null,block:!0,level:3,children:null},{type:"inline",tag:"",children:null,content:e,level:4,attrs:null,block:!0},{type:"th_close",tag:"th",attrs:null,block:!0,level:3,children:null}]}function lW(e,t){if(!e.startsWith("|")||e.includes(` +`)||!e.endsWith("|"))return null;const n=e.slice(1).split("|");return n.at(-1)===""&&n.pop(),n.length>0&&n.every(i=>i.trim().length>0)?n:null}function Q3(e){return lW(e)!==null}function aW(e){return/^:?-+:?$/.test(e.trim())}function Sge(e){if(!e.startsWith("|"))return!1;const t=e.slice(1).split("|");return t.at(-1)===""&&t.pop(),t.length>0&&t.every(aW)}function _ge(e){return/^(?:[::]-*|:?-+:?)?$/.test(e.trim())}function Ige(e){if(e==="")return!0;if(!e.startsWith("|"))return!1;const t=e.slice(1).split("|"),n=t.at(-1)??"";return t.slice(0,-1).every(aW)&&_ge(n)}function Mge(e){return e==="|"||e==="|:"}function Tge(e){const t=lW(e);return t!==null&&t.every(n=>!n.includes(":"))}function Ege(e,t=!1,n=""){const i=[...e];if(e.length<3)return i;const o=e.length-2,s=e[o];if(s.type==="inline"){const r=String(s.content??""),l=r.split(` +`)[0]??"",[a="",u="",...c]=r.split(` +`),d=!t&&!r.includes(` +`)&&/\r?\n$/.test(n)&&Q3(r);if(!t&&(r.includes(` +`)&&c.length===0&&Q3(a)&&Ige(u)||d)){const f=l.slice(1,-1).split("|").map(m=>m.trim()).flatMap(m=>$L(m)),h=[...PL(),...f,...BL()];i.splice(o-1,3,...h)}else if(r.includes(` +`)&&c.length===0&&Q3(a)&&Sge(u)){const f=l.slice(1,-1).split("|").map(m=>m.trim()).flatMap(m=>$L(m)),h=[...PL(),...f,...BL()];i.splice(o-1,3,...h)}else r.includes(` +`)&&c.length===0&&Tge(a)&&Mge(u)&&(s.content=r.slice(0,-2),s.children.splice(2,1))}return i}function Lge(e,t,n,i){const o=e.length;if(n==="$$"&&i==="$$"){let u=t;for(;u=0&&e[c]==="\\";)d++,c--;if(d%2===0)return u}u++}return-1}const s=n[n.length-1],r=i;let l=0,a=t;for(;a=0&&e[c]==="\\";)d++,c--;if(d%2===0){if(l===0)return a;l--,a+=r.length;continue}}const u=e[a];if(u==="\\"){a+=2;continue}u===s?l++:u===r[r.length-1]&&l>0&&l--,a++}return-1}var Nge=Lge;const Fge=["boldsymbol","mathbb","mathcal","mathfrak","mathrm","mathit","mathsf","vec","hat","bar","tilde","overline","underline","mathscr","mathnormal","operatorname","mathbf*"],rb=Fge.map(e=>e.replace(/[.*+?^${}()|[\\]"\]/g,"\\$&")).join("|"),Dge=/\\[a-z]+/i,uW="(?:\\\\|\\u0008)",Rge=new RegExp(String.raw`${uW}(?:${rb})\s*\{[^}]+\}`,"i"),Oge=new RegExp(String.raw`(?:${uW})?(?:${rb})\s*\{`,"i"),Pge=/\\(?:text|frac|left|right|times)/,Bge=/(?:^|[^+])\+(?!\+)|[=\-*/^<>]|\\times|\\pm|\\cdot|\\le|\\ge|\\neq/,$ge=/\b[A-Z]{2,}-[A-Z]{2,}\b/i,zge=/[A-Z]+\s*\([^)]+\)/i,jge=/^\(\s*[a-z](?:\s*,\s*[a-z])+\s*\)$/i,Hge=/\b(?:sin|cos|tan|log|ln|exp|sqrt|frac|sum|lim|int|prod)\b/,Wge=/\b\d{4}\/\d{1,2}\/\d{1,2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?\b/,qge={"\b":"\\b","\v":"\\v","\f":"\\f"};function Uge(e){let t="";for(const n of e)t+=qge[n]??n;return t}function Qd(e){if(!e)return!1;const t=Uge(e),n=t.trim();if(Wge.test(n)||n.includes("**"))return!1;if(n.length>2e3)return!0;const i=Dge.test(t),o=Rge.test(t),s=Oge.test(t),r=Pge.test(t),l=/(?:^|[^\w\\])(?:[A-Z]|\\[A-Z]+)_(?:\{[^}]+\}|[A-Z0-9\\])/i.test(t)||/(?:^|[^\w\\])(?:[A-Z]|\\[A-Z]+)\^(?:\{[^}]+\}|[A-Z0-9\\])/i.test(t),a=Bge.test(t)&&!$ge.test(t),u=zge.test(t),c=jge.test(n),d=Hge.test(t),f=/^\([a-z]\)$/i.test(n)||/^(?:[a-z]|pi)$/i.test(n),h=/^(?:[A-Z][a-z]?(?:_\{?\d+\}?|\^\{?\d+\}?)?)+$/.test(n);return i||o||s||r||l||a||u||c||d||f||h}const cW="__markstreamMathPluginApplied",kA=80,dW=2e4,zL=dW+4096;function wx(e){return!!e[cW]}function Vge(e){e[cW]=!0}const fW=["ldots","cdots","quad","in","displaystyle","int_","lim","lim_","ce","pu","end","infty","perp","mid","operatorname","to","rightarrow","leftarrow","math","mathrm","mathit","mathbb","mathcal","mathfrak","implies","alpha","beta","gamma","delta","epsilon","lambda","sum","sum_","prod","sqrt","fbox","boxed","color","rule","edef","fcolorbox","hline","hdashline","cdot","times","pm","le","ge","neq","sin","cos","tan","log","ln","exp","frac","text","left","right"],Kge=["cdot","mathbf{","partial","mu_{"],hW=fW.slice().sort((e,t)=>t.length-e.length).map(e=>e.replace(/[.*+?^${}()|[\\]\\\]/g,"\\$&")).join("|"),pW="[ \r\b\f\v]",Zge=new RegExp(`([^\\\\])(${Kge.map(e=>e).join("|")})+`,"g"),Gge=/span\{([^}]+)\}/,Qge=/\\operatorname\{span\}\{((?:[^{}]|\{[^}]*\})+)\}/,Yge=/(^|[^\\])\\\r?\n/g,Jge=/(^|[^\\])\\$/g,Xge=/[\p{L}\p{M}\p{N}\p{Pe}\p{Pf}'′″‴|‖]/u,e0e=new RegExp(`(${pW})|(${hW})\\b`,"g"),jL=new Map,HL=new Map;function t0e(e){if(!e)return e0e;const t=[...e];t.sort((r,l)=>l.length-r.length);const n=t.join(""),i=jL.get(n);if(i)return i;const o=`(?:${t.map(r=>r.replace(/[.*+?^${}()|[\\]\\"\]/g,"\\$&")).join("|")})`,s=new RegExp(`(${pW})|(${o})\\b`,"g");return jL.set(n,s),s}function n0e(e,t){const n=e?[]:[...t??[]];e||n.sort((l,a)=>a.length-l.length);const i=e?"__default__":n.join(""),o=HL.get(i);if(o)return o;const s=e?[rb,hW].filter(Boolean).join("|"):[n.map(l=>l.replace(/[.*+?^${}()|[\\]\\\]/g,"\\$&")).join("|"),rb].filter(Boolean).join("|"),r=new RegExp(`(^|[^\\\\\\w])(${s})\\s*\\{`,"g");return HL.set(i,r),r}const WL={" ":"t","\r":"r","\b":"b","\f":"f","\v":"v"};function qL(e){const t=/(^|[^\\])(__|\*\*)/g;let n=0;for(;t.exec(e)!==null;)n++;return n}function i0e(e){return e.replace(/(^|[^\\])!+/gu,(t,n)=>{if(n&&Xge.test(n))return t;const i=n?t.slice(n.length):t;return`${n}${"\\!".repeat(i.length)}`})}function UL(e){const t=/(^|[^\\])(__|\*\*)/g;let n,i=null;for(;(n=t.exec(e))!==null;)i={marker:n[2],index:n.index+(n[1]?.length??0)};return i}function Ld(e,t){const n=t?.commands??fW,i=t?.escapeExclamation??!0,o=t?.commands==null,s=t0e(o?void 0:n);let r=e.replace(s,(u,c,d,f,h)=>{if(c!==void 0&&WL[c]!==void 0)return`\\${WL[c]}`;if(d&&n.includes(d)){const m=h&&typeof f=="number"?h[f-1]:void 0;return m==="\\"||m&&/\w/.test(m)?u:`\\${d}`}return u});i&&(r=i0e(r));let l=r;const a=n0e(o,o?void 0:n);return l=l.replace(a,(u,c,d)=>`${c}\\${d}{`),l=l.replace(Gge,"span\\{$1\\}").replace(Qge,"\\operatorname{span}\\{$1\\}"),l=l.replace(Yge,`$1\\\\ +`),l=l.replace(Jge,"$1\\\\"),l=l.replace(Zge,"$1\\$2"),l}function VL(e){const t=e.trim();return!(!Qd(t)||/"[^"\n]{1,80}"\s*:\s*/.test(t)||!(/\\[a-z]+/i.test(t)||/[=+*/^<>]|\\times|\\pm|\\cdot|\\le|\\ge|\\neq/.test(t)||/[_^]/.test(t))&&/\s-\s/.test(t))}function mW(e){const t=[];let n=0;for(;n=n[0]&&t0;){if(e[s]==="\\"&&s+10;){if(e[l]==="\\"&&l+1=0&&e[n]==="\\";)i++,n--;return i%2===1}function bA(e,t){let n=t;for(;n0&&e[i-1]==="$"||i+1=l)break;const u=lb(o,a);if(u){r=Math.max(a+Math.max(1,t.length),u[1]);continue}p2(e,a)||s++,r=a+Math.max(1,t.length)}return s}function Cx(e,t,n){const i=Dv(String(e??""));if(!i.endsWith(t))return-1;const o=i.length-t.length;if(o<=0||!Dv(i.slice(0,o)).trim()||p2(i,o))return-1;const s=mW(i);if(lb(s,o))return-1;const r=KL(i,t,0,o,s);if(t==="$$"){if(r%2===1)return-1}else if(r>KL(i,n,0,o,s))return-1;return o}function Fv(e){return e===" "||e===" "}function Dv(e){let t=e.length;for(;t>0&&Fv(e[t-1]);)t--;return e.slice(0,t)}function ZL(e){let t=0;for(let n=0;n=48&&t<=57}function s0e(e){if(e.length<3)return!1;const t=e[0];if(t!=="-"&&t!=="*"&&t!=="_"&&t!=="=")return!1;let n=0;for(let i=0;i=3}function r0e(e){const t=e.trim();if(!t)return!1;let n=0;t[n]===":"&&n++;let i=0;for(;t[n]==="-";)i++,n++;return i<3?!1:(t[n]===":"&&n++,n===t.length)}function l0e(e){if(!e.includes("|"))return!1;const t=e[0]==="|"?e.slice(1):e;return(t.endsWith("|")?t.slice(0,-1):t).split("|").every(r0e)}function a0e(e){let t=0;if(!GL(e[t]))return!1;for(;GL(e[t]);)t++;return e[t]!=="."&&e[t]!==")"?!1:Fv(e[t+1])}function gW(e){const t=e.trimStart();if(!t||t.startsWith("```")||t.startsWith("~~~")||t.startsWith(":::")||t[0]===">"||t[0]==="<")return!0;if(t[0]==="#"){let n=0;for(;t[n]==="#";)n++;if(n>=1&&n<=6&&Fv(t[n]))return!0}return!!((t[0]==="-"||t[0]==="+"||t[0]==="*")&&Fv(t[1])||a0e(t)||s0e(t)||l0e(t))}function QL(e,t){return e?t?`${e} +${t}`:e:t}function wA(e){const t=String(e??"").trim();return t?Qd(t):!1}function YL(e){let t=0;for(let n=0;nkA){h=!0;break}const g=o[m],y=x1(g,c);if(y!==-1){const k=QL(f,g.slice(0,y));if(!wA(k)){h=!0;break}const v=g.slice(y+c.length),C=v.trim()?`suffix:${YL(v)}`:"nosuffix";return["closed",u,i+l,d,i+m,y,YL(k),C].join(":")}if(gW(g)){h=!0;break}if(f=QL(f,g),f.length>dW){h=!0;break}}if(!h&&wA(f))return["pending",u,i+l,d].join(":")}}return null}function J3(e,t){const n=String(e??"").trim();return!n||!/^\d[\d,.]*\s*[~~-]\s*$/.test(n)?!1:/\d/.test(String(t??""))}function c0e(e){const t=String(e??"").trimStart(),n=t.match(/^\d+(?:,\d{3})*(?:\.\d+)?/);if(!n)return!1;const i=t.slice(n[0].length);return/^\s*(?:[+\-*/^_=<>]|\\[a-z]+)/i.test(i)?!1:i===""||/^[)\s,.!?;:]/.test(i)}function X3(e){const t=String(e??"").trim();return t?/^(?:\.{3,}|…+)$/.test(t):!1}function d0e(e,t){Vge(e);const n=(r,l,a)=>{const u=String(l??"").replace(/^[\t ]+/,"").replace(/[\t ]+$/,"");if(!u)return;const c=r.push("paragraph_open","p",1);c.map=[a,a+1];const d=r.push("inline","",0);d.content=u,d.map=[a,a+1],d.children=[],r.push("paragraph_close","p",-1)},i=(r,l)=>{const a=r,u=!!t?.strictDelimiters,c=!a?.env?.__markstreamFinal,d=(v,C)=>{let w=C;for(;w=3&&(!w||/\s/.test(w))){const M=a.push("text","",0);return M.content=a.src.slice(a.pos,v),a.pos=v,!0}}const f=[["$$","$$"],["$","$"],["\\(","\\)"]],h=String(a.pending??""),m=Math.max(0,a.pos-h.length);let g=m,y=m;const k=m;for(const[v,C]of f){const w=a.src,M=mW(w),L=o0e(w,c);let E=!1;v==="$$"&&g!==k&&(g=k);let S=-1,x=-1,A=0;const T=I=>{if((I==="undefined"||I==null)&&(I=""),I==="\\"){a.pos=a.pos+I.length,g=a.pos;return}if(I==="\\)"||I==="\\("){const R=a.push("text_special","",0);R.content=I==="\\)"?")":"(",R.markup=I,a.pos=a.pos+I.length,g=a.pos;return}if(!I)return;if(v==="$$"&&I.includes("$")){let R=0;for(;R0&&I[F-1]==="$"||F+10){const P=I.slice(0,O),z=a.push("text","",0);z.content=P,a.pos=a.pos+P.length,g=a.pos}const R=I.slice(O).match(/^!\[([^\]]*)\]\(([^)]+)\)/);if(R){const[,P,z]=R,W=z.match(/^(\S+)(?:\s+"([^"]+)")?\s*$/),$=W?W[1]:z,K=W&&W[2]?W[2]:null,ne=a.push("image","img",0);ne.attrs=[["src",$],["alt",P]],K&&ne.attrs.push(["title",K]),ne.content=P,ne.children=[{type:"text",content:P,tag:""}],a.pos=a.pos+R[0].length,g=a.pos;const G=I.slice(O+R[0].length);G&&T(G);return}const F=a.push("text","",0);F.content=I,a.pos=a.pos+I.length,g=a.pos;return}const H=a.push("text","",0);H.content=I,a.pos=a.pos+I.length,g=a.pos};for(;!(g>=w.length);){const I=w.indexOf(v,g);if(I===-1)break;if(p2(w,I)){g=I+Math.max(1,v.length);continue}const O=lb(M,I);if(O){g=O[1];continue}const H=lb(L,I);if(H){g=H[1];continue}if(I===S&&g===x){if(A++,A>2){g=I+Math.max(1,v.length);continue}}else A=0,S=I,x=g;if(v==="("&&I>0){let G=I-1;for(;G>=0&&w[G]===" ";)G--;if(G>=0&&w[G]==="]"){g=I+v.length;continue}}if(v==="$"&&I>0&&w[I-1]==="$"){g=I+1;continue}if(v==="$"&&I=w.length);){const O=bA(w,I);if(O===-1)break;if(O+10&&w[O-1]==="$"){I=O+1;continue}const H=Y3(w,O+1);if(H===-1)break;const R=w.slice(O+1,H),F=R.includes("`"),P=!R||!R.trim(),z=w[H+1],W=J3(R,z),$=X3(R);if(!F&&!P&&!W&&!$){const K=w.slice(g,O);K&&T(K);const ne=a.push("math_inline","math",0);ne.content=Ld(R,t),ne.markup="$",ne.raw=`$${R}$`,ne.loading=!1,g=H+1,I=H+1}else T("$"),I=O+1}I{const c=r,d=!c?.env?.__markstreamFinal,f=t?.strictDelimiters,h=f?[["\\[","\\]"],["$$","$$"]]:[["\\[","\\]"],["[","]"],["$$","$$"]],m=c.bMarks[l]+c.tShift[l];let g=c.src.slice(m,c.eMarks[l]).trim(),y=!1,k="",v="",C=!1,w="",M=!1;for(const[K,ne]of h)if(g.startsWith(K))if(K.includes("[")){const G=K==="\\["?g.slice(K.length):"";if(K==="\\["&&x1(G,ne)===-1&&!/^\s*!\[/.test(G)&&!G.includes("`")&&Qd(G)){y=!0,k=K,v=ne;break}if(t?.strictDelimiters){if(g.replace("\\","")==="["){if(l+1=0?"\\]":v,A=S>=0?S:x1(g,v,E);if(!C&&A>k.length){const K=g.slice(L+k.length,A),ne=c.push("math_block","math",0);ne.content=Ld(K),ne.markup=k==="$$"?"$$":k==="["?"[]":"\\[\\]",ne.map=[l,l+1],ne.raw=`${k}${K}${x}`,ne.block=!0,ne.loading=!1,c.line=l+1;const G=g.slice(A+x.length);return G.trim()&&n(c,G,l),!0}let T=l,I="",O=!1,H="",R=l;const F=C?g:g===k?"":g.slice(k.length),P=!f&&k==="\\["?"]":"",z=x1(F,v);if(z!==-1){const K=z;I=F.slice(0,K),H=F.slice(K+v.length),R=C?l+1:l,O=!0,T=R}else for(F&&!C&&(I=F),T=l+1;T{const c=r,d=c.bMarks[l]+c.tShift[l],f=c.src.slice(d,c.eMarks[l]).trim();return!f.startsWith("$$")&&!f.startsWith("\\[")?!1:o(r,l,a,u)};e.inline.ruler.before("escape","math",i),e.block.ruler.before("lheading","explicit_math_block",s,{alt:["paragraph","reference","blockquote","list"]}),e.block.ruler.before("paragraph","math_block",o,{alt:["paragraph","reference","blockquote","list"]})}function f0e(e){const t=e.renderer.rules.image||function(n,i,o,s,r){const l=n,a=r;return a.renderToken?a.renderToken(l,i,o):""};e.renderer.rules.image=(n,i,o,s,r)=>{const l=n;return l[i].attrSet?.("loading","lazy"),t(l,i,o,s,r)},e.renderer.rules.fence=e.renderer.rules.fence||((n,i)=>{const o=n[i],s=String(o.info??"").trim();return`
    ${e.utils.escapeHtml(String(o.content??""))}
    `})}const h0e=/^\s]/i,p0e=/^<\/a\s*>/i;function m0e(e,t){if(e?.type!=="inline")return!1;const n=e.children;if(!Array.isArray(n)||n.length===0)return t.test(String(e.content??""));let i=0;for(let o=n.length-1;o>=0;o--){const s=n[o];if(s?.type==="link_close"){for(o--;o>=0&&n[o]?.level!==s.level&&n[o]?.type!=="link_open";)o--;continue}if(s?.type==="html_inline"){const r=String(s.content??"");h0e.test(r)&&i>0&&i--,p0e.test(r)&&i++}if(!(i>0)&&s?.type==="text"&&t.test(String(s.content??"")))return!0}return!1}function g0e(e){const t=e.core?.ruler,n=t.getNamedRules?.().find(i=>i.name==="linkify")?.fn;typeof n=="function"&&t.at("linkify",i=>{if(!i.md?.options?.linkify)return;const o=Array.isArray(i.tokens)?i.tokens:[],s=i.md.linkify;if(!s)return;const r=o.filter(l=>m0e(l,s));if(r.length)return n(Object.assign(Object.create(Object.getPrototypeOf(i)),i,{tokens:r}))})}function v0e(e){const t=e.inline.ruler,n=t.getNamedRules?.(),i=n?.find(l=>l.name==="link")?.fn,o=n?.find(l=>l.name==="image")?.fn;if(typeof i!="function"||typeof o!="function")return;const s=e.validateLink,r=e;r.__markstreamOriginalValidateLink=s,t.at("link",(...l)=>{const a=l[0].md,u=a?.validateLink===s?a.options?.validateLink:a?.validateLink;if(!a||typeof u!="function")return i(...l);const c=a.validateLink;a.validateLink=u;try{return i(...l)}finally{a.validateLink=c}}),t.at("image",(...l)=>{const a=l[0].md;if(!a)return o(...l);const u=a.validateLink;a.validateLink=s;try{return o(...l)}finally{a.validateLink=u}})}function y0e(e={}){const t=e.markdownItOptions??{},n=typeof t.experimental=="object"&&t.experimental!==null?t.experimental:{},i=Object.prototype.hasOwnProperty.call(t,"stream")?!!t.stream:!0,o=Object.prototype.hasOwnProperty.call(t,"validateLink"),s=new U1e({html:!0,linkify:!0,typographer:!0,...t,experimental:{stream:i,...n}});if(!o){const r=l=>!ip(l,{tagName:"a",attrName:"href"});dge(r),s.set({validateLink:r})}return v0e(s),g0e(s),(e.enableMath??!0)&&d0e(s,{...e.mathOptions??{}}),(e.enableContainers??!0)&&dme(s),e.enableFixIndentedCodeBlock!==!1&&Dme(s),gge(s),bge(s),yge(s),xge(s),f0e(s),Nme(s,{customHtmlTags:e.customHtmlTags}),s}function op(e){const t=Object.assign(Object.create(Object.getPrototypeOf(e)),e);return Array.isArray(e.attrs)&&(t.attrs=e.attrs.map(n=>[...n])),Array.isArray(e.map)&&(t.map=[...e.map]),Array.isArray(e.children)&&(t.children=e.children.map(n=>op(n))),t}function k0e(e){const t=e.meta??{};return{type:"checkbox",checked:t.checked===!0,raw:t.checked?"[x]":"[ ]"}}function b0e(e){const t=e,n=t.attrGet?t.attrGet("checked"):void 0,i=n===""||n==="true";return{type:"checkbox_input",checked:i,raw:i?"[x]":"[ ]"}}function w0e(e){const t=String(e.content??"");return{type:"emoji",name:t,markup:String(e.markup??""),raw:`:${t}:`}}function Iy(e,t,n){const i=[];let o="",s=t+1;const r=[];for(;sn.startsWith(t)||t.startsWith(n)):!1}function JL(e,t,n,i){n.length>0&&e.push(...n),i.length>0&&t.push(...i),n.length=0,i.length=0}function XL(e,t){return!t&&e.startsWith(" ")&&!e.startsWith(" ")?` ${e}`:e}function S0e(e,t){const n=[],i=[],o=[],s=[],r=e.split(A0e),l=/\r?\n$/.test(e),a=r.some(h=>h.startsWith("diff ")||h.startsWith("--- ")||h.startsWith("+++ ")||h.startsWith("@@ ")),u=h=>{const m=h;if(!kW.some(g=>m.startsWith(g)))if(m.startsWith("-")){const g=m.slice(1);o.push(XL(g,a))}else if(m.startsWith("+")){const g=m.slice(1);s.push(XL(g,a))}else{JL(n,i,o,s);const g=a&&m.startsWith(" ")?m.slice(1):m;n.push(g),i.push(g)}},c=l?Math.max(0,r.length-1):r.length;for(let h=0;h0||s.length>0)&&JL(n,i,o,s);const d=n.join(` +`),f=i.join(` +`);return{original:t&&l&&d?`${d} +`:d,updated:t&&l&&f?`${f} +`:f}}function Ax(e){const t=Array.isArray(e.map)&&e.map.length===2,n=e.meta??{},i=typeof n.closed=="boolean"?n.closed:void 0,o=i===!0||i!==!1&&t,s=String(e.info??""),r=s.startsWith("diff"),l=r?(()=>{const u=s,c=u.indexOf(" ");return c===-1?"":String(u.slice(c+1)??"")})():s;let a=String(e.content??"");if(!o&&e.markup){const u=e.markup[0],c=e.markup.length,d=C0e(u,c);d.test(a)&&(a=a.replace(d,""))}if(r){const{original:u,updated:c}=S0e(a,o===!0);return{type:"code_block",language:l,code:String(c??""),raw:String(a??""),diff:r,loading:i===!0?!1:i===!1?!0:!t,originalCode:u,updatedCode:c}}return{type:"code_block",language:l,code:String(a??""),raw:String(a??""),diff:r,loading:i===!0?!1:i===!1?!0:!t}}function _0e(e){const t=e.meta??{};return{type:"footnote_reference",id:String(t.label??""),raw:`[^${String(t.label??"")}]`}}function I0e(){return{type:"hardbreak",raw:`\\ +`}}function M0e(e,t,n){const i=[];let o="",s=t+1;const r=[];for(;s\s*$/.test(t)||Sf.has(e)}function T0e(e){if(!e||e.length===0)return eN();const t=t8.get(e);if(t)return t;const n=e.map(Va).filter(Boolean);if(!n.length){const o=eN();return t8.set(e,o),o}const i={customTagSet:new Set(n),allowedTagSet:W4({customHtmlTags:e})};return t8.set(e,i),i}function AW(e){const t=e,n=t.raw??t.content??t.markup??"";return String(n??"")}function E0e(e){const t=e.meta,n=t?.markstreamCustomHtmlRaw,i=t?.markstreamCustomHtmlInner;return typeof n=="string"&&typeof i=="string"?{raw:n,inner:i}:null}function ab(e,t){const n=t.toLowerCase();for(let i=e.length-1;i>=0;i--){const[o,s]=e[i];if(String(o).toLowerCase()===n)return s}}function L0e(e,t,n){const i=e.slice();return ab(i,"href")||i.push(["href",t]),n!=null&&!ab(i,"title")&&i.push(["title",n]),i}function CA(e){return e.map(AW).join("")}function R9(e){const t=[],n=i=>{const o=String(i??"");if(!o)return;const s=t[t.length-1];if(s?.type==="text"){s.content=`${s.content}${o}`,s.raw=`${s.raw}${o}`;return}t.push({type:"text",content:o,raw:o})};for(const i of e)if(i){if(i.type==="reference"||i.type==="footnote_reference"){n(String(i.raw??""));continue}if("children"in i&&Array.isArray(i.children)){t.push({...i,children:R9(i.children)});continue}t.push(i)}return t}function N0e(e,t,n){let i=0;for(let o=t;o`;g.toLowerCase().includes(M.toLowerCase())||(g+=M),k=!0,y=!0}const v=[],C=/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;let w;for(;(w=C.exec(l))!==null;){const M=w[1],L=w[2]||w[3]||w[4]||"";v.push([M,L])}if(u?.has(a)){const M=E0e(e);return[{type:a,tag:a,attrs:v,content:M?M.inner:h.innerTokens.length?CA(h.innerTokens):"",children:h.innerTokens.length?i(h.innerTokens,o,s,r):[],raw:M?.raw??g,loading:e.loading||y,autoClosed:k},h.nextIndex]}return[{type:"html_inline",tag:a,attrs:v,content:g,children:m,raw:g,loading:y,autoClosed:k},h.nextIndex]}function xW(e){if(e.type==="math_inline"){if(e.raw)return String(e.raw);const t=e.markup==="$$"?"$$":"$";return`${t}${String(e.content??"")}${t}`}return Array.isArray(e.children)&&e.children.length>0?e.children.map(t=>xW(t)).join(""):String(e.content??"")}function D0e(e){return!e||!Array.isArray(e.children)||e.children.length===0?"":e.children.map(t=>xW(t)).join("")}function tN(e,t=!1){let n=e.attrs??[],i=null;if((!n||n.length===0)&&Array.isArray(e.children))for(const d of e.children){const f=d.attrs;if(Array.isArray(f)&&f.length>0){n=f,i=d;break}}const o=String(n.find(d=>d[0]==="src")?.[1]??""),s=n.find(d=>d[0]==="alt")?.[1],r=D0e(i??e);let l="";r?l=r:s!=null&&String(s).length>0?l=String(s):i?.content!=null&&String(i.content).length>0?l=String(i.content):Array.isArray(i?.children)&&i.children[0]?.content?l=String(i.children[0].content):Array.isArray(e.children)&&e.children[0]?.content?l=String(e.children[0].content):e.content!=null&&String(e.content).length>0&&(l=String(e.content));const a=n.find(d=>d[0]==="title")?.[1]??null,u=a===null?null:String(a),c=String(e.content??"");return{type:"image",src:o,alt:l,title:u,raw:c,loading:t}}function R0e(e){const t=String(e.content??"");return{type:"inline_code",code:t,raw:t}}function O0e(e,t,n){const i=[];let o="",s=t+1;const r=[];for(;s=0;i--){const[o,s]=e[i];if(String(o).toLowerCase()===n)return s}}function B0e(e,t,n){const i=e.slice();return ub(i,"href")||i.push(["href",t]),n!=null&&!ub(i,"title")&&i.push(["title",n]),i}function My(e,t,n){const i=e[t],o=P0e(i.attrs),s=String(ub(o,"href")??""),r=ub(o,"title"),l=r==null?null:String(r),a=B0e(o,s,l);let u=t+1;const c=[];let d=!0;for(;uy.type==="strong_open")){const y=String(h.content??""),k=String(h.raw??y),v=op(h);v.content=y.slice(0,-2),v.raw=k.replace(/\*\*$/,""),f=c.slice(),f[f.length-1]=v}const m=bo(f,void 0,void 0,n),g=m.map(y=>{const k=y;return"content"in y?String(k.content??""):String(k.raw??"")}).join("");return{node:{type:"link",href:s,title:l,text:g,children:m,raw:`[${g}](${s}${l?` "${l}"`:""})`,loading:d,attrs:a},nextIndex:u0?i:[{type:"text",content:a,raw:a}],raw:`~${a}~`},nextIndex:s0?i:[{type:"text",content:o||String(e[t].content??""),raw:o||String(e[t].content??"")}],raw:`^${o||String(e[t].content??"")}^`},nextIndex:s?@[\\\]^_`{|}~]/,Y0e=/\p{P}/u,J0e=/^[\x22\x27《「『【〔〖〘〚〈([{“‘﹁﹃﹙﹛﹝]$/u,X0e=/^[\x22\x27》」』】〕〗〙〛〉)]}”’﹂﹄﹚﹜﹞]$/u,eve=/^(?:https?:\/\/|mailto:|ftp:\/\/)/i,tve=/:\/\//,AA=1,SW=2,nve=4,ive=8,_W=16,Bd=32,O9=64,r0=128,IW=256,ove=512,l0=1024,sve=1982;function Ty(e){let t=0;for(let n=0;n=t){n++,i++;continue}n++,i++;continue}if(o==="*"&&n>=t)return n;n++}return-1}function _f(e){return!!e&&G0e.test(e)}function If(e){return!!e&&(Q0e.test(e)||Y0e.test(e))}function TW(e,t){return!!e&&!!t&&/^\p{Script=Han}$/u.test(t)&&J0e.test(e)}function EW(e,t){return!!e&&!!t&&/^[\p{L}\p{N}]$/u.test(t)&&X0e.test(e)}function lve(e,t){const n=t>0?e[t-1]:void 0,i=e[t+1];return!i||_f(i)?!1:!(If(i)&&!TW(i,n)&&n&&!_f(n)&&!If(n))}function ave(e,t){const n=t>0?e[t-1]:void 0,i=e[t+1];return!n||_f(n)?!1:!(If(n)&&!EW(n,i)&&i&&!_f(i)&&!If(i))}function uve(e,t,n=0){let i=n,o=!1;for(;i0?e[t-1]:void 0,i=e[t+2];return!i||_f(i)?!1:!(If(i)&&!TW(i,n)&&n&&!_f(n)&&!If(n))}function dve(e,t){const n=t>0?e[t-1]:void 0,i=e[t+2];return!n||_f(n)?!1:!(If(n)&&!EW(n,i)&&i&&!_f(i)&&!If(i))}function fve(e,t=0){let n=t,i=!1;for(;n=0&&e[s]==="\\";s--)o++;return o%2===1}const gve=/[\p{L}\p{N}]/u,vve=/^[\p{L}\p{N}]+$/u;function xA(e){return e?gve.test(e):!1}function LW(e){return e?vve.test(e):!1}function B0(e,t){let n=t;for(;n0?e[t-1]:void 0,o=n=2&&i.intraword&&t.push({start:n,end:o}),n=o}for(let n=0;n=3)return i;n=i+o.len}return-1}function wve(e){return e?eve.test(e)||tve.test(e):!1}function Cve(e,t){if(!e||!t)return null;const n=e.match(/\[([^\]\n]+)\]\(([^)]*)$/);return n&&n[2]===t?n[1]:null}function bo(e,t,n,i){if(!e||e.length===0)return[];const o=i?.__linkifyDemotionContext,s=h2(t),r={filename:o?.filename||s.filename,explicitFilename:o?.explicitFilename||s.explicitFilename,marketTicker:o?.marketTicker||s.marketTicker};(r.filename||r.explicitFilename||r.marketTicker)&&(i={...i,__linkifyDemotionContext:r});const l=i,a=[];let u=null,c=0;const d=i?.requireClosingStrong,f=e;function h(){return e===f&&(e=e.slice()),e}function m(){u=null}function g(Y,J){const U=e.length===1?t:String(J.content??""),Q=[],ue=yve(Y);if(ue!==-1){M(Y.slice(0,ue),Y.slice(0,ue));const pe=Y.slice(ue);return pe&&(T({type:"text",content:pe,raw:pe}),c--),c++,!0}if(U0e.test(Y)){const pe=Y.indexOf("~~");pe!==-1&&Q.push({type:"strikethrough",index:pe})}if(V0e.test(Y)){const pe=Y.indexOf("**");pe!==-1&&Q.push({type:"strong",index:pe})}if(/[^*]*\*[^*]+/.test(Y)){const pe=U?MW(U,0):Y.indexOf("*");if(U&&pe===-1)return!1;pe!==-1&&Q.push({type:"emphasis",index:pe})}Q.sort((pe,ee)=>pe.index!==ee.index?pe.index-ee.index:pe.type===ee.type?0:pe.type==="strong"?-1:ee.type==="strong"?1:0);const me=Q[0];if(!me)return!1;if(me.type==="strikethrough"){const pe=me.index,ee=pe>-1?Y.slice(0,pe):"";if(ee&&M(ee,ee),pe===-1)return c++,!0;const re=Y.indexOf("~~",pe+2),ge=re===-1?Y.slice(pe+2):Y.slice(pe+2,re),ae=re===-1?"":Y.slice(re+2),{node:Ce}=iN([{type:"s_open",tag:"s",content:"",markup:"~~",info:"",meta:null},{type:"text",tag:"",content:ge,markup:"",info:"",meta:null},{type:"s_close",tag:"s",content:"",markup:"~~",info:"",meta:null}],0,i);return m(),w(Ce),ae&&(T({type:"text",content:ae,raw:ae}),c--),c++,!0}if(me.type==="strong"){const pe=me.index,ee=pe>-1?Y.slice(0,pe):"";if(ee&&M(ee,ee),pe===-1)return c++,!0;if(t&&pe===0){let ce=!1,Te=0;for(;Te=2)return M(Y,Y),c++,!0}}if(t&&(Y.match(/\*/g)||[]).length>rve(t))return M(Y.slice(ee.length),Y.slice(ee.length)),c++,!0;const re=B0(Y,pe);if(re.len>=3){const ce=bve(Y,pe+re.len);if(ce!==-1){const Te=Y.slice(pe+re.len,ce);if(kve(Te)){const{node:ke}=Rg([{type:"strong_open",tag:"strong",content:"",markup:"**",info:"",meta:null},{type:"em_open",tag:"em",content:"",markup:"*",info:"",meta:null},{type:"text",tag:"",content:Te,markup:"",info:"",meta:null},{type:"em_close",tag:"em",content:"",markup:"*",info:"",meta:null},{type:"strong_close",tag:"strong",content:"",markup:"**",info:"",meta:null}],0,t,i);m(),w(ke);const Ae=Y.slice(ce+3);return Ae&&(T({type:"text",content:Ae,raw:Ae}),c--),c++,!0}}}if(!cve(Y,pe)){const ce=Y.slice(pe,pe+re.len);M(ce,ce);const Te=Y.slice(pe+re.len);return Te&&(T({type:"text",content:Te,raw:Te}),c--),c++,!0}const ge=fve(Y,pe+2);let ae="",Ce="";if(ge.index!==-1){ae=Y.slice(pe+2,ge.index),Ce=Y.slice(ge.index+2);const ce=ge.index,Te=B0(Y,ce);if(re.intraword&&Te.intraword&&!LW(ae)||!ae&&re.len>=4&&re.intraword)return M(Y.slice(ee.length),Y.slice(ee.length)),c++,!0}else{if(d||ge.sawInvalidClose||re.intraword)return M(Y.slice(ee.length),Y.slice(ee.length)),c++,!0;ae=Y.slice(pe+2),Ce=""}if(!ae&&/^\*+$/.test(Ce))return M(Y,Y),c++,!0;const{node:ve}=Rg([{type:"strong_open",tag:"strong",content:"",markup:"**",info:"",meta:null},{type:"text",tag:"",content:ae,markup:"",info:"",meta:null},{type:"strong_close",tag:"strong",content:"",markup:"**",info:"",meta:null}],0,t,i);return m(),w(ve),Ce&&(T({type:"text",content:Ce,raw:Ce}),c--),c++,!0}if(me.type==="emphasis"){let pe=me.index;pe===-1&&(pe=0);const ee=Y.slice(0,pe);if(ee&&M(ee,ee),!lve(Y,pe)){M(Y[pe],Y[pe]);const ce=Y.slice(pe+1);return ce&&(T({type:"text",content:ce,raw:ce}),c--),c++,!0}const re=B0(Y,pe),ge=uve(U,Y,pe+1),ae=ge.index,Ce=e[c+1];if(i?.final&&Ce?.type==="em_open"&&ae!==-1&&Y.slice(pe+1,ae).trim()!==Y.slice(pe+1,ae)||ae===-1&&(ge.sawInvalidClose||i?.final||re.intraword||!xA(Y[pe+1])))return M(Y.slice(pe),Y.slice(pe)),c++,!0;const{node:ve}=Iy([{type:"em_open",tag:"em",content:"",markup:"*",info:"",meta:null},{type:"text",tag:"",content:ae>-1?Y.slice(pe+1,ae):Y.slice(pe+1),markup:"",info:"",meta:null},{type:"em_close",tag:"em",content:"",markup:"*",info:"",meta:null}],0,i);if(m(),w(ve),ae!==-1&&ae{for(let ve=0;ve=0&&Ce[Te]==="\\";Te--)ce++;if(ce%2===0)return ve}return-1})(Y);if(Q===-1)return!1;let ue=1;for(let Ce=Q+1;Ceme?.type==="math_inline")||!K0e.test(Y))return null;const U=J.parseInline(Y,{__markstreamFinal:!!i?.final});if(!Array.isArray(U)||U.length===0)return null;const Q=(U.find(me=>me?.type==="inline")?.children??[]).filter(me=>!(me?.type==="text"&&String(me.content??"")===""));if(!Q.length||!Q.some(me=>me?.type!=="text")||Q.length===1&&Q[0]?.type==="text"&&String(Q[0].content??"")===Y)return null;const ue=bo(Q,Y,n,i);return ue.length?ue:null}function v(Y){m(),a.push(Y)}function C(Y){m();const J=op(Y);a.push(J)}function w(Y){v(Y)}function M(Y,J){u?(u.content+=Y,u.raw+=J??Y):(u={type:"text",content:String(Y??""),raw:String(J??Y??"")},a.push(u))}function L(Y,J){if(!Y)return;const U=bo([{...J,type:"text",content:Y,raw:Y}],Y,n,i);if(U.length===1&&U[0]?.type==="text"){const Q=U[0];M(String(Q.content??""),String(Q.raw??Q.content??""));return}for(const Q of U)w(Q)}function E(Y,J){return String(Y.markup??"").startsWith(J)}function S(Y){if(!u||Y.loading!==!0||Y.markup!=="\\(\\)")return;const J=e[c-1];!J||J.type!=="text"||!E(J,"\\(")||u.content.endsWith("(")&&(u.content=u.content.slice(0,-1),u.raw.endsWith("(")&&(u.raw=u.raw.slice(0,-1)),!u.content&&a[a.length-1]===u&&(a.pop(),u=null))}function x(Y){return Y.endsWith("](")?e[c+1]?.type==="link_open"&&e[c+1]?.markup==="linkify"&&e[c+2]?.type==="text"&&e[c+3]?.type==="link_close"&&e[c+4]?.type==="text"&&String(e[c+4]?.content??"").startsWith(")"):!1}function A(Y,J,U=Ty(Y)){let Q=Y;const ue=String(J.content??"");return(U&AA)!==0&&Q.endsWith("\\")&&!E(J,"\\\\")&&!ue.endsWith("\\\\")&&(Q=Q.slice(0,-1)),(U&l0)!==0&&Q.endsWith("(")&&!E(J,"\\(")&&!ue.endsWith("\\(")&&(Q=Q.slice(0,-1)),(U&SW)!==0&&/\*+$/.test(Q)&&!E(J,"\\*")&&!ue.endsWith("\\*")&&(Q=Q.replace(/\*+$/,"")),Q}for(;c=0;ce--){const Te=a[ce];if(Te.type!=="text")break;re=ce,ge=String(Te.content??"")+ge}rere==="href")?.[1],ee=String(pe??"");if(t&&ee){const re=t.indexOf("](");if(re!==-1){const ge=t.indexOf(")",re+2);ge===-1?U.loading=!0:U.loading&&t.slice(re+2,ge).includes(ee)&&(U.loading=!1)}}/^file:\/\/\/[a-z]:\//i.test(U.href)&&$(U,J-1)||P(U)||v(U)}function R(Y){if(Y.markup!=="linkify")return!1;const{node:J,nextIndex:U}=My(e,c,i);return W(J,U)?(c=U,!0):!1}function F(Y){m(),w($0e(Y)),c++}function P(Y){if(Y.type!=="link")return!1;const J=a[a.length-1];if(!J||J.type!=="text")return!1;const U=String(J.content??"").match(/^([^[]*)\[([^\]\n]+)\]\($/);if(!U)return!1;const Q=Y,ue=String(Q.href??""),me=String(Q.text??""),pe=String(U[2]??""),ee=ue.replace(/^(?:https?:\/\/|mailto:|ftp:\/\/)/i,"");if(!ue||!(me===ue||me===ee||wve(me)))return!1;const re=String(U[1]??"");return re?(J.content=re,J.raw=re):a.pop(),v({...Y,text:pe,children:[{type:"text",content:pe,raw:pe}],raw:`[${pe}](${ue}${Q.title?` "${Q.title}"`:""})`}),!0}function z(Y){if(Y.type!=="link")return!1;const J=Y,U=String(J.href??"");return U?W({href:U,title:J.title==null||J.title===""?null:String(J.title),loading:!!J.loading},c+1):!1}function W(Y,J){const U=a[a.length-1];if(U?.type!=="image"||U.src||!U.loading||!String(U.raw??"").endsWith("]("))return!1;const Q=e[J],ue=String(Q?.content??"");if(Q?.type!=="text"||!ue.startsWith(")"))return!1;a.pop(),u=null;const me=String(U.alt??"");v({type:"image",src:Y.href,alt:me,title:Y.title,raw:`![${me}](${Y.href}${Y.title?` "${Y.title}"`:""})`,loading:!!Y.loading});const pe=ue.slice(1),ee=op(Q);return ee.content=pe,ee.raw=pe,h()[J]=ee,!0}function $(Y,J=c-1){if(Y.type!=="link")return!1;const U=a[a.length-1],Q=e[J];if(!U||U.type!=="text"||Q?.type!=="text")return!1;const ue=String(U.content??""),me=String(Q.content??"");if(!ue.endsWith("!")||!me.endsWith("!")||E(Q,"\\!"))return!1;const pe=ue.slice(0,-1);pe?(U.content=pe,U.raw=pe,u=U):(a.pop(),u=null);const ee=Y,re=String(ee.text??ee.children?.map(Ce=>String(Ce?.content??Ce?.raw??"")).join("")??""),ge=String(ee.href??""),ae=ee.title==null||ee.title===""?null:String(ee.title);return v({type:"image",src:ge,alt:re,title:ae,raw:`![${re}](${ge}${ae?` "${ae}"`:""})`,loading:!!ee.loading}),!0}function K(Y,J="",U=null){const Q=String(Y.alt??Y.raw??"");return{type:"link",href:J,title:U,text:Q,children:[Y],raw:`[${Q}](${J}${U?` "${U}"`:""})`,loading:!0}}function ne(Y){const J=Y.startsWith("![")?Y:`![${Y}`,U=J.slice(2),Q=U.indexOf("](");return{type:"image",src:"",alt:Q===-1?U.replace(/\]$/,""):U.slice(0,Q),title:null,raw:J,loading:!0}}function G(Y){const J=Y.indexOf("[![");if(J===-1||typeof t=="string"&&e.length===1&&mve(t,J,"["))return!1;const U=Y.slice(0,J);return U&&M(U,U),v(K(ne(Y.slice(J+1)))),c++,!0}function te(Y){if(i?.final)return!1;const J=e[c-1];if(J?.type!=="text"||!String(J.content??"").endsWith("[")||E(J,"\\["))return!1;const U=a[a.length-1];if(U?.type==="text"&&U.content.endsWith("[")){const Q=U.content.slice(0,-1);Q?(U.content=Q,U.raw=Q,u=U):(a.pop(),u=null)}return v(K(tN(Y))),c++,!0}function le(Y){if(Y.type!=="link")return!1;const J=Y,U=String(J.raw??""),Q=String(J.text??"");if(!U.startsWith("[![")&&!Q.startsWith("!["))return!1;const ue=J.title==null||J.title===""?null:String(J.title);return v(K({type:"image",src:String(J.href??""),alt:Q.replace(/^!\[/,"").replace(/\]$/,""),title:ue,raw:U.startsWith("[![")?U.slice(1):U,loading:!0})),!0}function ie(Y){if(!Y.startsWith("]("))return!1;const J=e[c-2];if(J?.type==="text"&&String(J.content??"").endsWith("[")&&E(J,"\\["))return!1;const U=a[a.length-1];if(U?.type!=="image"&&U?.type!=="link")return!1;const Q=U,ue=U?.type==="link"&&Array.isArray(Q.children)&&Q.children.length===1&&Q.children[0]?.type==="image"?a.pop():null,me=ue?ue.children[0]:a.pop();if(!me||me.type!=="image")return!1;const pe=e[c+1];let ee=String(ue?.href??""),re=ue?.title==null?null:String(ue.title),ge=!0;if(pe?.type==="link_open"){const{node:Ce,nextIndex:ve}=My(e,c+1,i);ee=Ce.href,re=Ce.title,ge=!0,c=ve}else{if(ee=Y.slice(2),ee.includes('"')){const Ce=ee.split('"');ee=String(Ce[0]??"").trim(),re=Ce[1]==null?null:String(Ce[1]).trim()}c++}const ae=K(me,ee,re);return ae.loading=ge,v(ae),!0}function _e(){const Y=e[c-3];return e[c-2]?.type==="image"&&e[c-1]?.type==="text"&&String(e[c-1].content??"")==="]("&&Y?.type==="text"&&String(Y.content??"").endsWith("[")&&E(Y,"\\[")}function Z(Y,J){const U=Y.indexOf("[");if(U===-1)return!1;let Q=Y.slice(0,U);const ue=Y.indexOf("](",U);if(ue!==-1){const me=e[c+2];let pe=Y.slice(U+1,ue);if(pe.includes("[")){const ce=pe.indexOf("[");Q+=Y.slice(0,U+ce+1);const Te=U+ce+1;pe=Y.slice(Te+1,ue)}const ee=e[c+1];if(Y.endsWith("](")&&ee?.type==="link_open"&&me){const ce=e[c+4];let Te=4,ke=!0;if(ce?.type==="text"){const Ne=String(ce.content??"");if(Ne.startsWith(")")){ke=!1;const Ze=Ne.slice(1);if(Ze){const rt=op(ce);rt.content=Ze,rt.raw=Ze,h()[c+4]=rt}else Te++}else Ne==="."&&Te++}L(Q,J);const Ae=String(me.content??"");return i?.validateLink&&!i.validateLink(Ae)?M(pe,pe):v({type:"link",href:Ae,title:null,text:pe,children:[{type:"text",content:pe,raw:pe}],loading:ke}),c+=Te,!0}const re=Y.indexOf(")",ue),ge=re!==-1?Y.slice(ue+2,re):"",ae=re===-1;let Ce=Q.match(/\*+$/);if(Ce&&(Q=Q.replace(/\*+$/,"")),L(Q,J),Ce||(Ce=pe.match(/^\*+/)),!d&&Ce){const ce=Ce[0].length;pe=pe.replace(/^\*+/,"").replace(/\*+$/,"");const Te=[];if(ce===1?Te.push({type:"em_open",tag:"em",nesting:1}):ce===2?Te.push({type:"strong_open",tag:"strong",nesting:1}):ce===3&&(Te.push({type:"strong_open",tag:"strong",nesting:1}),Te.push({type:"em_open",tag:"em",nesting:1})),Te.push({type:"link",href:ge,title:null,text:pe,children:[{type:"text",content:pe,raw:pe}],loading:ae}),ce===1){Te.push({type:"em_close",tag:"em",nesting:-1});const{node:ke}=Iy(Te,0,i);w(ke)}else if(ce===2){Te.push({type:"strong_close",tag:"strong",nesting:-1});const{node:ke}=Rg(Te,0,void 0,i);w(ke)}else if(ce===3){Te.push({type:"em_close",tag:"em",nesting:-1}),Te.push({type:"strong_close",tag:"strong",nesting:-1});const{node:ke}=Rg(Te,0,void 0,i);w(ke)}else{const{node:ke}=Iy(Te,0,i);w(ke)}}else i?.validateLink&&!i.validateLink(ge)?M(pe,pe):v({type:"link",href:ge,title:null,text:pe,children:[{type:"text",content:pe,raw:pe}],loading:ae});const ve=re!==-1?Y.slice(re+1):"";return ve&&(T({type:"text",content:ve,raw:ve}),c--),c++,!0}return!1}function se(Y){const J=Y.indexOf("![");if(J===-1)return!1;const U=Y.slice(0,J);return U&&!u?u={type:"text",content:U,raw:U}:U&&u&&(u.content+=U),u&&(a.push(u),u=null),v(ne(Y.slice(J))),c++,!0}function he(Y){if(!(Y?.startsWith("[")&&n?.type==="list_item_open"))return!1;const J=Y.slice(1).match(/[^\s\]]/);if(J===null)return c++,!0;if(J&&/x/i.test(J[0])){const U=J[0]==="x"||J[0]==="X";return v({type:"checkbox_input",checked:U,raw:U?"[x]":"[ ]"}),c++,!0}return!1}return a}function Sx(e,t,n){const i=n?.__sourceLineMapper;if(!i)return{startLine:e,endLine:t};const o=i(e),s=t>e?i(t-1).endLine:i(t).startLine;return{startLine:o.startLine,endLine:Math.max(o.startLine,s)}}function oN(e,t){const n=Math.max(0,Math.min(e.length,Math.trunc(t)));let i=0;for(let o=0;oi&&e[o-1]!==` +`&&r++,{startLine:s,endLine:r}}function Rv(e,t,n,i){const o=Ave(e,t,n);return Sx(o.startLine,o.endLine,i)}function xve(e,t){const n=e?.map;if(!Array.isArray(n)||n.length<2)return null;const i=Number(n[0]),o=Number(n[1]);return!Number.isFinite(i)||!Number.isFinite(o)?null:Sx(i,o,t)}function bi(e,t,n){if(!n?.includeSourceMap)return e;const i=xve(t,n);if(!i)return e;if(e.sourceMap=i,e.type==="code_block"){const o=e;o.startLine=i.startLine,o.endLine=i.endLine}return e}function Sve(e,t,n,i){if(!i?.includeSourceMap)return e;const o=t?.map;if(!Array.isArray(o)||o.length<2)return e;const s=Number(o[0]),r=Number(o[1]),l=Number(n);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(l)||(e.sourceMap=Sx(s,Math.max(r,l),i)),e}function _ve(e){const t=String(e.content??""),n=t.replace(/[ \t\r\n]+$/g,"");if(n===t)return;e.content=n;const i=e.children;if(!(!Array.isArray(i)||i.length===0))for(;i.length;){const o=i[i.length-1];if(!o){i.pop();continue}if(o.type==="softbreak"||o.type==="hardbreak"){i.pop();continue}if(o.type==="text"){const s=String(o.content??""),r=s.replace(/[ \t\r\n]+$/g,"");if(r===s)break;if(r){o.content=r;break}i.pop();continue}break}}function Ive(e){const t=String(e.content??""),n=t.match(/\r?\n\s*\d+[.)]?\s*$/);if(!n||typeof n.index!="number")return;e.content=t.slice(0,n.index);const i=e.children;if(!(!Array.isArray(i)||i.length===0))for(;i.length;){const o=i[i.length-1];if(!o){i.pop();continue}if(o.type==="softbreak"||o.type==="hardbreak"){i.pop();continue}if(o.type==="text"){const s=String(o.content??"");if(/^[ \t\r\n\d.)]*$/.test(s)){i.pop();continue}const r=s.replace(/[ \t\r\n\d.)]+$/g,"");r!==s&&(r?o.content=r:i.pop())}break}}function Mve(e){const t=String(e.content??"");return/[ \t\r\n]+$/.test(t)||/\r?\n\s*\d+[.)]?\s*$/.test(t)}function Gm(e,t,n){const i=e[t],o=[],s=qf(n,!0);let r=t+1;for(;rd.raw).join("")};n?.includeSourceMap&&bi(c,e[r],n),o.push(c),r=u+1}else r+=1;const l={type:"list",ordered:i.type==="ordered_list_open",start:(()=>{if(i.attrs&&i.attrs.length){const a=i.attrs.find(u=>u[0]==="start");if(a){const u=Number(a[1]);return Number.isFinite(u)&&u!==0?u:1}}})(),items:o,raw:o.map(a=>a.raw).join(` +`)};return n?.includeSourceMap&&bi(l,i,n),[l,r+1]}function Tve(e,t,n,i){const o=String(n[1]??"note"),s=String(n[2]??o.charAt(0).toUpperCase()+o.slice(1)),r=[],l=qf(i,!0);let a=t+1;for(;au.raw).join(` +`)} +:::`},a+1]}const Eve=new Set(["warning","info","note","tip","danger","caution"]);function Lve(e){let t=0;for(;t=0;g--){const y=f[g];if(y.type==="text"&&/:+/.test(y.content)){h=g;break}}const m={type:"paragraph",children:bo((h!==-1?f.slice(0,h):f)||[],void 0,void 0,a.options()),raw:String(d.content??"").replace(/\n:+$/,"").replace(/\n\s*:::\s*$/,"")};n?.includeSourceMap&&bi(m,e[u],n),l.push(m),a.remember(m.raw)}u+=3}else if(e[u].type==="bullet_list_open"||e[u].type==="ordered_list_open"){const[d,f]=Gm(e,u,a.options());n?.includeSourceMap&&bi(d,e[u],n),l.push(d),a.remember(d.raw),u=f}else if(e[u].type==="blockquote_open"){const[d,f]=Qm(e,u,a.options());n?.includeSourceMap&&bi(d,e[u],n),l.push(d),a.remember(d.raw),u=f}else{const d=z4(e,u,a.options());d?(l.push(d[0]),a.remember(d[0].raw),u=d[1]):u++}return[{type:"admonition",kind:o,title:s,children:l,raw:`:::${o} ${s} +${l.map(d=>d.raw).join(` +`)} +:::`},u+1]}const Fve=/^::: ?(warning|info|note|tip|danger|caution|error) ?(.*)$/;function Dve(e,t,n){const i=e[t];if(i.type!=="container_open")return null;const o=Fve.exec(String(i.info??""));return o?Tve(e,t,o,n):null}const _x={parseContainer:(e,t,n)=>Nve(e,t,n),matchAdmonition:Dve};function Qm(e,t,n){const i=[],o=qf(n,!0);let s=t+1;for(;sl.raw).join(` +`)};return n?.includeSourceMap&&bi(r,e[t],n),[r,s+1]}function Rve(e){if(e.info?.startsWith("diff"))return Ax(e);const t=String(e.content??""),n=t.match(/ type="application\/vnd\.ant\.([^"]+)"/);let i=t;n?.[1]&&(i=t.replace(/]*>/g,"").replace(/<\/antArtifact>/g,""));const o=Array.isArray(e.map)&&e.map.length===2;return{type:"code_block",language:n?n[1]:String(e.info??""),code:i,raw:i,loading:!o}}function Ove(e,t,n){const i=[];let o=t+1,s=[],r=[];const l=qf(n,!0);for(;ou.raw).join("")),o+=3}else if(e[o].type==="dd_open"){let a=o+1;for(r=[];a0&&(i.push({type:"definition_item",term:s,definition:r,raw:`${s.map(u=>u.raw).join("")}: ${r.map(u=>u.raw).join(` +`)}`}),s=[]),o=a+1}else o++;return[{type:"definition_list",items:i,raw:i.map(a=>a.raw).join(` +`)},o+1]}function Pve(e,t,n){const i=e[t].meta??{},o=String(i?.label??"0"),s=[],r=qf(n,!0);let l=t+1;for(;la.raw).join(` +`)}`},l+1]}function Bve(e,t,n){const i=e[t],o=i.attrs,s=Array.isArray(o)&&o.length?Object.fromEntries(o.filter(c=>Array.isArray(c)&&c.length>=1&&c[0]).map(([c,d])=>[String(c),d==null||d===""?!0:String(d)])):void 0,r=String(i.tag?.substring(1)??"1"),l=Number.parseInt(r,10),a=e[t+1],u=String(a.content??"");return{type:"heading",level:l,text:u,...s?{attrs:s}:{},children:bo(a.children||[],u,void 0,n),raw:u}}function $ve(e,t,n){const i=t.toLowerCase(),o=new RegExp(String.raw`^<\s*${i}(?=\s|>|/)`,"i"),s=new RegExp(String.raw`^<\s*\/\s*${i}(?=\s|>)`,"i");let r=0,l=Math.max(0,n);for(;l$/.test(d)||r++,l=a+c+1;continue}l=a+1}return-1}function NW(e){const t=String(e.content??"");if(/^\s*");else if(a)a=!y.includes(">");else if(u)u=!y.includes("?>");else if(y.startsWith("");else if(y.startsWith("");else if(y.startsWith("");else{const k=o(y);if(k)if(k.closing){for(let v=r.length-1;v>=0;v--)if(r[v]===k.tag){r.length=v;break}}else k.selfClosing||s(k.after,k.tag)||r.push(k.tag)}}if(d===-1||d>=t)break;c=d+1}return l||a||u||r.length>0}function x2e(e,t,n){if(!n?.length)return!1;const i=new Set(Np(n));if(!i.size)return!1;const o=c=>{const d=c.charCodeAt(0);return d>=65&&d<=90||d>=97&&d<=122||d>=48&&d<=57||c==="_"||c==="-"||c===":"},s=c=>c===" "||c===" ",r=c=>{if(c[0]!=="<")return null;let d=1;for(;d"&&g!=="/")return null;const y=c.indexOf(">",d);if(y===-1)return null;let k=y-1;for(;k>=0&&s(c[k]);)k--;return{closing:f,tag:m,selfClosing:!f&&c[k]==="/",after:c.slice(y+1)}},l=(c,d)=>{const f=c.toLowerCase();let h=0;for(;h")return!0}}return!1},a=[];let u=0;for(;u=t?t:c,f=e.slice(u,d),h=f.endsWith("\r")?f.slice(0,-1):f,m=Ym(h);if(m){const g=r(h.slice(m.index));if(g)if(g.closing){for(let y=a.length-1;y>=0;y--)if(a[y]===g.tag){a.length=y;break}}else g.selfClosing||l(g.after,g.tag)||a.push(g.tag)}if(c===-1||c>=t)break;u=c+1}return a.length>0}function S2e(e,t){const n=t2e.exec(e);if(!n)return null;const i=n[1]??"",o=n.index+i.length,s=e.indexOf(` +`,o),r=e.slice(o,s===-1?e.length:s);return!Ym(r.endsWith("\r")?r.slice(0,-1):r)||HW(e,o)||A2e(e,o)||x2e(e,o,t)?null:`${e.slice(0,n.index)}${i}`}function Fx(e,t,n){let i=t;for(;ii&&(r=!0),t.inMath=!1,t.mathOpenOffset=null,s+=2;continue}s++;continue}if(t.inDollarMath){if(e.startsWith("$$",s)&&!Qu(e,l)){i!=null&&o&&n+s+2>i&&(r=!0),t.inDollarMath=!1,t.dollarMathOpenOffset=null,s+=2;continue}s++;continue}if(e[s]==="`"&&!Qu(e,l)){const a=Fx(e,s,"`"),u=WW(e,s+a,a);if(u===-1)break;s=u+a;continue}if(e.startsWith("\\[",s)&&!Qu(e,l)){t.inMath=!0,t.mathOpenOffset=n+s,s+=2;continue}if(e.startsWith("$$",s)&&!Qu(e,l)){t.inDollarMath=!0,t.dollarMathOpenOffset=n+s,s+=2;continue}s++}return r}function _2e(e,t){if(!wx(t))return e;const n=t,i=uN.get(n),o=i?.source===e?i.state:i&&e.startsWith(i.source)?qW(i.state,e.slice(i.source.length),i.source.length-i.state.lineBuffer.length).state:H4(e).state;uN.set(n,{source:e,state:o});const{context:s}=o,r=s.inMath?s.mathOpenOffset:s.inDollarMath?s.dollarMathOpenOffset:null;if(r==null)return e;const l=e.slice(r+2),a=e.lastIndexOf(` +`,r-1)+1;if(e.slice(a,r).trim()!==""&&!/^\r?\n/.test(l)||/^\s*!\[/.test(l))return e;const u=l.trim(),c=/^(?:[a-z]|pi)$/i.test(u);return Qd(l)&&!c?e:e.slice(0,r)}function I2e(e,t,n,i,o){const s=Tx(e),r=Ex(e);if(t.inFence&&t.fenceInBlockquote&&e.trim()&&Lx(e)==null&&l8(t),t.inFence&&t.fenceInList&&e.trim()&&s.column=t.fenceLen&&/^\s*$/.test(l.rest)&&l8(t):(t.inFence=!0,t.fenceChar=l.markerChar,t.fenceLen=l.markerLen,t.fenceInBlockquote=l.inBlockquote,t.fenceInList=l.inList||t.listContentIndent!=null&&!l.inBlockquote&&s.column>=t.listContentIndent,t.fenceListIndent=l.listIndent||t.listContentIndent||0);else if(!t.inFence)return hN(e,t,n,i,o)}else return hN(e,t,n,i,o);return!1}function H4(e,t=y2e(),n=null,i=!1,o=0){const s=z0(t);let r=z0(t),l="",a=!1,u=0;for(;uu&&e[c-1]==="\r"?c-1:d?c:e.length,h=e.slice(u,f);I2e(h,s,o+u,n,i)&&(a=!0),d?(r=z0(s),l=""):l=h,u=d?c+1:e.length}return{closedOpenMath:a,state:{committedContext:r,context:s,lineBuffer:l}}}function qW(e,t,n=0){return t&&!e.context.inMath&&!e.context.inDollarMath&&!e.context.inFence&&!e.committedContext.inFence&&!/[\\$`~\r\n]/.test(t)&&!(e.lineBuffer.endsWith("\\")&&(t[0]==="["||t[0]==="]"))?{closedOpenMath:!1,state:{committedContext:z0(e.committedContext),context:z0(e.context),lineBuffer:e.lineBuffer+t}}:H4(e.lineBuffer+t,e.committedContext,n+e.lineBuffer.length,e.context.inMath||e.context.inDollarMath,n)}function M2e(e,t){if(!wx(e))return;const n=e.stream;if(typeof n?.reset!="function")return;const i=e,o=j4.get(i);if(o?.source===t)return;const s=o?t.startsWith(o.source):!1,r=s&&o?t.slice(o.source.length):"",l=s&&o?qW(o.explicitBracketMath,r,o.source.length-o.explicitBracketMath.lineBuffer.length):H4(t),a=l.state,u=s&&o?l.closedOpenMath:!1;if(o&&s&&o.key===null&&o.pendingCandidate===!1&&!u&&!C2e(o.source,r)&&!b2e(t)){o.source=t,o.explicitBracketMath=a;return}const c=u0e(t);(o&&(o&&!s||o.key!==c||u)||!o&&c)&&n.reset(),k2e(e,t,c,a)}function T2e(e){return typeof e.preTransformTokens=="function"||typeof e.postTransformTokens=="function"}function UW(e,t){const n=e?.map,i=t?.map;return n===i?!0:!Array.isArray(n)||!Array.isArray(i)?!1:n.length===i.length&&n.every((o,s)=>o===i[s])}function E2e(e,t){const n=e?.attrs,i=t?.attrs;if(n===i)return!0;if(!Array.isArray(n)||!Array.isArray(i)||n.length!==i.length)return!1;for(let o=0;o":""}function vN(e){return{type:"paragraph",children:e,raw:e.map(D2e).join("")}}function yN(e,t){if(t.sourceMap)for(const n of e)n.sourceMap||(n.sourceMap=t.sourceMap)}function kN(e,t){if(e.type!=="paragraph")return null;const n=e.children,i=Array.isArray(n)?n:[];if(i.length===0)return null;const o=h2e(t);if(!o?.size)return null;let s=-1;for(let c=0;ch?.type==="hardbreak")){s=c;break}}if(s===-1)return null;const r=i.slice(0,s),l=i[s];if(!l)return null;const a=[];r.length&&a.push(vN(r)),a.push(l);const u=i.slice(s+1);return u.length&&a.push(vN(u)),a}function R2e(e){const t=e.trim();if(!t)return null;const n=/^(?:]*>\s*)?]*)?>/i.test(t),i=/<\/html>\s*$/i.test(t);return!n||!i?null:[{type:"html_block",tag:"html",raw:e,content:e,loading:!1}]}function j0(e){const t=e.raw;if(typeof t=="string")return t;const n=e.content;return typeof n=="string"?n:""}function O2e(e,t){if(e.type!=="html_block"||!t)return!1;const n=String(e.raw??e.content??"");return new RegExp(String.raw`^\s*<\s*\/\s*${Au(t)}\s*>\s*$`,"i").test(n)}const u8=new Set(["iframe","script","style","textarea","title"]);function m2(e,t,n){if(!e||!t)return null;const i=t.toLowerCase(),o=f=>{if(e.startsWith("",f+4);return{closing:!1,end:C===-1?e.length:C+3,selfClosing:!1,tag:""}}if(e.startsWith("",f+9);return{closing:!1,end:C===-1?e.length:C+3,selfClosing:!1,tag:""}}const h=No(e.slice(f));if(h===-1)return null;const m=f+h+1,g=e.slice(f,m);if(/^<\s*[!?]/.test(g))return{closing:!1,end:m,selfClosing:!1,tag:""};let y=g.slice(1).trimStart();const k=y.startsWith("/");k&&(y=y.slice(1).trimStart());const v=y.match(/^([A-Z][\w:-]*)/i);return v?.[1]?{closing:k,end:m,selfClosing:/\/\s*>$/.test(g),tag:v[1].toLowerCase()}:{closing:!1,end:f+1,selfClosing:!1,tag:""}},s=(f,h)=>{const m=new RegExp(String.raw`<\s*\/\s*${Au(f)}(?=\s|>)`,"gi");m.lastIndex=h;const g=m.exec(e);if(!g||g.index==null)return null;const y=o(g.index);return y?{start:g.index,end:y.end}:null};let r=-1,l=-1,a=Math.max(0,n);for(;a$/.test(u))return{raw:u,start:r,end:l+1,closed:!0};if(u8.has(i)){const f=s(i,l+1);return f?{raw:e.slice(r,f.end),start:r,end:f.end,closeStart:f.start,closed:!0}:{raw:e.slice(r),start:r,end:e.length,closed:!1}}let c=1,d=l+1;for(;d]*$/,"")} +`}function bN(e){return e.replace(/\r\n/g,` +`).replace(/(^|\n)[ \t]{1,4}/g,"$1")}function $2e(e,t,n){return n?e.includes(n,t)?!0:bN(e.slice(Math.max(0,t))).includes(bN(n)):!1}function z2e(e,t){let n=Math.max(0,t);for(;n)`,"gi");let i=-1,o;for(;(o=n.exec(e))!==null;)i=o.index;return i}function KW(e,t){return{final:t,__disableStreamParse:!0,requireClosingStrong:e.requireClosingStrong,customHtmlTags:e.customHtmlTags,validateLink:e.validateLink}}const H2e=new Set(["admonition","blockquote","code_block","definition_list","footnote","heading","list","math_block","table","thematic_break"]),W2e=/(?:^|\n)\s{0,3}(?:#{1,6}\s+\S|[-+*]\s+\S|\d+[.)]\s+\S|>\s*\S|`{3,}|~{3,}|(?:\*{3,}|-{3,}|_{3,})(?:\s|$)|\|.*\|)/m;function q2e(e){return/\n\s*\n/.test(e)||W2e.test(e)}function U2e(e,t){if(!e.trim()||t.length===0)return!1;if(t.some(i=>H2e.has(String(i?.type??"").toLowerCase()))||t.some(i=>{if(i?.type!=="html_block")return!1;const o=i;return Array.isArray(o.children)&&o.children.length>0}))return!0;if(!q2e(e))return!1;if(t.length>1)return!0;const[n]=t;return!!(n&&n.type==="paragraph")}function V2e(e){const t=[];let n=0;for(;n=e.length)break;const i=e.slice(n).match(/^<([A-Z][\w:-]*)/i);if(!i?.[1])return null;const o=m2(e,i[1],n);if(!o||o.start!==n)return null;t.push(o.raw),n=o.end}return t.length>1?t:null}function K2e(e,t,n,i){const o=n.customHtmlTags?.join("\0")??"",s=t,r=aN.get(s),l=r&&r.final===i&&r.customHtmlTags===o&&r.requireClosingStrong===n.requireClosingStrong&&r.validateLink===n.validateLink,a=e.map((u,c)=>l&&r.blocks[c]===u?r.children[c]:rm(u,t,n));return aN.set(s,{blocks:e,children:a,customHtmlTags:o,final:i,requireClosingStrong:n.requireClosingStrong,validateLink:n.validateLink}),a.flat()}function Z2e(e,t,n,i){return e.map(o=>{if(o?.type!=="html_block")return o;const s=o,r=String(s.tag??"").toLowerCase();if(!r||r==="details"||VH.has(r)||Array.isArray(s.children))return o;const l=String(o.raw??s.content??"");if(!l)return o;const a=No(l);if(a===-1)return o;const u=m2(l,r,0),c=u?.closeStart??-1,d=u?.closed===!0&&c>=a+1,f=d?l.slice(a+1,c):l.slice(a+1);if(!f.trim())return o;const h=KW(n,i),m=d?null:V2e(f),g=m?K2e(m,t,h,i):rm(f,t,h);return U2e(f,g)?{...o,children:g}:o})}function G2e(e){for(const t of e)if(t?.type==="html_block")return!0;return!1}function rm(e,t,n){return e.trim()?GW(e,t,{...n,__disableStreamParse:!0,__disableStructuredReuse:!0}):[]}function Q2e(e,t,n){const i=rm(e,t,n),o=i[0];return i.length===1&&o?.type==="paragraph"&&Array.isArray(o.children)?o.children:i}function Y2e(e,t,n){const i=NW({content:e}),o=No(e),s=VW(e,"summary");if(o!==-1&&s!==-1&&s>=o+1){const r=Q2e(e.slice(o+1,s),t,n);r.length>0&&(i.children=r)}return i.raw=e,i}function J2e(e,t,n){const i=No(e);if(i===-1)return[];const o=e.slice(i+1);if(!o.trim())return[];const s=m2(o,"summary",0);if(!s)return rm(o,t,n);const r=o.slice(0,s.start),l=o.slice(s.end);return[...rm(r,t,n),Y2e(s.raw,t,n),...rm(l,t,n)]}function ZW(e,t,n,i,o,s=0){const r=[];let l=s;for(let a=0;a{const $=VW(f,"details");return $!==-1?f.slice(0,$):f})():f,[C]=ZW(k?[]:g===-1?e.slice(a+1):e.slice(a+1,g),t,n,i,o,h+f.length),w=J2e(v,n,KW(i,o)),M=g===-1?"":String(e[g].raw??j0(e[g])??""),L=k||g!==-1&&y?.closed===!0,E=M.replace(/[\t\r\n ]+$/,""),S=L?(()=>{const $=(y?.raw??"").lastIndexOf(E);return $===-1?t.length:h+$})():t.length,x=No(f),A=k&&x!==-1?h+x+1:h+f.length,T=t.slice(A,S===-1?t.length:S),I=n.parse(T,{__markstreamFinal:o}),O=n.renderer.render(I,n.options,{__markstreamFinal:o}),H=S+E.length,R=L?Math.max(S+M.length,z2e(t,H)):t.length,F=L?t.slice(S,R):M,P=L?t.slice(h,R):t.slice(h),z=k&&x!==-1?f.slice(0,x+1):f,W={...u,tag:"details",attrs:$4(f.slice(0,x+1)),raw:P,content:`${z}${O}${F}`,children:[...w,...C],loading:!o&&!L};if(i.includeSourceMap&&(W.sourceMap=Rv(t,h,L?R:t.length,i)),r.push(W),l=L?R:t.length,g===-1&&!k)break;g!==-1&&(a=g)}return[r,l]}function X2e(e,t,n,i){if(!n)return e;const o=e.slice();let s=0;for(let r=0;r=d.start&&x.end<=d.end){o.splice(L,1);continue}break}M=S+E.length,o.splice(L,1)}}return o}function eye(e){const t=l=>l===" "||l===" "||l===` +`||l==="\r",n=l=>{if(!l||l[0]!=="<"||l.includes(">"))return!1;let a=1;if(a{const y=g.charCodeAt(0);return y>=65&&y<=90||y>=97&&y<=122},c=g=>{const y=g.charCodeAt(0);return y>=48&&y<=57},d=g=>g==="!"||u(g),f=g=>u(g)||c(g)||g===":"||g==="-",h=g=>u(g)||c(g)||g==="_"||g==="."||g===":"||g==="-",m=h;if(a>=l.length||!d(l[a]))return!1;for(a++;a=l.length)return!0;if(l[a]==="/"){for(a++;a=l.length}if(!h(l[a]))return!1;for(a++;a=l.length)return!0;const g=l[a];if(g==='"'||g==="'"){for(a++;a=l.length)return!0;a++}else{for(;a"||y==='"'||y==="'"||y==="`")break;a++}if(a>=l.length)return!0}}}return!0},i=(l,a)=>HW(l,a),o=String(e??""),s=o.lastIndexOf("<");if(s===-1||i(o,s))return o;if(s>0){const l=o[s-1],a=l===" "||l===" "||l===` +`||l==="\r",u=o[s-2];if(!a&&!((l==="n"||l==="r")&&u==="\\"))return o}const r=o.slice(s);return r.includes(">")||r.length>1&&(r[1]===" "||r[1]===" "||r[1]===` +`||r[1]==="\r")||!n(r)?o:o.slice(0,s)}function CN(e,t){if(e===t)return;const n=e.split(/\r?\n/),i=t.split(/\r?\n/),o=[];let s=0;for(let r=0;r{const l=Number.isFinite(r)?Math.max(0,Math.trunc(r)):0;if(lString(m??"").toLowerCase()).filter(Boolean));if(!n.size)return e;const i=m=>m===" "||m===" ",o=m=>{const g=m.charCodeAt(0);return g>=65&&g<=90||g>=97&&g<=122||g>=48&&g<=57||m==="_"||m==="-"||m===":"},s=m=>{if(!m)return!1;if(m[0]===" ")return!0;let g=0;for(let y=0;y=4)return!0;continue}if(k===" ")return!0;break}return!1},r=m=>{let g=!1,y=!1;for(let k=0;k")return k}return-1},l=m=>{let g=0;for(;g{if(s(m))return-1;const y=m.replace(/^[ \t]+/,"");if(!y||y.startsWith(">")||y.startsWith("|")||/^(?:[*+-]|\d+[.)])[\t ]+/.test(y))return-1;let k=!1,v=0;for(;v=M.length){k=!0,v++;continue}const E=M[L];if(E==="!"||E==="?"){k=!0,v+=w+1;continue}if(E==="/"){k=!0,v+=w+1;continue}const S=L;for(;L"&&A!=="/"){k=!0,v++;continue}const T=new RegExp(String.raw`<\s*\/\s*${x}\s*>`,"i"),I=/\/\s*>$/.test(M),O=T.test(m.slice(v+w+1)),H=T.test(e.slice(g+v+w+1)),R=/[\r\n]/.test(e.slice(g+v+w+1));if(k&&n.has(x)&&!I&&!O&&(H||R))return v;k=!0,v+=w+1}return-1};let u=!1,c="",d=0,f="",h=0;for(;hh&&e[m-1]==="\r",k=g?y?m-1:m:e.length,v=e.slice(h,k),C=g?y?`\r +`:` +`:"",w=l(v);let M=v;if(!u&&!w){const L=a(v,h);if(L!==-1){const E=C||` +`;M=`${v.slice(0,L).replace(/[ \t]+$/,"")}${E}${E}${v.slice(L).replace(/^[ \t]+/,"")}`}}f+=M,f+=C,w&&(u?w.markerChar===c&&w.markerLen>=d&&/^\s*$/.test(w.rest)&&(u=!1,c="",d=0):(u=!0,c=w.markerChar,d=w.markerLen)),h=g?m+1:e.length}return f}function nye(e,t){if(!e||!t.length)return e;const n=new Set(t.map(d=>String(d??"").toLowerCase()));if(!n.size)return e;const i=d=>d===" "||d===" ",o=d=>{const f=d.charCodeAt(0);return f>=65&&f<=90||f>=97&&f<=122||f>=48&&f<=57||d==="_"||d==="-"},s=d=>{let f=0;for(;f{let f=!1,h=!1;for(let m=0;m")return m}return-1},l=(d,f,h)=>{const m=h.toLowerCase();let g=d.indexOf("<",f);for(;g!==-1;){let y=g+1;for(;y=d.length||d[y]!=="/"){g=d.indexOf("<",g+1);continue}for(y++;yd.length){g=d.indexOf("<",g+1);continue}let k=!0;for(let C=0;C="A"&&w<="Z"?String.fromCharCode(w.charCodeAt(0)+32):w)!==m[C]){k=!1;break}}if(!k){g=d.indexOf("<",g+1);continue}let v=y+m.length;if(v")return!0;g=d.indexOf("<",g+1)}return!1},a=d=>{let f=0;for(;f=d.length||d[f]!=="<")return d;for(f++;f=d.length||d[f]==="/")return d;const h=f;for(;fc&&e[d-1]==="\r",h=f?d-1:d,m=e.slice(c,h);u+=a(m),u+=f?`\r +`:` +`,c=d+1}return u}function iye(e,t){if(!e||!t.length)return e;const n=new Set(t.map(f=>String(f??"").toLowerCase()));if(!n.size)return e;const i=f=>f===" "||f===" ",o=f=>{let h=0,m=!1,g=0;for(;h=f.length||f[h]!==">")break;for(m=!0,h++;h{let h=0;for(;hnew RegExp(String.raw`(<\s*\/\s*${f}\s*>)${"(?=[\\t ]*(?:#{1,6}[\\t ]+|>|(?:[*+-]|\\d+[.)])[\\t ]+|(?:`{3,}|~{3,})|\\||\\$\\$|:{3,}|\\[\\^[^\\]]+\\]:|(?:-{3,}|\\*{3,}|_{3,})))"}`,"gi"));let l=!1,a="",u=0,c="",d=0;for(;dd&&e[f-1]==="\r",g=h?m?f-1:f:e.length,y=e.slice(d,g),k=h?m?`\r +`:` +`:"",v=o(y),C=v?.prefix??"",w=v?.content??y,M=s(w);M&&(l?M.markerChar===a&&M.markerLen>=u&&/^\s*$/.test(M.rest)&&(l=!1,a="",u=0):(l=!0,a=M.markerChar,u=M.markerLen));let L=w;if(!l&&L.includes("{if(T.replace(/^[\t ]+/,"").startsWith("|"))return S;const I=T.slice(0,A).replace(/^[\t ]+/,"");if(I.length>0){const O=x.match(/^<\s*\/\s*([A-Z][\w:-]*)/i)?.[1]?.toLowerCase()??"",H=I.match(/^<\s*([A-Z][\w:-]*)/i)?.[1]?.toLowerCase()??"";if(!O||!H||O!==H)return S}return`${x} + +`});if(C){const E=C+L.split(` +`).join(` +${C}`);c+=E}else c+=L;c+=k,d=h?f+1:e.length}return c}function oye(e,t){if(!e||!t.length)return e;const n=new Set(t.map(I=>String(I??"").toLowerCase()));if(!n.size)return e;const i=I=>I===" "||I===" ",o=I=>{if(!I)return!1;if(I[0]===" ")return!0;let O=0;for(let H=0;H=4)return!0;continue}if(R===" ")return!0;break}return!1},s=I=>{const O=I.charCodeAt(0);return O>=65&&O<=90||O>=97&&O<=122||O>=48&&O<=57||I==="_"||I==="-"||I===":"},r=I=>{let O=0;for(;O{let O=0,H=!1,R=0;for(;O=I.length||I[O]!==">")break;for(H=!0,O++;Or(I).startsWith("<"),u=I=>{for(let O=0;O{if(o(I))return"";const O=r(I);if(!O.startsWith("<"))return"";let H=1;for(;H=O.length||O[H]==="/"||O[H]==="!"||O[H]==="?")return"";const R=H;for(;H"&&P!=="/"?"":F},d=I=>{if(o(I))return null;const O=r(I);if(!O.startsWith("<"))return null;let H=1;for(;H=O.length)return null;const R=O[H]==="/";if(R)for(H++;H"&&W!=="/")return null;if(R)return{type:"close",name:z};if(/\/\s*>\s*$/.test(O))return{type:"open",name:z,complete:!0};const $=O.indexOf(">",H);if($!==-1){const K=O.slice($+1);if(new RegExp(`<\\s*\\/\\s*${z}\\s*>`,"i").test(K))return{type:"open",name:z,complete:!0}}return{type:"open",name:z,complete:!1}},f=I=>{if(o(I))return null;const O=r(I).replace(/[ \t]+$/,"");if(!O.startsWith("<")||/^<\s*(?:!--|!doctype\b|\?)/i.test(O))return null;const H=O.match(/^<\s*([A-Z][\w:-]*)\b[^>]*\/\s*>\s*$/i);if(H?.[1])return H[1].toLowerCase();const R=O.match(/^<\s*([A-Z][\w:-]*)\b[^>]*>[\s\S]*<\s*\/\s*([A-Z][\w:-]*)\s*>\s*$/i);if(!R?.[1]||!R[2])return null;const F=R[1].toLowerCase();return F===R[2].toLowerCase()?F:null};let h=!1,m="",g=0;const y=I=>{let O=0;for(;Oy(I),v=I=>{const O=r(I);return O?o(I)?!0:/^(?:#{1,6}[ \t]+|>|[*+-][ \t]+|\d+[.)][ \t]+|`{3,}|~{3,}|\||\$\$|:{3,}|\[\^[^\]]+\]:|-{3,}|\*{3,}|_{3,})/.test(O):!1},C=(I,O,H)=>{let R=I,F=0;for(;RR&&e[P-1]==="\r",$=z?W?P-1:P:e.length,K=e.slice(R,$),ne=l(K),G=ne?.key??"";if(F>0&&O&&G!==O)break;const te=ne?.content??K,le=d(te);if(le?.name===H){if(le.type==="open")le.complete||F++;else if(F>0&&(F--,F===0))return!1}else if(F>0&&(u(te)||v(te)))return!0;if(z)R=P+1;else break}return!1};let w="",M=0,L=!0,E=!1,S=!1,x=` +`;const A=[];let T="";for(;MM&&e[I-1]==="\r",R=O?H?I-1:I:e.length,F=e.slice(M,R),P=O?H?`\r +`:` +`:"",z=l(F),W=z?.key??"",$=z?.content??F,K=k($);K&&(h?K.markerChar===m&&K.markerLen>=g&&/^\s*$/.test(K.rest)&&(h=!1,m="",g=0):(h=!0,m=K.markerChar,g=K.markerLen));const ne=A.length>0;if(!h&&!ne){const te=c($),le=!!te&&!L&&E&&S&&C(M,W,te);te&&!L&&(!E||le)&&(W&&T&&W===T?w+=`${W}${x}`:W||(w+=x))}if(w+=F,w+=P,P&&(x=P),!h){const te=d($);if(te){if(te.type==="open")te.complete||A.push(te.name);else for(let le=A.length-1;le>=0;le--)if(A[le]===te.name){A.length=le;break}}}const G=u($);L=G,E=!G&&a($),S=!G&&!!f($),T=W,M=O?I+1:e.length}return w}function sye(e){let t=!1,n="",i=0,o=!1,s=!1,r=!1,l=0;const a=(c,d)=>{const f=Nx(c);if(f){t?f.markerChar===n&&f.markerLen>=i&&/^\s*$/.test(f.rest)&&(t=!1,n="",i=0):(t=!0,n=f.markerChar,i=f.markerLen);return}if(t)return;let h=0;for(;h{for(;l=c?c:d,h=f>l&&e[f-1]==="\r"?f-1:f;if(a(e.slice(l,h)),d===-1||d>=c){l=c;break}r=!1,l=d+1}},inMath:()=>o||s||r}}function c8(e,t,n,i){let o=e.replace(/([^\\])\r(ight|ho)/g,"$1\\r$2");const s=sye(o);if(o=o.replace(/([^\\])\r?\n(abla|eq|ot|exists)/g,(r,l,a,u)=>{s.scanTo(u+1);const c=s.inMath();return s.scanTo(u+r.length),c?`${l}\\n${a}`:r}),t||(o.endsWith("- *")&&(o=o.replace(/- \*$/,"- \\*")),/(?:^|\n)\s*-\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*-\s*$/,r=>r.startsWith(` +`)?` +`:""):/(?:^|\n)\s*--\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*--\s*$/,r=>r.startsWith(` +`)?` +`:""):/(?:^|\n)\s*>\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*>\s*$/,r=>r.startsWith(` +`)?` +`:""):/\n\s*[*+]\s*$/.test(o)?o=o.replace(/\n\s*[*+]\s*$/,` +`):/(?:^|\n)\s*\d+\s*$/.test(o)?/^\d+$/.test(o.trim())||(o=o.replace(/(?:^|\n)\s*\d+\s*$/,r=>r.startsWith(` +`)?` +`:"")):/(?:^|\n)\s*\d+[.)]\s+\*{1,3}\s*$/.test(o)?o=o.replace(/((?:^|\n)\s*\d+[.)]\s+)(\*{1,3})\s*$/,(r,l,a)=>`${l}${a.split("").map(()=>"\\*").join("")}`):/(?:^|\n)\s*\d+[.)]\s*$/.test(o)?o=o.replace(/(?:^|\n)\s*\d+[.)]\s*$/,r=>r.startsWith(` +`)?` +`:""):/\n[[(]\n*$/.test(o)&&(o=o.replace(/(\n\[|\n\()+\n*$/g,` +`)),o=S2e(o,i.customHtmlTags)??o),i.customHtmlTags?.length&&o.includes("<")){const r=Np(i.customHtmlTags);if(r.length&&(o=tye(o,r),o=nye(o,r),o=oye(o,r),o=iye(o,r),o.includes("[\t ]*)(\r?\n)(?![\t ]*\r?\n|$)`,"gim");o=o.replace(a,"$1$2$2")}}return t||(o=eye(o)),o}function rye(e,t,n,i){const o=e,s=`${n?"final":"stream"}:${(i.customHtmlTags??[]).join(",")}`,r=_A.get(o);let l;if(!n&&!i.customHtmlTags?.length&&r&&r.mode===s&&t.length>=r.source.length&&t.startsWith(r.source)){const a=Math.max(0,r.source.length-n2e-i2e),u=c8(t.slice(a),n,e,i),c=r.source.length-a;l=u.length>=c&&u.slice(0,c)===r.safeMarkdown.slice(-c)?r.safeMarkdown.slice(0,r.safeMarkdown.length-c)+u:c8(t,n,e,i)}else l=c8(t,n,e,i);return n||(l=_2e(l,e)),_A.set(o,{source:t,safeMarkdown:l,mode:s}),l}function GW(e,t,n={}){const i=OW(n),o=i?au():0,s=!!n.final,r=(e??"").toString();g2e(t,n)&&(t.stream.reset(),v2e(t),_A.delete(t));const l=rye(t,r,s,n);i&&cf(i,"safeMarkdownMs",au()-o);const a=R2e(l);if(a){if(n.includeSourceMap){const M={...n,__sourceLineMapper:CN(r,l)};a[0].sourceMap=Rv(l,0,l.length,M)}const C=n.preTransformTokens,w=n.postTransformTokens;if(Mx(t,n)||typeof C=="function"||typeof w=="function"){const M=gN(t,l,{__markstreamFinal:s},n),L=typeof C=="function"&&C(M)||M;typeof w=="function"&&w(L)}return cN(a,n,i,o)}const u=i?au():0,c=gN(t,l,{__markstreamFinal:s},n);if(i&&cf(i,"tokenizeMs",au()-u),!c||!Array.isArray(c))return cN([],n,i,o);const d=n.preTransformTokens,f=n.postTransformTokens;let h=c;d&&typeof d=="function"&&(h=d(h)||h);const m=t,g=typeof m.validateLink=="function"&&m.__markstreamOriginalValidateLink&&m.validateLink!==m.__markstreamOriginalValidateLink?m.validateLink:void 0,y=n.validateLink??g??m.options?.validateLink??(typeof m.validateLink=="function"?m.validateLink:void 0),k={...n,validateLink:y,__markdownIt:t,__sourceLineMapper:n.includeSourceMap===!0?CN(r,l):void 0,__sourceMarkdown:l,__customHtmlBlockCursor:0};let v=f2e(t,l,h,k,i);if(f&&typeof f=="function"){const C=f(h);if(Array.isArray(C)){const w=C[0],M=w?.type;w&&typeof M=="string"?v=S1(C,{...k,__customHtmlBlockCursor:0},i):v=C}}if(G2e(v)){const C=i?au():0;v=X2e(v,s,l,k),v=ZW(v,l,t,k,s)[0],v=Z2e(v,t,k,s),i&&cf(i,"htmlBlockPassesMs",au()-C)}if(s){const C=new WeakSet,w=M=>{if(!M||typeof M!="object"||C.has(M))return;if(C.add(M),Array.isArray(M)){for(const E of M)w(E);return}const L=M;L.type==="html_block"&&L.loading===!0&&(L.loading=!1);for(const E of Object.values(L))w(E)};w(v)}return v=BW(v,n),n.debug&&console.log("Parsed Markdown Tree Structure:",v),PW(v,i,o)}function AN(e,t){if(!e||!Array.isArray(e))return[];const n=[],i=qf(t),o=t?.__linkifyDemotionSeed;if(Array.isArray(o)&&o.length)for(const l of o)i.remember(String(l??""));const s=t?.includeSourceMap===!0;let r=0;for(;rd.type==="html_block")){if(s)for(const d of c)bi(d,a,t);for(const d of c)Bu(d,a,t);n.push(...c)}else{const d={type:"paragraph",raw:u,children:c};s&&bi(d,a,t);const f=kN(d,t);if(f){s&&yN(f,d);for(const h of f)Bu(h,a,t);n.push(...f)}else Bu(d,a,t),n.push(d)}i.remember(u)}r+=1;break;default:r+=1;break}}return n}const lye=/\\([ \\!"#$%&'()*+,./:;<=>?@[\]^_`{|}~-])/g,H0=/\d/u,aye=/[,.!?;:,。;、!?:]/u,uye=/\d\p{Script=Han}{1,3}$/u;function cye(e){return e.pos>0&&e.pos+1{const u=l,c=u.posMax,d=u.pos;if(u.src.charCodeAt(d)!==r||a||s.refuseDigitRange&&cye(u))return!1;u.pos=d+1;let f=!1;for(;u.pos]|$)/i,pye=new Set([...f2,"base","button","datalist","dialog","embed","fieldset","form","iframe","input","legend","link","meta","object","optgroup","option","output","param","select","style","template","textarea","title"]),mye=new Set(["a","abbr","b","blockquote","br","caption","code","col","colgroup","dd","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","mark","ol","p","picture","pre","s","small","source","span","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","ul"]);function xN(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function gye(e){return typeof e=="string"?e:e==null?"":String(e)}function QW(e){return/^[^\s"'<>`=]+$/.test(e)&&!/^on/i.test(e)}function Yd(e){return gye(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function YW(e){return Yd(e).replace(/`/g,"`")}function q4(e){return String(e??"").trim().toLowerCase()}function Dx(e,t="safe"){const n=q4(e);return n?t==="escape"?!0:t==="trusted"?f2.has(n):!mye.has(n):!1}function JW(e,t="safe"){const n=q4(e);return n?t==="escape"?!0:t==="trusted"?f2.has(n):pye.has(n):!1}function SN(e){const t=Object.entries(e);return t.length===0?"":t.map(([n,i])=>i===""?` ${n}`:` ${n}="${YW(i)}"`).join("")}function XW(e){const t=e.startsWith("/"),n=t?e.slice(1):e,i=n.match(hye);return i?{attrsStr:t?"":n.slice(i[0].length).trimStart(),isClosing:t,isSelfClosing:!t&&e.trimEnd().endsWith("/"),tagName:i[1]}:null}function vye(e,t){const n=e.split(",").map(i=>i.trim()).filter(Boolean);return n.length===0?!1:n.some(i=>{const o=i.split(/\s+/,1)[0]??"";return!o||ip(o,{tagName:t,attrName:"srcset"})})}function eq(e,t,n,i){return X1e.has(e)||n==="safe"&&e==="style"?!0:e==="srcset"?vye(t,i):!!(eme.has(e)&&t&&ip(t,{tagName:i,attrName:e}))}function Fh(e,t){const n=t.toLowerCase();return Object.keys(e).find(i=>i.toLowerCase()===n)}function tq(e,t,n,i=!1){if(t!=="safe"||q4(n)!=="a")return e;const o=Fh(e,"href");if(i&&(!o||!e[o])){const a=Fh(e,"target"),u=Fh(e,"rel");return a&&delete e[a],u&&delete e[u],e}const s=Fh(e,"target");if((s?String(e[s]).trim():"").toLowerCase()!=="_blank")return e;const r=Fh(e,"rel"),l=new Set(String(r?e[r]:"").split(/\s+/).map(a=>a.trim()).filter(Boolean).filter(a=>a.toLowerCase()!=="opener"));return l.add("noopener"),l.add("noreferrer"),r&&r!=="rel"&&delete e[r],e.rel=Array.from(l).join(" "),e}function _N(e,t="safe",n){const i={};for(const[o,s]of Object.entries(e)){const r=o.trim(),l=r.toLowerCase();!r||!QW(r)||eq(l,s,t,n)||(i[r]=s)}return tq(i,t,n,!!Fh(e,"href"))}function nq(e,t){const n=e.toLowerCase();return UH.has(n)?!1:xN(t,n)||xN(t,e)}function Rx(e,t="safe",n){const i={};for(const[o,s]of Object.entries(e)){const r=o.trim(),l=r.toLowerCase();!r||!QW(r)||eq(l,s,t,n)||(i[r]=s)}return tq(i,t,n,!!Fh(e,"href"))}function W0(e){const t={};if(!Array.isArray(e)||e.length===0)return t;for(const[n,i]of e)n&&(t[String(n)]=i==null?"":String(i));return t}function P9(e,t="safe",n){const i=Rx(W0(e),t,n),o=Object.entries(i).map(([s,r])=>[s,r]);return o.length>0?o:void 0}function yye(e,t){const n=t.toLowerCase();if(["checked","disabled","readonly","required","autofocus","multiple","hidden"].includes(n))return e==="true"||e===""||e===t;if(["value","min","max","step","width","height","size","maxlength"].includes(n)){const i=Number(e);if(e!==""&&!Number.isNaN(i))return i}return e}function kye(e){const t={};for(const[n,i]of Object.entries(e))t[n]=yye(i,n);return t}function d8(e){return e.trim().length>0}function iq(e){const t=[];let n=0;for(;n",n);if(r!==-1){n=r+3;continue}break}const i=e.indexOf("<",n);if(i===-1){if(nn){const r=e.slice(n,i);d8(r)&&t.push({type:"text",content:r})}if(e.startsWith("![CDATA[",i+1)){const r=e.indexOf("]]>",i);if(r!==-1){t.push({type:"text",content:e.slice(i,r+3)}),n=r+3;continue}break}if(e.startsWith("!",i+1)){const r=e.indexOf(">",i);if(r!==-1){n=r+1;continue}break}const o=e.indexOf(">",i);if(o===-1)break;const s=XW(e.slice(i+1,o));if(!s){const r=e.slice(i,o+1);d8(r)&&t.push({type:"text",content:r}),n=o+1;continue}if(s.isClosing)t.push({type:"tag_close",tagName:s.tagName});else{const r={};if(s.attrsStr){const l=/([^\s=]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S*)))?/g;let a;for(;(a=l.exec(s.attrsStr))!==null;){const u=a[1],c=a[2]??a[3]??a[4]??"";u&&!u.endsWith("/")&&(r[u]=c)}}t.push({type:s.isSelfClosing||Sf.has(s.tagName.toLowerCase())?"self_closing":"tag_open",tagName:s.tagName,attrs:r})}n=o+1}return t}function bye(e){const t=[];let n=0;for(;n",n);if(l!==-1){n=l+3;continue}break}const i=e.indexOf("<",n);if(i===-1){nn&&t.push({type:"text",content:e.slice(n,i)}),e.startsWith("![CDATA[",i+1)){const l=e.indexOf("]]>",i);if(l!==-1){t.push({type:"text",content:e.slice(i,l+3)}),n=l+3;continue}break}if(e.startsWith("!",i+1)){const l=e.indexOf(">",i);if(l!==-1){n=l+1;continue}break}const o=e.indexOf(">",i);if(o===-1)break;const s=XW(e.slice(i+1,o));if(!s){t.push({type:"text",content:e.slice(i,o+1)}),n=o+1;continue}if(s.isClosing){t.push({type:"tag_close",tagName:s.tagName}),n=o+1;continue}const r={};if(s.attrsStr){const l=/([^\s=]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S*)))?/g;let a;for(;(a=l.exec(s.attrsStr))!==null;){const u=a[1],c=a[2]??a[3]??a[4]??"";u&&!u.endsWith("/")&&(r[u]=c)}}t.push({type:s.isSelfClosing||Sf.has(s.tagName.toLowerCase())?"self_closing":"tag_open",tagName:s.tagName,attrs:r}),n=o+1}return t}function wye(e){const t=String(e.tagName??"").trim();if(!t)return"";if(e.type==="tag_close")return`</${Yd(t)}>`;const n=Object.entries(e.attrs??{}).map(([i,o])=>o===""?` ${Yd(i)}`:` ${Yd(i)}="${YW(o)}"`).join("");return e.type==="self_closing"?`<${Yd(t)}${n} />`:`<${Yd(t)}${n}>`}function Cye(e,t){if(!e||!e.includes("<")||!t||Object.keys(t).length===0)return!1;for(const n of iq(e))if((n.type==="tag_open"||n.type==="self_closing")&&nq(n.tagName??"",t))return!0;return!1}function lm(e,t="safe"){if(!e)return"";if(t==="escape")return Yd(e);const n=bye(e),i=[],o=[],s=[];for(const r of n){if(r.type==="text"){s.length===0&&o.push(Yd(r.content??""));continue}const l=q4(r.tagName);if(!l)continue;if(JW(l,t)){r.type==="tag_open"?s.push(l):r.type==="tag_close"&&s[s.length-1]===l&&s.pop();continue}if(s.length>0)continue;if(t==="safe"&&Dx(l,t)){o.push(wye(r));continue}if(r.type==="self_closing"){o.push(`<${l}${SN(_N(r.attrs??{},t,l))}>`);continue}if(r.type==="tag_open"){o.push(`<${l}${SN(_N(r.attrs??{},t,l))}>`),Sf.has(l)||i.push(l);continue}const a=i.lastIndexOf(l);if(a===-1)continue;for(;i.length>a+1;){const c=i.pop();c&&o.push(``)}const u=i.pop();u&&o.push(``)}for(;i.length>0;){const r=i.pop();r&&o.push(``)}return o.join("")}const Aye=[/javascript:/i,/vbscript:/i,/data:text\/html/i,/expression\s*\(/i,/@import/i],IN="http://www.w3.org/2000/svg",xye=new Set(["script","style","iframe","object","embed","link","meta"]),Sye=new Set(["svg","style","g","a","defs","marker","path","rect","circle","ellipse","line","polyline","polygon","text","tspan","title","desc","use","image","lineargradient","radialgradient","stop","clippath","mask","pattern"]),_ye=new Set(["href","xlink:href","src","srcdoc","action","data","formaction","poster"]),Iye=new Set(["clip-path","fill","filter","marker-end","marker-mid","marker-start","mask","stroke"]),Mye=new Set(["circle","ellipse","image","line","path","polygon","polyline","rect","text","tspan","use"]);function Tye(e){return(e.getAttribute("href")||e.getAttribute("xlink:href"))?.startsWith("#")===!0}function Eye(e){return!!(e.getAttribute("href")||e.getAttribute("xlink:href")||e.getAttribute("src"))}function Lye(e){const t=e.nodeName.toLowerCase();return t==="use"?Tye(e):t==="image"?Eye(e):t==="text"||t==="tspan"?!!e.textContent?.trim():Mye.has(t)}function Nye(e){return e.replace(/(["'])\s*javascript:/gi,"$1#").replace(/\bjavascript:/gi,"#").replace(/(["'])\s*vbscript:/gi,"$1#").replace(/\bvbscript:/gi,"#").replace(/\bdata:text\/html/gi,"#")}function Fye(e,t,n){const i=e.toLowerCase(),o=t.toLowerCase(),s=String(n??"").trim();return s?(i==="use"||i==="marker"||i==="clippath"||i==="mask")&&(o==="href"||o==="xlink:href")?s.startsWith("#")?s:"":i==="a"&&(o==="href"||o==="xlink:href")?ip(s,{tagName:"a",attrName:"href"})?"":s:i==="image"&&(o==="href"||o==="xlink:href"||o==="src")?ip(s,{tagName:"img",attrName:"src"})?"":s:o==="href"||o==="xlink:href"?s.startsWith("#")?s:"":ip(s,{tagName:i,attrName:o})?"":s:""}function Dye(e,t){let n=t+4;for(;n{const i=n.trim();if(/^[0-9a-f]+$/i.test(i)){const o=Number.parseInt(i,16);try{return Number.isFinite(o)?String.fromCodePoint(o):""}catch{return""}}return String(n).trim()})}function sq(e){const t=oq(e),n=t.toLowerCase();let i=0;for(;in.test(t))||sq(t)}function Rye(e){if(e.tagName.toLowerCase()!=="a"||e.getAttribute("target")?.trim().toLowerCase()!=="_blank")return;const t=new Set(String(e.getAttribute("rel")??"").split(/\s+/).map(n=>n.trim()).filter(Boolean).filter(n=>n.toLowerCase()!=="opener"));t.add("noopener"),t.add("noreferrer"),e.setAttribute("rel",Array.from(t).join(" "))}function Ly(e){const t=Number.parseFloat(String(e??""));return Number.isFinite(t)?t:0}function rq(e,t){if(e.nodeType===Node.TEXT_NODE){const o=e.textContent??"";o&&t.push(o);return}if(e.nodeType!==Node.ELEMENT_NODE)return;const n=e,i=n.tagName.toLowerCase();if(!xye.has(i)){if(i==="br"){t.push(` +`);return}for(const o of Array.from(n.childNodes))rq(o,t)}}function Oye(e){for(const t of Array.from(e.querySelectorAll("foreignObject"))){const n=[];rq(t,n);const i=n.join("").split(/\r?\n/).map(c=>c.trim()).filter(Boolean);if(!i.length){t.remove();continue}const o=Ly(t.getAttribute("width")),s=Ly(t.getAttribute("height")),r=Ly(t.getAttribute("x")),l=Ly(t.getAttribute("y")),a=e.ownerDocument.createElementNS(IN,"text");a.setAttribute("x",String(r+o/2)),a.setAttribute("y",String(l+s/2)),a.setAttribute("text-anchor","middle"),a.setAttribute("dominant-baseline","central");const u=t.querySelector(".nodeLabel");if(u?.getAttribute("class")&&a.setAttribute("class",u.getAttribute("class")),i.length===1)a.textContent=i[0];else{const c=-.6*(i.length-1);for(const[d,f]of i.entries()){const h=e.ownerDocument.createElementNS(IN,"tspan");h.setAttribute("x",String(r+o/2)),h.setAttribute("dy",d===0?`${c}em`:"1.2em"),h.textContent=f,a.appendChild(h)}}t.parentNode?.replaceChild(a,t)}}function Pye(e){Oye(e);const t=[e,...Array.from(e.querySelectorAll("*"))];for(const n of t){const i=n.tagName.toLowerCase();if(!Sye.has(i)){n.remove();continue}if(i==="style"&&MN(n.textContent??"")){n.remove();continue}const o=Array.from(n.attributes);for(const s of o){const r=s.name.toLowerCase();if(/^on/i.test(r)){n.removeAttribute(s.name);continue}if(r==="style"&&s.value&&MN(s.value)){n.removeAttribute(s.name);continue}if(r==="srcdoc"){n.removeAttribute(s.name);continue}if(_ye.has(r)&&s.value){const l=Fye(i,r,s.value);if(!l){n.removeAttribute(s.name);continue}l!==s.value&&n.setAttribute(s.name,l);continue}if(Iye.has(r)&&s.value&&sq(s.value)){n.removeAttribute(s.name);continue}if(s.value){const l=Nye(s.value);l!==s.value&&n.setAttribute(s.name,l)}}Rye(n)}}function R8t(e){if(typeof DOMParser>"u"||!e)return null;try{const t=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(!t||t.nodeName.toLowerCase()!=="svg")return null;const n=t;return Pye(n),Bye(n)?null:n}catch{return null}}function Bye(e){const t=e.getAttribute("viewBox");if(t){const o=t.trim().split(/[\s,]+/);if(o.length===4){const s=Number.parseFloat(o[2]||""),r=Number.parseFloat(o[3]||"");if(!Number.isFinite(s)||!Number.isFinite(r)||s<=0||r<=0)return!0}}const n=[e,...Array.from(e.querySelectorAll("*"))];let i=!1;for(const o of n){Lye(o)&&(i=!0);for(const s of Array.from(o.attributes))if(/\bNaN\b/i.test(s.value)||s.name==="style"&&/max-width:\s*0(?:px)?/i.test(s.value))return!0}return!i}const Ny=[];function f8(e){return String(e??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function $ye(e){return(String(e||"text").trim().split(/\s+/)[0]||"text").replace(/[^\w+.#:-]/g,"-").replace(/-+/g,"-")||"text"}function zye(e){return e.replace(/[^\w:.+-]/g,"-").replace(/-+/g,"-")}function TN(e=`editor-${Date.now()}`,t={}){const n=y0e(t),i=n;i.__markstreamRegisteredPluginCount=Ny.length,i.__markstreamHasCustomParserExtensions=!!(t.plugin?.length||t.apply?.length||Ny.length);const o={"common.copy":"Copy"};let s;if(typeof t.i18n=="function")s=t.i18n;else if(t.i18n&&typeof t.i18n=="object"){const h=t.i18n;s=m=>h[m]??o[m]??m}else s=h=>o[h]??h;if(Array.isArray(t.plugin))for(const h of t.plugin){const m=h;if(Array.isArray(m)){const[g,...y]=m;typeof g=="function"&&n.use(g,...y)}else typeof m=="function"&&n.use(m)}if(Array.isArray(t.apply))for(const h of t.apply)try{h(n)}catch(m){console.error("[getMarkdown] apply function threw an error",m)}if(Ny.length)for(const h of Ny)if(Array.isArray(h)){const[m,...g]=h;typeof m=="function"&&n.use(m,...g)}else typeof h=="function"&&n.use(h);n.use(fye),n.use(Bde),n.use(Rde);const r=Yde,l=r.default??r;n.use(l),n.use(Dde),n.use(Fde),n.core.ruler.after("block","mark_fence_closed",h=>{const m=h,g=m.src,y=!!m.env?.__markstreamFinal,k=g.split(/\r?\n/);for(const v of m.tokens){if(v.type!=="fence"||!v.map||!v.markup)continue;const C=v.map[0],w=v.map[1],M=v.markup,L=M[0],E=M.length,S=k[Math.max(0,w-1)]??"";let x=0;for(;xC+1&&A>=E&&T===S.length,O=v;O.meta=O.meta??{},O.meta.unclosed=!I,O.meta.closed=!!I}}),n.renderer.rules.fence=(h,m)=>{const g=h[m],y=String(g.info??"").trim(),k=String(g.content??""),v=btoa(unescape(encodeURIComponent(k))),C=$ye(y),w=f8(C),M=zye(`editor-${e}-${m}-${C}`),L=f8(s("common.copy"));return`
    +
    + ${f8(C.toUpperCase())} + +
    +
    +
    `};const a=/^\[(\d+)\]/,u=/^\[([^\]\n]+)\]/,c=h=>{if(!h.startsWith("["))return!1;const m=u.exec(h);if(!m)return h!=="["&&!/^\[\d+$/.test(h);const g=String(m[1]??"");return h.slice(m[0].length).startsWith("(")?!1:!/^\d+$/.test(g)},d=(h,m)=>{const g=h;if(g.src[g.pos]!=="[")return!1;const y=a.exec(g.src.slice(g.pos));if(!y)return!1;const k=g.src.slice(Math.max(0,g.pos-120),g.pos);if(/"[^"\n]{1,80}"\s*:\s*$/.test(k))return!1;const v=g.src.slice(g.pos+y[0].length);if(v.startsWith("](")||v.startsWith("(")||c(v))return!1;if(!m){const C=y[1],w=g.push("reference","span",0);w.content=C,w.markup=y[0],w.raw=y[0]}return g.pos+=y[0].length,!0};n.inline.ruler.before("escape","reference",d),n.renderer.rules.reference=(h,m)=>{const y=String(h[m].content??"");return`${y}`};const f=n.use.bind(n);return n.use=((...h)=>(i.__markstreamHasCustomParserExtensions=!0,f(...h))),n}const jye="modulepreload",Hye=function(e){return"/"+e},EN={},qo=function(t,n,i){let o=Promise.resolve();if(n&&n.length>0){let r=function(u){return Promise.all(u.map(c=>Promise.resolve(c).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),a=l?.nonce||l?.getAttribute("nonce");o=r(n.map(u=>{if(u=Hye(u),u in EN)return;EN[u]=!0;const c=u.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const f=document.createElement("link");if(f.rel=c?"stylesheet":jye,c||(f.as="script"),f.crossOrigin="",f.href=u,a&&f.setAttribute("nonce",a),document.head.appendChild(f),c)return new Promise((h,m)=>{f.addEventListener("load",h),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function s(r){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=r,window.dispatchEvent(l),!l.defaultPrevented)throw r}return o.then(r=>{for(const l of r||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})};function Wye({nextContent:e,previousContent:t,typewriterEnabled:n}){return n?e===t?{settledContent:e,streamedDelta:"",appended:!1}:t&&e.startsWith(t)&&e.length>t.length?{settledContent:t,streamedDelta:e.slice(t.length),appended:!0}:{settledContent:e,streamedDelta:"",appended:!1}:{settledContent:e,streamedDelta:"",appended:!1}}function lq({nextContent:e,persistedContent:t,currentState:n,typewriterEnabled:i,streamRenderVersionChanged:o=!1}){const s=`${n.settledContent}${n.streamedDelta}`;return i?n.streamedDelta&&s===e?o?{settledContent:s,streamedDelta:"",appended:!1}:{settledContent:n.settledContent,streamedDelta:n.streamedDelta,appended:!1}:Wye({nextContent:e,previousContent:t??s,typewriterEnabled:i}):{settledContent:e,streamedDelta:"",appended:!1}}const qye={plain:"plaintext",text:"plaintext",txt:"plaintext",js:"javascript",mjs:"javascript",cjs:"javascript",ts:"typescript",mts:"typescript",cts:"typescript",golang:"go",py:"python",rb:"ruby",rs:"rust",kt:"kotlin",kts:"kotlin",md:"markdown",yml:"yaml",sh:"shellscript",bash:"shellscript",zsh:"shellscript",shell:"shellscript",shellscript:"shellscript",ps:"powershell",ps1:"powershell",pwsh:"powershell","c++":"cpp","c#":"csharp",cs:"csharp",objc:"objective-c",objectivec:"objective-c","objective-c":"objective-c",objectivecpp:"objective-cpp","objective-c++":"objective-cpp","objective-cpp":"objective-cpp"};function Uye(e){const t=String(e??"").trim();if(!t)return"";const[n=""]=t.split(/\s+/);return n.split(":")[0]?.trim().toLowerCase()??""}function aq(e){const t=Uye(e);return qye[t]??t}function Vye(e){if(!Array.isArray(e))return;const t=e.filter(i=>typeof i=="string").map(i=>aq(i)).filter(Boolean),n=Array.from(new Set(t)).sort();return n.length>0?n:void 0}function Kye(e){if(!Array.isArray(e))return;const t=[],n=new Set;for(const i of e){if(typeof i!="string")continue;const o=i.trim();!o||n.has(o)||(n.add(o),t.push(o))}return t.length>0?t:void 0}function Zye(e){return Kye(e)?.join("\0")??""}function Gye(e,t){return`${Zye(e)}\0\0${Vye(t)?.join("\0")??""}`}function a1(e,t,n=1){const i=Number(e);return Number.isFinite(i)?Math.max(n,i):t}function LN(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}var Qye=class{constructor(e={},t){this.source="",this.visible="",this.done=!1,this.paused=!1,this.listeners=new Set,this.rafId=0,this.startedAt=0,this.lastTick=0,this.charBudget=0,this.hasStarted=!1,this.destroyed=!1,this.getSnapshot=()=>({source:this.source,visible:this.visible,done:this.done,paused:this.paused,pendingChars:this.pendingChars,caughtUp:this.caughtUp,final:this.final}),this.subscribe=d=>this.destroyed?()=>{}:(this.listeners.add(d),()=>{this.listeners.delete(d)}),this.enqueue=d=>{if(this.destroyed||!d)return;this.done&&(this.done=!1);const f=this.source.length>0,h=this.pendingChars<=0;if(this.source+=d,h){const m=NN();this.startedAt=f&&this.hasStarted?m-this.normalizedStartDelayMs:m,this.lastTick=m,this.charBudget=0}this.hasStarted=!0,this.emit(),this.ensureLoop()},this.finish=(d={})=>{if(!this.destroyed){if(this.done=!0,d.flush??this.flushOnFinish){this.visible=this.source,this.charBudget=0,this.currentCps=this.minCharsPerSecond,this.cancelLoop(),this.emit();return}this.emit(),this.ensureLoop()}},this.flush=()=>{this.destroyed||(this.visible=this.source,this.charBudget=0,this.currentCps=this.minCharsPerSecond,this.cancelLoop(),this.emit())},this.reset=(d="")=>{this.destroyed||(this.cancelLoop(),this.source=d,this.visible=d,this.done=!1,this.paused=!1,this.hasStarted=!1,this.startedAt=0,this.lastTick=0,this.charBudget=0,this.currentCps=this.minCharsPerSecond,this.emit())},this.pause=()=>{this.destroyed||this.paused||(this.paused=!0,this.cancelLoop(),this.emit())},this.resume=()=>{if(this.destroyed||!this.paused)return;this.paused=!1;const d=NN();this.lastTick=d,this.startedAt||=d,this.emit(),this.ensureLoop()},this.destroy=()=>{this.destroyed||(this.destroyed=!0,this.cancelLoop(),this.listeners.clear())},this.dispose=()=>{this.destroy()},this.tick=d=>{if(this.rafId=0,this.destroyed||this.paused)return;if(this.pendingChars<=0){this.startedAt=0,this.lastTick=0,this.charBudget=0,this.currentCps=this.minCharsPerSecond;return}if(d-this.startedAtthis.normalizedCatchUpThreshold?this.normalizedCatchUpLatencyMs:this.normalizedTargetLatencyMs,y=e9e(m/Math.max(.001,g/1e3),this.minCharsPerSecond,this.maxCharsPerSecond);if(this.currentCps+=(y-this.currentCps)*.2,this.charBudget+=this.currentCps*(h/1e3),this.charBudget<1){this.ensureLoop();return}const k=Math.min(Math.floor(this.charBudget),this.maxCharsPerCommit),v=Xye(this.source.slice(this.visible.length),k,this.segmenter);v.text&&(this.visible+=v.text,this.charBudget=Math.max(0,this.charBudget-v.graphemeCount),this.emit()),this.ensureLoop()};const{minCharsPerSecond:n=40,maxCharsPerSecond:i=1e3,targetLatencyMs:o=900,catchUpLatencyMs:s=350,catchUpThreshold:r=600,maxCommitFps:l=30,startDelayMs:a=80,maxCharsPerCommit:u=80,flushOnFinish:c=!1}=e;this.minCharsPerSecond=a1(n,40,1),this.maxCharsPerSecond=Math.max(this.minCharsPerSecond,a1(i,1e3,1)),this.normalizedTargetLatencyMs=a1(o,900,1),this.normalizedCatchUpLatencyMs=a1(s,350,1),this.normalizedCatchUpThreshold=LN(r,600),this.normalizedStartDelayMs=LN(a,80),this.maxCommitFps=Math.trunc(a1(l,30,1)),this.maxCharsPerCommit=Math.trunc(a1(u,80,1)),this.flushOnFinish=c,this.segmenter=Jye(),t&&this.listeners.add(t),this.currentCps=this.minCharsPerSecond}get pendingChars(){return Math.max(0,this.source.length-this.visible.length)}get caughtUp(){return this.pendingChars===0}get final(){return this.done&&this.caughtUp}ensureLoop(){if(!(this.destroyed||this.rafId||this.paused||this.pendingChars<=0)){if(typeof requestAnimationFrame!="function"){this.flush();return}this.rafId=requestAnimationFrame(this.tick)}}cancelLoop(){this.rafId&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.rafId),this.rafId=0)}emit(){if(!this.destroyed)for(const e of this.listeners)e()}};function Yye(e={},t){const n=new Qye(e,t);return{getSnapshot:n.getSnapshot,subscribe:n.subscribe,enqueue:n.enqueue,finish:n.finish,flush:n.flush,reset:n.reset,pause:n.pause,resume:n.resume,destroy:n.destroy,dispose:n.dispose}}function Jye(){if(typeof Intl>"u")return null;const e=Intl.Segmenter;return e?new e(void 0,{granularity:"grapheme"}):null}function Xye(e,t,n){if(!e||t<=0)return{text:"",graphemeCount:0};if(!n){const s=Array.from(e).slice(0,t);return{text:s.join(""),graphemeCount:s.length}}let i="",o=0;for(const s of n.segment(e)){if(o>=t)break;i+=s.segment,o++}return{text:i,graphemeCount:o}}function NN(){return typeof performance<"u"?performance.now():Date.now()}function e9e(e,t,n){return Math.min(n,Math.max(t,e))}var t9e=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});const MA=Symbol.for("markstream-vue:node-lifecycle");function O8t(){}const Ox=new Map;let uq="material";const R1=new Map,FN=new Map;let TA=null;function n9e(e){Ox.set(e.id,e)}function i9e(e){const t=Ox.get(uq);if(!t)return;const n=t.core[e];if(n)return n;const i=R1.get(t.id);if(i){const o=i[e];if(o)return o}t.loadExtended&&!R1.has(t.id)&&s9e(t)}function o9e(){var e,t;return(t=(e=Ox.get(uq))==null?void 0:e.fallback)!=null?t:""}function s9e(e){return t9e(this,null,function*(){var t,n,i;if(R1.has(e.id))return(t=R1.get(e.id))!=null?t:null;let o=FN.get(e.id);return o||(o=((i=(n=e.loadExtended)==null?void 0:n.call(e))!=null?i:Promise.resolve(null)).then(s=>(R1.set(e.id,s),TA?.(),s)).catch(()=>(R1.set(e.id,null),null)),FN.set(e.id,o)),o})}const DN='',RN='',r9e={id:"material",core:{"":RN,plain:'',text:RN,javascript:'',typescript:'',jsx:'',tsx:'',html:'',css:'',scss:'',json:'',python:'',ruby:'',go:'',java:'',kotlin:'',c:'',cpp:'',cs:DN,csharp:DN,php:'',shell:'',powershell:'',sql:'',yaml:'',markdown:'',xml:'',rust:'',vue:'',mermaid:''},fallback:'',loadExtended:()=>qo(()=>import("./extended-p72mFE2C.js"),[]).then(e=>e.materialExtendedMap)},l9e=_u(0);TA=()=>{l9e.value++},n9e(r9e);const a9e={"":"",javascript:"javascript",js:"javascript",mjs:"javascript",cjs:"javascript",typescript:"typescript",ts:"typescript",jsx:"jsx",tsx:"tsx",golang:"go",py:"python",rb:"ruby",sh:"shell",bash:"shell",zsh:"shell",shellscript:"shell",bat:"shell",batch:"shell",ps1:"powershell",plaintext:"plain",text:"plain",txt:"plain","c++":"cpp","c#":"csharp",cs:"csharp","objective-c":"objectivec","objective-c++":"objectivecpp",yml:"yaml",md:"markdown",rs:"rust",kt:"kotlin"};function U4(e){var t;const n=(function(i){if(!i)return"";const o=i.trim();if(!o)return"";const[s]=o.split(/\s+/),[r]=s.split(":");return r.toLowerCase()})(e);return(t=a9e[n])!=null?t:n}function P8t(e){const t=U4(e);if(!t)return"plaintext";switch(t){case"plain":return"plaintext";case"jsx":return"javascript";case"tsx":return"typescript";case"objectivec":return"objective-c";case"objectivecpp":return"objective-cpp";default:return t}}function B8t(e){return i9e(U4(e))||o9e()}const ON={js:"JavaScript",javascript:"JavaScript",ts:"TypeScript",jsx:"JSX",tsx:"TSX",html:"HTML",css:"CSS",scss:"SCSS",json:"JSON",py:"Python",python:"Python",rb:"Ruby",go:"Go",java:"Java",c:"C",cpp:"C++",cs:"C#",csharp:"C#",php:"PHP",sh:"Shell",bash:"Bash",sql:"SQL",yaml:"YAML",md:"Markdown",d2:"D2",d2lang:"D2","":"Plain Text",plain:"Plain Text"};var V4=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});let Zr=null,Hh=!1,Wh=null,K4=Bx;function g2(e){var t;const n=(t=e?.default)!=null?t:e;return n&&typeof n.renderToString=="function"?n:null}function Px(){try{const e=globalThis;return g2(e?.katex)}catch{return null}}function Bx(){return V4(null,null,function*(){const e=Px();if(e)return e;const t=yield qo(()=>import("./katex-DnlPpQZa.js"),[]);try{yield qo(()=>import("./mhchem-DtR62fUK.js"),__vite__mapDeps([0,1]))}catch{}return g2(t)})}function cq(e){const t=Promise.resolve(e).then(n=>{var i;return Wh===t&&n?(Zr=(i=g2(n))!=null?i:n,Zr):null}).catch(()=>null).finally(()=>{Wh===t&&(Wh=null)});return Wh=t,Hh=!0,t}function u9e(e){K4=e,Zr=null,Hh=!1,Wh=null}function c9e(e){u9e(Bx)}function dq(){return typeof K4=="function"}function $8t(){var e;const t=K4;if(!t||t===Bx)return null;if(Zr)return Zr;const n=Px();if(n)return Zr=n,Zr;if(Hh)return null;try{const i=t();return i?typeof i?.then=="function"?(cq(i),null):(Zr=(e=g2(i))!=null?e:i,Zr):null}catch{return null}}function fq(){return V4(this,null,function*(){var e;const t=Px();if(t)return Zr=t,Zr;if(Zr)return Zr;if(Wh)return Wh;if(Hh)return null;const n=K4;if(!n)return Hh=!0,null;try{const i=n();if(typeof i?.then=="function")return cq(i);if(i)return Zr=(e=g2(i))!=null?e:i,Hh=!0,Zr}catch{}return Hh=!0,null})}function hq(e){return e?e.replace(/·/g,"⋅").replace(/℃/g,"°C"):""}let B9=null,Ch=null;const Vr=new Map,Zc=new Map;let Ov=5;const sp=new Set;function q0(){if(Vr.size{const{id:n,html:i,error:o}=t.data,s=Vr.get(n);if(s)if(Vr.delete(n),clearTimeout(s.timeoutId),s.cleanup(),q0(),o)s.aborted||s.reject(new Error(o));else{const{content:r,displayMode:l}=t.data;if(r){const a=`${l?"d":"i"}:${r}`;if(Zc.set(a,i),Zc.size>200){const u=Zc.keys().next().value;Zc.delete(u)}}s.aborted||s.resolve(i)}},B9.onerror=t=>{console.error("[katexWorkerClient] Worker error:",t);for(const[n,i]of Vr.entries())clearTimeout(i.timeoutId),i.cleanup(),i.aborted||i.reject(new Error(`Worker error: ${t.message}`));Vr.clear(),d9e()}}function h9e(e,t=!0,n=2e3,i){return V4(this,null,function*(){performance.now();const o=hq(e);if(!dq()){const a=new Error("KaTeX rendering disabled");return a.name="KaTeXDisabled",a.code="KATEX_DISABLED",Promise.reject(a)}if(Ch)return Promise.reject(Ch);const s=`${t?"d":"i"}:${o}`,r=Zc.get(s);if(r)return q0(),Promise.resolve(r);const l=B9||(Ch=new Error("[katexWorkerClient] No worker instance set. Please inject a Worker via setKaTeXWorker()."),Ch.name="WorkerInitError",Ch.code="WORKER_INIT_ERROR",null);if(!l)return Promise.reject(Ch);if(Vr.size>=Ov){const a=new Error("Worker busy");return a.name="WorkerBusy",a.code="WORKER_BUSY",a.busy=!0,a.inFlight=Vr.size,a.max=Ov,Promise.reject(a)}return new Promise((a,u)=>{if(i?.aborted){const g=new Error("Aborted");return g.name="AbortError",void u(g)}const c=Math.random().toString(36).slice(2);let d=null;const f=globalThis.setTimeout(()=>{const g=Vr.get(c);if(!g)return;Vr.delete(c),g.cleanup();const y=new Error("Worker render timed out");y.name="WorkerTimeout",y.code="WORKER_TIMEOUT",g.aborted||g.reject(y),q0()},n);d=()=>{const g=Vr.get(c);if(!g||g.aborted)return;g.aborted=!0,g.cleanup();const y=new Error("Aborted");y.name="AbortError",u(y)},i&&i.addEventListener("abort",d,{once:!0});const h=a,m=u;Vr.set(c,{resolve:g=>{h(g)},reject:g=>{m(g)},timeoutId:f,aborted:!1,cleanup:()=>{i&&d&&i.removeEventListener("abort",d),d=null}});try{l.postMessage({id:c,content:o,displayMode:t})}catch(g){const y=Vr.get(c);Vr.delete(c),clearTimeout(f),y?.cleanup(),y?.reject(g),q0()}})})}function z8t(e,t=!0,n){const i=`${t?"d":"i"}:${hq(e)}`;if(Zc.set(i,n),Zc.size>200){const o=Zc.keys().next().value;Zc.delete(o)}}const p9e="WORKER_BUSY";function m9e(e=2e3,t){return Vr.size{let o,s=!1,r=null,l=()=>{};const a=()=>{o&&globalThis.clearTimeout(o),sp.delete(l),t&&r&&t.removeEventListener("abort",r),r=null};l=()=>{s||(s=!0,a(),n())},sp.add(l),o=globalThis.setTimeout(()=>{if(s)return;s=!0,a();const u=new Error("Wait for worker slot timed out");u.name="WorkerBusyTimeout",u.code="WORKER_BUSY_TIMEOUT",i(u)},e),queueMicrotask(()=>q0()),t&&(r=()=>{if(s)return;s=!0,a();const u=new Error("Aborted");u.name="AbortError",i(u)},t.aborted?r():t.addEventListener("abort",r,{once:!0}))})}const Og={timeout:2e3,waitTimeout:1500,backoffMs:30,maxRetries:1};function j8t(e){return V4(this,arguments,function*(t,n=!0,i={}){var o,s,r,l;if(!dq()){const g=new Error("KaTeX rendering disabled");throw g.name="KaTeXDisabled",g.code="KATEX_DISABLED",g}const a=(o=i.timeout)!=null?o:Og.timeout,u=(s=i.waitTimeout)!=null?s:Og.waitTimeout,c=(r=i.backoffMs)!=null?r:Og.backoffMs,d=(l=i.maxRetries)!=null?l:Og.maxRetries,f=Number.isFinite(d)?Math.max(0,Math.min(Math.floor(d),8)):Og.maxRetries,h=i.signal;let m=0;for(;;){if(h?.aborted){const g=new Error("Aborted");throw g.name="AbortError",g}try{return yield h9e(t,n,a,h)}catch(g){if(g?.code!==p9e||m>=f)throw g;if(m++,yield m9e(u,h).catch(()=>{}),h?.aborted){const y=new Error("Aborted");throw y.name="AbortError",y}c>0&&(yield new Promise(y=>globalThis.setTimeout(y,c*m)))}}})}function O1(e){const t=typeof e=="number"?e:Number.parseFloat(String(e??""));return Number.isFinite(t)&&t>0?t:null}function g9e(e){var t;for(const n of e.split(/\r?\n/)){const i=n.trim();if(!i||i.startsWith("%%"))continue;const o=i.match(/^([A-Z][\w-]*)\b/i);return((t=o?.[1])==null?void 0:t.toLowerCase())||""}return""}function cb(e){const t=e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o&&!o.startsWith("%%")),n=Math.max(1,t.length),i=g9e(e);return i==="gantt"?220+28*n:i==="sequencediagram"?180+26*n:i==="classdiagram"||i==="statediagram"||i==="erdiagram"?180+24*n:i==="flowchart"||i==="graph"?170+28*n:200+22*n}function db(e){const t=e.split(/\r?\n/).filter(n=>/^\s*-\s+/.test(n)).length;return t>=3?500:t>0?280+60*t:360}function pq(e,t=360,n=500){return n==null?Math.max(t,e):Math.min(Math.max(t,e),n)}function fb(e,t=360,n=500){return pq(e,t,n)}function hb(e,t=360,n=500){return pq(e,t,n)}var v9e=Object.defineProperty,y9e=Object.defineProperties,k9e=Object.getOwnPropertyDescriptors,PN=Object.getOwnPropertySymbols,b9e=Object.prototype.hasOwnProperty,w9e=Object.prototype.propertyIsEnumerable,BN=(e,t,n)=>t in e?v9e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,mq=(e,t)=>{for(var n in t||(t={}))b9e.call(t,n)&&BN(e,n,t[n]);if(PN)for(var n of PN(t))w9e.call(t,n)&&BN(e,n,t[n]);return e},$N=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});const pb=()=>qo(()=>import("./mermaid.core-WW7RuneT.js").then(e=>e.bp),__vite__mapDeps([2,3]));let Fc=null,P1=pb,u0=null,EA=!1,LA=!1,c0=0;function C9e(e){P1=e,c0++,Fc=null,u0=null,EA=!1,LA=!1}function A9e(e){C9e(pb)}function zN(){return typeof P1=="function"}function jN(e){if(!e)return e;const t=e&&e.default?e.default:e;if(t&&(typeof t.render=="function"||typeof t.parse=="function"||typeof t.initialize=="function"))return t;if(t&&t.mermaidAPI&&(typeof t.mermaidAPI.render=="function"||typeof t.mermaidAPI.parse=="function")){const o=t.mermaidAPI;return n=mq({},t),i={render:o.render.bind(o),parse:o.parse?o.parse.bind(o):void 0,initialize:s=>typeof t.initialize=="function"?t.initialize(s):o.initialize?o.initialize(s):void 0},y9e(n,k9e(i))}var n,i;return e.mermaid&&typeof e.mermaid.render=="function"?e.mermaid:t}function HN(e){if(e)try{const t=e?.initialize;e.initialize=n=>{const i=mq({suppressErrorRendering:!0},n||{});return typeof t=="function"?t.call(e,i):e?.mermaidAPI&&typeof e.mermaidAPI.initialize=="function"?e.mermaidAPI.initialize(i):void 0}}catch{}}function H8t(){return $N(this,null,function*(){if(Fc)return Fc;const e=(function(){try{const i=globalThis;return jN(i?.mermaid)}catch{return null}})();if(e)return Fc=e,HN(Fc),Fc;const t=P1,n=c0;return t?t===pb&&EA?null:u0||(u0=$N(null,null,function*(){let i;try{i=yield t()}catch(o){if(t===pb)return n===c0&&t===P1&&(EA=!0,(function(s){LA||(LA=!0,console.warn('[markstream-vue] Optional dependency "mermaid" is not installed. Mermaid blocks will render as source.',s))})(o)),null;throw o}finally{n===c0&&t===P1&&(u0=null)}return n!==c0||t!==P1?null:i?(Fc=jN(i),HN(Fc),Fc):null}),u0):null})}let ju=null,Ah=null;const uu=new Map,xh=new Map;function h8(e){for(const t of uu.values())t.reject(e);uu.clear(),xh.clear()}let WN=5,qN=!1;const x9e="WORKER_BUSY",UN="MERMAID_DISABLED";function S9e(e){if(ju&&ju!==e){const n=new Error("Worker replaced");n.code="WORKER_REPLACED",h8(n)}ju=e,Ah=null;const t=e;ju.onmessage=n=>{if(ju!==t)return;const{id:i,ok:o,result:s,error:r}=n.data,l=uu.get(i);l&&(o===!1||r?l.reject(new Error(r||"Unknown error")):l.resolve(s))},ju.onerror=n=>{var i,o;if(ju===t)if(uu.size!==0){try{qN?console.error("[mermaidWorkerClient] Worker error:",n?.message||n):(o=console.debug)==null||o.call(console,"[mermaidWorkerClient] Worker error:",n?.message||n)}catch{}h8(new Error(`Worker error: ${n.message}`))}else(i=console.debug)==null||i.call(console,"[mermaidWorkerClient] Worker error (no pending):",n?.message||n)},ju.onmessageerror=n=>{var i,o;if(ju===t)if(uu.size!==0){try{qN?console.error("[mermaidWorkerClient] Worker messageerror:",n):(o=console.debug)==null||o.call(console,"[mermaidWorkerClient] Worker messageerror:",n)}catch{}h8(new Error("Worker messageerror"))}else(i=console.debug)==null||i.call(console,"[mermaidWorkerClient] Worker messageerror (no pending):",n)}}function gq(e,t,n,i){if(!zN()){const r=new Error("Mermaid rendering disabled");return r.name="MermaidDisabled",r.code=UN,Promise.reject(r)}const o=`${e}\0${t.theme}\0${n}\0${t.code}`;let s=xh.get(o);return s||(s=(function(r,l,a=1400){if(!zN()){const c=new Error("Mermaid rendering disabled");return c.name="MermaidDisabled",c.code=UN,Promise.reject(c)}if(Ah)return Promise.reject(Ah);const u=ju||(Ah=new Error("[mermaidWorkerClient] No worker instance set. Please inject a Worker via setMermaidWorker()."),Ah.name="WorkerInitError",Ah.code="WORKER_INIT_ERROR",null);if(!u)return Promise.reject(Ah);if(uu.size>=WN){const c=new Error("Worker busy");return c.name="WorkerBusy",c.code=x9e,c.inFlight=uu.size,c.max=WN,Promise.reject(c)}return new Promise((c,d)=>{const f=Math.random().toString(36).slice(2);let h,m=!1;const g=()=>{m||(m=!0,h!=null&&globalThis.clearTimeout(h),uu.delete(f))},y={resolve:k=>{g(),c(k)},reject:k=>{g(),d(k)}};uu.set(f,y);try{u.postMessage({id:f,action:r,payload:l})}catch(k){return uu.delete(f),void d(k)}h=globalThis.setTimeout(()=>{const k=new Error("Worker call timed out");k.name="WorkerTimeout",k.code="WORKER_TIMEOUT";const v=uu.get(f);v&&v.reject(k)},a)})})(e,t,n),xh.set(o,s),s.then(()=>{xh.get(o)===s&&xh.delete(o)},()=>{xh.get(o)===s&&xh.delete(o)})),(function(r,l){if(!l)return r;if(l.aborted){const a=new Error("Aborted");return a.name="AbortError",Promise.reject(a)}return new Promise((a,u)=>{let c=()=>{};const d=()=>l.removeEventListener("abort",c);c=()=>{d();const f=new Error("Aborted");f.name="AbortError",u(f)},l.addEventListener("abort",c,{once:!0}),r.then(f=>{d(),a(f)},f=>{d(),u(f)})})})(s,i)}function W8t(e,t,n=1400,i){return gq("canParse",{code:e,theme:t},n,i)}function q8t(e,t,n=1400,i){return gq("findPrefix",{code:e,theme:t},n,i)}var _9e=Object.defineProperty,I9e=Object.defineProperties,M9e=Object.getOwnPropertyDescriptors,VN=Object.getOwnPropertySymbols,T9e=Object.prototype.hasOwnProperty,E9e=Object.prototype.propertyIsEnumerable,KN=(e,t,n)=>t in e?_9e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Bt=(e,t)=>{for(var n in t||(t={}))T9e.call(t,n)&&KN(e,n,t[n]);if(VN)for(var n of VN(t))E9e.call(t,n)&&KN(e,n,t[n]);return e},Dn=(e,t)=>I9e(e,M9e(t)),io=(e,t,n)=>new Promise((i,o)=>{var s=a=>{try{l(n.next(a))}catch(u){o(u)}},r=a=>{try{l(n.throw(a))}catch(u){o(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,r);l((n=n.apply(e,t)).next())});const L9e="__global__",p8="__MARKSTREAM_VUE_CUSTOM_COMPONENTS_STORE__",NA=(()=>{const e=globalThis;if(e[p8])return e[p8];const t={scopedCustomComponents:{},revision:_u(0)};return e[p8]=t,t})(),ZN=NA.revision,N9e=Symbol("markstreamCustomComponents"),F9e=new Set(["text","paragraph","heading","code_block","list","list_item","blockquote","table","table_row","table_cell","definition_list","definition_item","footnote","footnote_reference","footnote_anchor","admonition","hardbreak","link","image","thematic_break","math_inline","math_block","strong","emphasis","strikethrough","highlight","insert","subscript","superscript","emoji","checkbox","checkbox_input","inline_code","html_inline","html_block","reference","mermaid","infographic","d2","vmr_container"]);function v2(e){return F9e.has(String(e).trim().toLowerCase())}function D9e(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}function m8(e={}){const t={};for(const[n,i]of Object.entries(e))if(i!=null){t[n]=i;for(const o of new Set([Va(n),Va(D9e(n))]))!o||v2(o)||Object.prototype.hasOwnProperty.call(t,o)||(t[o]=i)}return t}function vs(e){const t=en(N9e,null);return D(()=>{var n;return ZN.value,(function(i,o={}){return ZN.value,Bt(Bt(Bt({},m8(NA.scopedCustomComponents[L9e]||{})),m8(o)),m8((function(s){return s&&NA.scopedCustomComponents[s]||{}})(i)))})(e?.(),(n=t?.value)!=null?n:{})})}const R9e=["aria-label"],O9e={key:0,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",class:"checkbox-icon checkbox-unchecked"},P9e={key:1,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",class:"checkbox-icon checkbox-checked"},Ei=(e,t)=>{const n=e.__vccOpts||e;for(const[i,o]of t)n[i]=o;return n},ra=Ei(ot({__name:"CheckboxNode",props:{node:{}},setup:e=>(t,n)=>(b(),N("span",{class:"checkbox-node",role:"img","aria-label":e.node.checked?"checked":"unchecked"},[e.node.checked?(b(),N("svg",P9e,[...n[1]||(n[1]=[_("rect",{x:"3",y:"3",width:"18",height:"18",rx:"4",fill:"currentColor"},null,-1),_("path",{d:"M9 12l2 2 4-4",stroke:"hsl(var(--ms-background))","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round"},null,-1)])])):(b(),N("svg",O9e,[...n[0]||(n[0]=[_("rect",{x:"3",y:"3",width:"18",height:"18",rx:"4",stroke:"currentColor","stroke-width":"2"},null,-1)])]))],8,R9e))}),[["__scopeId","data-v-be21ab83"]]);ra.install=e=>{e.component(ra.__name,ra)};const B9e={class:"emoji-node"},Il=Ei(ot({__name:"EmojiNode",props:{node:{}},setup:e=>(t,n)=>(b(),N("span",B9e,B(e.node.name),1))}),[["__scopeId","data-v-de55dc97"]]);Il.install=e=>{e.component(Il.__name,Il)};const $9e=["id"],z9e=["title"],la=Ei(ot({__name:"FootnoteReferenceNode",props:{node:{}},setup(e){const t=`#fnref--${e.node.id}`;function n(){if(typeof document>"u")return;const i=document.querySelector(t);i?i.scrollIntoView({behavior:"smooth"}):console.warn(`Element with href: ${t} not found`)}return(i,o)=>(b(),N("sup",{id:`fnref-${e.node.id}`,class:"footnote-reference",onClick:n},[_("span",{href:t,title:`查看脚注 ${e.node.id}`,class:"footnote-link cursor-pointer"},"["+B(e.node.id)+"]",9,z9e)],8,$9e))}}),[["__scopeId","data-v-c1463a29"]]);la.install=e=>{e.component(la.__name,la)};const vq=(()=>{try{return!1}catch{}return!1})();function g8(e){vq&&console.warn(e)}function GN(e,t="safe",n){return Rx(e,t,n)}function yq(e){return kye(e)}function v8(e){return e===!0?"":e===!1?"false":e==null?null:String(e)}function $x(e,t="safe"){const n=String(e.tag||e.type||"").trim(),i=P9((o=e.attrs)?Array.isArray(o)?o.every(Array.isArray)?o.map(([r,l])=>[String(r),v8(l)]):o.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)&&"name"in r).map(r=>[String(r.name),v8(r.value)]):Object.entries(o).map(([r,l])=>[r,v8(l)]):null,t,n);var o;if(!i)return;const s=yq(W0(i));return Object.keys(s).length>0?s:void 0}function QN(e,t,n=!1){const i=Object.entries(t??{}),o=i.length>0?i.map(([s,r])=>r===""?` ${s}`:` ${s}="${r}"`).join(""):"";return n?`<${e}${o} />`:`<${e}${o}>`}function Pg(e,t){Array.isArray(t)?e.push(...t):t!=null&&e.push(t)}function y8(e,t,n,i,o,s,r=!1){const l=(function(d,f){return nq(d,f)})(e,i);if(f2.has(e.toLowerCase())||!l&&JW(e,s))return null;if(!l&&Dx(e,s))return r?[QN(e,t,!0)]:[QN(e,t),...n,``];const a=Rx(t,s,e),u=a.key,c=u!=null&&u!==""?u:o;if(l){const d=i[e]||i[e.toLowerCase()],f=yq(a);return Fn(d,Dn(Bt({},f),{key:c}),n.length>0?n:void 0)}return Fn(e,Dn(Bt({},a),{innerHTML:void 0,key:c}),n.length>0?n:void 0)}function kq(e,t){return Cye(e,t)}function mb(e,t,n="safe"){if(!e)return[];try{return(function(s,r,l="safe"){let a=0;const u=[],c=[];for(const d of s)if(d.type==="text")(u.length>0?u[u.length-1].children:c).push(d.content);else if(d.type==="self_closing"){const f=y8(d.tagName,d.attrs||{},[],r,"ms-html-"+a++,l,!0);Pg(u.length>0?u[u.length-1].children:c,f)}else if(d.type==="tag_open")u.push({tagName:d.tagName,children:[],attrs:d.attrs,autoKey:"ms-html-"+a++});else if(d.type==="tag_close"){const f=d.tagName.toLowerCase();let h=-1;for(let m=u.length-1;m>=0;m--)if(u[m].tagName.toLowerCase()===f){h=m;break}if(h!==-1)for(;u.length>h;){const m=u.pop(),g=y8(m.tagName,m.attrs||{},m.children,r,m.autoKey,l);u.length>0?Pg(u[u.length-1].children,g):Pg(c,g),m.tagName.toLowerCase()!==f&&u.length>h&&g8(`Auto-closing unclosed tag: <${m.tagName}>`)}else g8(`Ignoring closing tag with no matching opening tag: `)}for(;u.length>0;){const d=u.pop(),f=y8(d.tagName,d.attrs||{},d.children,r,d.autoKey,l);u.length>0?Pg(u[u.length-1].children,f):Pg(c,f),g8(`Auto-closing unclosed tag: <${d.tagName}>`)}return c})(iq(e),t,n)}catch(o){return i=o,vq&&console.error("Failed to parse HTML to VNodes:",i),null}var i}const j9e=["innerHTML"],aa=Ei(ot({__name:"HtmlInlineNode",props:{node:{},customId:{},htmlPolicy:{}},setup(e){const t=e,n=en("markstreamHtmlPolicy",void 0),i=D(()=>{var l,a;return(a=(l=t.htmlPolicy)!=null?l:n?.value)!=null?a:"safe"}),o=vs(()=>t.customId),s=ot({name:"DynamicRenderer",props:{nodes:{type:Array,required:!0}},render(){return this.nodes}}),r=D(()=>{const l=t.node.content;if(!l)return{mode:"html",content:""};if(i.value==="escape")return{mode:"html",content:lm(l,i.value)};if(t.node.loading&&!t.node.autoClosed)return{mode:"text",content:l};if(t.node.loading&&t.node.autoClosed){const u=mb(l,o.value,i.value);if(u!==null)return{mode:"dynamic",nodes:u}}if(!kq(l,o.value))return{mode:"html",content:lm(l,i.value)};const a=mb(l,o.value,i.value);return a===null?{mode:"html",content:lm(l,i.value)}:{mode:"dynamic",nodes:a}});return(l,a)=>r.value.mode==="dynamic"?(b(),N("span",{key:0,class:De(["html-inline-node",{"html-inline-node--loading":t.node.loading}])},[V(p(s),{nodes:r.value.nodes},null,8,["nodes"])],2)):r.value.mode==="text"?(b(),N("span",{key:1,class:De(["html-inline-node",{"html-inline-node--loading":t.node.loading}])},B(r.value.content),3)):(b(),N("span",{key:2,class:De(["html-inline-node",{"html-inline-node--loading":t.node.loading}]),innerHTML:r.value.content},null,10,j9e))}}),[["__scopeId","data-v-d17f12b0"]]);aa.install=e=>{e.component(aa.__name,aa)};const H9e={class:"inline-code"},W9e={key:0},Er=Ei(ot({__name:"InlineCodeNode",props:{node:{}},setup(e){const t=e,n=qm(),i=en("markstreamFade",void 0),o=en("markstreamTextStreamState",void 0),s=en("markstreamStreamVersion",void 0),r=D(()=>{const v=n.fade;return v===""||v===!0||v==="true"||v!==!1&&v!=="false"&&void 0}),l=D(()=>typeof r.value=="boolean"?r.value:typeof i?.value!="boolean"||i.value),a=D(()=>{var v;return String((v=t.node.code)!=null?v:"")}),u=D(()=>!l.value),c=D(()=>{var v;const C=(v=n["index-key"])!=null?v:n.indexKey;return C==null||C===""?"":String(C)}),d=q(t.node.code),f=q(""),h=q(0);let m;function g(){m?.(),m=void 0}function y(){g(),f.value&&(d.value=d.value+f.value,f.value="")}ze([()=>t.node.code,c,l],([v])=>{const C=String(v??""),w=c.value,M=lq({nextContent:C,persistedContent:w?o?.get(w):void 0,currentState:{settledContent:d.value,streamedDelta:f.value},typewriterEnabled:l.value});d.value=M.settledContent,f.value=M.streamedDelta,M.appended?(h.value+=1,(function(){if(!f.value||m||!s)return;const L=s.value;m=ze(()=>s.value,E=>{E!==L&&y()},{flush:"sync"})})()):f.value||g(),w&&o?.set(w,C)},{immediate:!0}),cd(g);const k=D(()=>h.value%2==0?"inline-code-stream-delta--a":"inline-code-stream-delta--b");return(v,C)=>(b(),N("code",H9e,[u.value?(b(),N(Le,{key:0},[Be(B(a.value),1)],64)):(b(),N(Le,{key:1},[d.value?(b(),N("span",W9e,B(d.value),1)):X("",!0),f.value?(b(),N("span",{key:1,class:De(["inline-code-stream-delta",[k.value]]),onAnimationend:y},B(f.value),35)):X("",!0)],64))]))}}),[["__scopeId","data-v-4e331c97"]]);Er.install=e=>{e.component(Er.__name,Er)};const FA=q(!1),YN=q(""),JN=q("top"),U0=q(null),V0=q(null),DA=q(null),RA=q(null),XN=q(null);let $9=null,z9=null,OA=0;function bq(){$9&&(clearTimeout($9),$9=null),z9&&(clearTimeout(z9),z9=null)}let Fy=!1,Dy=null,eF=!1;function q9e(e,t,n="top",i=!1,o,s){if(!e)return;const r=++OA;bq();const l=()=>io(null,null,function*(){var a,u;if(yield(function(){return io(this,null,function*(){if(!Fy&&!eF&&typeof document<"u"){Dy!=null||(Dy=io(null,null,function*(){const[{createApp:c,h:d},{default:f}]=yield Promise.all([qo(()=>import("./vue.runtime.esm-bundler-Dz1HMlA6.js"),[]),qo(()=>import("./Tooltip-Da35cfam.js"),[])]),h=document.createElement("div");h.setAttribute("data-singleton-tooltip","1"),document.body.appendChild(h),c({setup:()=>()=>{var m;return d(f,{visible:FA.value,"anchor-el":U0.value,content:YN.value,placement:JN.value,id:V0.value,originX:DA.value,originY:RA.value,isDark:(m=XN.value)!=null?m:void 0})}}).mount(h),Fy=!0}));try{yield Dy}catch(c){Fy=!1,Dy=null,eF=!0,console.warn("[markstream-vue] Failed to mount Tooltip component. Tooltips will be disabled.",c)}}})})(),Fy&&r===OA){V0.value=`tooltip-${Date.now()}-${Math.floor(1e3*Math.random())}`,U0.value=e,YN.value=t,JN.value=n,DA.value=(a=o?.x)!=null?a:null,RA.value=(u=o?.y)!=null?u:null,XN.value=typeof s=="boolean"?s:null,FA.value=!0;try{e.setAttribute("aria-describedby",V0.value)}catch{}}});i?l():$9=setTimeout(l,80)}function U9e(e=!1){OA+=1,bq();const t=()=>{if(U0.value&&V0.value)try{U0.value.removeAttribute("aria-describedby")}catch{}FA.value=!1,U0.value=null,V0.value=null,DA.value=null,RA.value=null};e?t():z9=setTimeout(t,120)}const V9e={"common.copy":"Copy","common.copied":"Copied","common.decrease":"Decrease","common.reset":"Reset","common.increase":"Increase","common.expand":"Expand","common.collapse":"Collapse","common.preview":"Preview","common.source":"Source","common.export":"Export","common.open":"Open","common.minimize":"Minimize","common.zoomIn":"Zoom in","common.zoomOut":"Zoom out","common.resetZoom":"Reset zoom","image.loadError":"Image failed to load","image.loading":"Loading image..."},K9e=Symbol("markstreamI18nFallback");function wq(e,t){var n;return(n=t?.[e])!=null?n:V9e[e]}const PA=(e,t)=>{var n;return(n=wq(e,t))!=null?n:(function(i){return(i.split(".").pop()||i).replace(/[_-]/g," ").replace(/([A-Z])/g," $1").replace(/\s+/g," ").replace(/\b\w/g,o=>o.toUpperCase()).trim()})(e)};function tF(e,t){return{t(n){const i=wq(n,t);if(e.te&&i!=null&&!e.te(n))return PA(n,t);const o=e.t(n);return o===n&&i!=null?PA(n,t):o}}}function Z9e(){const e=(function(){var n,i,o;try{const s=gs(),r=K9e,l=s?.provides,a=(n=s?.appContext)==null?void 0:n.provides;return(o=(i=l?.[r])!=null?i:a?.[r])!=null?o:null}catch{}return null})(),t=(function(){var n,i;try{const o=gs(),s=o?.proxy,r=s?.$t;if(typeof r=="function"){const u=s?.$te;return{t:r.bind(s),te:typeof u=="function"?u.bind(s):void 0}}const l=(i=(n=o?.appContext)==null?void 0:n.config)==null?void 0:i.globalProperties,a=l?.$t;if(typeof a=="function"){const u=l?.$te;return{t:a.bind(l),te:typeof u=="function"?u.bind(l):void 0}}}catch{}return null})();if(t)return tF(t,e);try{const n=globalThis.$vueI18nUse||null;if(n&&typeof n=="function")try{const i=n();if(i&&typeof i.t=="function")return tF({t:i.t.bind(i),te:typeof i.te=="function"?i.te.bind(i):void 0},e)}catch{}}catch{}return{t:n=>PA(n,e)}}const Cq=Symbol("ViewportPriority"),Aq=Symbol("ViewportPriorityOptions"),xq=Symbol("OffscreenHeavyNodeDeferral"),G9e=D(()=>!1),gp="400px";function zx(){return en(Aq,void 0)}function jx(){return en(xq,G9e)}function Q9e(e,t){var n,i;const o=typeof window<"u"&&typeof document<"u",s=typeof t=="boolean"?q(t):t,r=o?(n=window.requestIdleCallback)!=null?n:E=>window.setTimeout(()=>E({didTimeout:!0,timeRemaining:()=>0}),16):null,l=o?(i=window.cancelIdleCallback)!=null?i:E=>window.clearTimeout(E):null,a=new WeakMap;let u=1;const c=new Map,d=new Map,f=new Set;let h=null,m=null;function g(E){if(!E)return"viewport";let S=a.get(E);return S||(S=u++,a.set(E,S)),String(S)}function y(){if(h!=null){try{l?.(h)}catch{}h=null}}function k(E){if(E){const S=c.get(E);if(S&&!S.targets.size){try{S.io.disconnect()}catch{}c.delete(E)}}d.size||f.size||y()}function v(E){const S=d.get(E);if(!S)return;const x=c.get(S.bucketKey);if(!S.visible.value){S.visible.value=!0;try{S.resolve()}catch{}}try{x?.io.unobserve(E)}catch{}x?.targets.delete(E),d.delete(E),f.delete(E),k(S.bucketKey)}function C(){window.__MARKSTREAM_DISABLE_VIEWPORT_PRIORITY_IDLE_DRAIN__!==!0&&r&&h==null&&f.size&&(h=r(()=>{h=null;const E=f.values().next().value;E&&(f.delete(E),v(E),f.size&&C())},{timeout:1200}))}function w(E,S){if(!o||typeof IntersectionObserver>"u")return null;const x=(function(R,F){var P,z,W;return{root:(P=e?.(R??null))!=null?P:null,rootMargin:(z=F?.rootMargin)!=null?z:gp,threshold:(W=F?.threshold)!=null?W:0}})(E,S),A=[g((T=x).root),T.rootMargin,T.threshold].join("\0");var T;const I=c.get(A);if(I)return{key:A,bucket:I};let O;try{O=new IntersectionObserver(R=>{for(const F of R)(F.isIntersecting||F.intersectionRatio>0)&&v(F.target)},{root:x.root,rootMargin:x.rootMargin,threshold:x.threshold})}catch{return null}const H={io:O,targets:new Map};return c.set(A,H),{key:A,bucket:H}}function M(){if(o&&s.value)for(const[E,S]of Array.from(d.entries())){const x=w(E,S.opts);if(!x){v(E);continue}if(x.key===S.bucketKey)continue;const A=S.bucketKey,T=c.get(A);try{T?.io.unobserve(E)}catch{}T?.targets.delete(E),S.bucketKey=x.key,x.bucket.targets.set(E,S),x.bucket.io.observe(E),k(A)}}ze(s,E=>{if(!E){for(const S of Array.from(d.keys()))v(S);y()}},{flush:"sync"});const L=(E,S)=>{const x=q(!1);let A,T=!1;const I=new Promise(F=>{A=()=>{T||(T=!0,F())}}),O=()=>{const F=d.get(E);if(!F)return f.delete(E),void k();const P=c.get(F.bucketKey);try{P?.io.unobserve(E)}catch{}P?.targets.delete(E),d.delete(E),f.delete(E),k(F.bucketKey)};if(!o||!s.value)return x.value=!0,A(),{isVisible:x,whenVisible:I,destroy:O};const H=w(E,S);if(!H)return x.value=!0,A(),{isVisible:x,whenVisible:I,destroy:O};const R={resolve:A,visible:x,bucketKey:H.key,opts:S};return d.set(E,R),H.bucket.targets.set(E,R),H.bucket.io.observe(E),o&&m==null&&(m=window.requestAnimationFrame(()=>{m=null,M()})),S?.allowIdle!==!1&&(f.add(E),C()),{isVisible:x,whenVisible:I,destroy:O}};return L.refresh=M,Gn(Cq,L),L}function Hx(){var e,t;const n=en(Cq,void 0);if(n)return n;const i=new WeakMap,o=new Map,s=new Set;let r=null;const l=typeof window<"u"?(e=window.requestIdleCallback)!=null?e:h=>window.setTimeout(()=>h({didTimeout:!0,timeRemaining:()=>0}),16):null,a=typeof window<"u"?(t=window.cancelIdleCallback)!=null?t:h=>window.clearTimeout(h):null,u=()=>{if(r!=null){try{a?.(r)}catch{}r=null}},c=h=>{if(!h)return;const m=o.get(h);if(m&&!m.targets.size){try{m.io.disconnect()}catch{}o.delete(h)}},d=h=>{const m=i.get(h);if(!m)return;const g=o.get(m.bucketKey);if(!m.visible.value){m.visible.value=!0;try{m.resolve()}catch{}}try{g?.io.unobserve(h)}catch{}i.delete(h),g?.targets.delete(h),s.delete(h),c(m.bucketKey),s.size||u()},f=()=>{window.__MARKSTREAM_DISABLE_VIEWPORT_PRIORITY_IDLE_DRAIN__!==!0&&l&&r==null&&s.size&&(r=l(()=>{r=null;const h=s.values().next().value;h&&(s.delete(h),d(h),s.size&&f())},{timeout:1200}))};return(h,m)=>{const g=q(!1);let y,k=!1;const v=new Promise(M=>{y=()=>{k||(k=!0,M())}}),C=()=>{const M=i.get(h);if(!M)return s.delete(h),void(s.size||u());const L=o.get(M.bucketKey);try{L?.io.unobserve(h)}catch{}i.delete(h),L?.targets.delete(h),s.delete(h),c(M.bucketKey),s.size||u()},w=(M=>{var L,E;if(typeof window>"u"||typeof IntersectionObserver>"u")return null;const S=(O=>{var H,R;return[(H=O?.rootMargin)!=null?H:gp,(R=O?.threshold)!=null?R:0].join("\0")})(M),x=o.get(S);if(x)return{key:S,bucket:x};const A=(L=M?.rootMargin)!=null?L:gp;let T;try{T=new IntersectionObserver(O=>{for(const H of O)(H.isIntersecting||H.intersectionRatio>0)&&d(H.target)},{root:null,rootMargin:A,threshold:(E=M?.threshold)!=null?E:0})}catch{return null}const I={io:T,targets:new Set};return o.set(S,I),{key:S,bucket:I}})(m);return w?(i.set(h,{resolve:y,visible:g,bucketKey:w.key}),w.bucket.targets.add(h),w.bucket.io.observe(h),m?.allowIdle!==!1&&(s.add(h),f()),{isVisible:g,whenVisible:v,destroy:C}):(g.value=!0,y(),{isVisible:g,whenVisible:v,destroy:C})}}function Y9e(e,t){var n,i;const o=(i=(n=e.indexKey)!=null?n:t["index-key"])!=null?i:t.indexKey;return o==null||o===""?"":String(o)}const J9e=["data-markstream-viewport-pending"],X9e=["src","alt","title","loading","fetchpriority","decoding","tabindex","aria-label"],eke={key:1,class:"image-placeholder"},tke={key:1,class:"image-node__raw-text"},nke={key:2,class:"image-shimmer-overlay"},ike={key:1,class:"image-node__raw-text"},oke={key:3,class:"image-error"},df=Ei(ot({__name:"ImageNode",props:{node:{},fallbackSrc:{default:""},lazy:{type:Boolean,default:!1},usePlaceholder:{type:Boolean,default:!0}},emits:["load","error","click"],setup(e,{emit:t}){var n,i,o;const s=e,r=t,l=q(!1),a=q(!1),u=q(""),c=q("primary"),d=q(null),f=qm(),h=en(MA,null),m=Hx(),g=zx(),y=jx(),k=D(()=>AL(s.node.src)),v=D(()=>AL(s.fallbackSrc)),C=(o=(i=(n=gs())==null?void 0:n.vnode.el)==null?void 0:i.querySelector)==null?void 0:o.call(i,"img"),w=typeof window<"u"&&C?.getAttribute("src")===(k.value||v.value),M=q(typeof window>"u"||w||!y.value),L=_u(null);let E="",S=null;const x=D(()=>u.value),A=D(()=>!s.lazy),T=D(()=>typeof window<"u"&&y.value&&!w),I=D(()=>!T.value||M.value),O=D(()=>I.value?x.value:""),H=D(()=>{var Z,se;return(se=(Z=g?.value.heavyBlockMargin)!=null?Z:g?.value.rootMargin)!=null?se:gp}),R=D(()=>!s.node.loading&&c.value!=="failed"&&u.value.length>0),F=D(()=>c.value==="failed"),P=D(()=>(!A.value||T.value&&!M.value)&&!l.value&&!a.value&&c.value!=="failed"&&u.value.length>0),z=D(()=>Y9e(s,f));function W(Z=z.value){Z&&d.value&&h?.reportHeight(Z,d.value.offsetHeight)}function $(Z=z.value){Z&&ft(()=>{W(Z)})}function K(){S&&(clearTimeout(S),S=null)}function ne(){const Z=z.value;Z&&E!==Z&&(E&&h?.markSettled(E),K(),E=Z,h?.markPending(Z),typeof window<"u"&&(S=window.setTimeout(()=>{E===Z&&($(Z),G())},8e3)))}function G(){return io(this,null,function*(){const Z=E;Z&&(K(),E="",yield ft(),W(Z),h?.markSettled(Z))})}function te(){if(c.value==="primary"&&v.value&&v.value!==u.value)return c.value="fallback",u.value=v.value,l.value=!1,a.value=!1,void $();c.value="failed",a.value=!0,r("error",u.value),$()}function le(){l.value=!0,a.value=!1,r("load",x.value),$()}function ie(Z){Z.preventDefault(),l.value&&!a.value&&r("click",[Z,x.value])}const{t:_e}=Z9e();return ze([k,v,()=>s.node.loading],()=>(l.value=!1,a.value=!1,s.node.loading||k.value?(u.value=k.value,void(c.value="primary")):v.value?(u.value=v.value,void(c.value="fallback")):(u.value="",c.value="failed",void(a.value=!0))),{immediate:!0}),typeof window<"u"&&ze([d,T],([Z,se],he,Y)=>{var J;if((J=L.value)==null||J.destroy(),L.value=null,!se||M.value)return void(M.value=!0);if(!Z)return void(M.value=!1);let U=!0;const Q=m(Z,{rootMargin:H.value,allowIdle:!1});L.value=Q,M.value=Q.isVisible.value,Q.whenVisible.then(()=>{U&&L.value===Q&&(M.value=!0)}),Y(()=>{U=!1,Q.destroy(),L.value===Q&&(L.value=null)})},{immediate:!0}),ze([R,l,a,x,()=>s.lazy,I],([Z,se,he,Y,J,U])=>Z&&Y&&!he&&U?se?(G(),void $()):J?(ne(),void $()):void(se||he||ne()):(G(),void $()),{flush:"post",immediate:!0}),ii(()=>{var Z;(Z=L.value)==null||Z.destroy(),L.value=null,(function(){const se=E;se&&(K(),E="",h?.markSettled(se))})()}),(Z,se)=>{var he,Y,J,U,Q;return b(),N("span",{ref_key:"rootRef",ref:d,class:"image-node-container","data-markstream-viewport-pending":T.value&&!M.value?"true":void 0},[R.value?(b(),N("img",{key:0,src:O.value||void 0,alt:String((Y=(he=s.node.alt)!=null?he:s.node.title)!=null?Y:""),title:String((U=(J=s.node.title)!=null?J:s.node.alt)!=null?U:""),class:De(["image-node__img",{"is-loading":!A.value&&!l.value,"is-loaded":A.value||l.value,"has-natural-size":l.value,"cursor-pointer":l.value}]),loading:s.lazy?"lazy":void 0,fetchpriority:A.value?"high":void 0,decoding:A.value?"sync":"async",tabindex:l.value?0:-1,"aria-label":(Q=s.node.alt)!=null?Q:p(_e)("image.preview"),onError:te,onLoad:le,onClick:ie},null,42,X9e)):X("",!0),e.node.loading&&!a.value?(b(),N("span",eke,[s.usePlaceholder?Hn(Z.$slots,"placeholder",{key:0,node:s.node,displaySrc:x.value,imageLoaded:l.value,hasError:a.value,fallbackSrc:s.fallbackSrc,lazy:s.lazy},()=>[se[0]||(se[0]=_("span",{class:"image-shimmer"},null,-1))],!0):(b(),N("span",tke,B(e.node.raw),1))])):X("",!0),P.value&&!e.node.loading?(b(),N("span",nke,[s.usePlaceholder?Hn(Z.$slots,"placeholder",{key:0,node:s.node,displaySrc:x.value,imageLoaded:l.value,hasError:a.value,fallbackSrc:s.fallbackSrc,lazy:s.lazy},()=>[se[1]||(se[1]=_("span",{class:"image-shimmer"},null,-1))],!0):(b(),N("span",ike,B(e.node.raw),1))])):X("",!0),F.value?(b(),N("span",oke,[Hn(Z.$slots,"error",{node:s.node,displaySrc:x.value,imageLoaded:l.value,hasError:a.value,fallbackSrc:s.fallbackSrc,lazy:s.lazy},()=>[se[2]||(se[2]=_("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24"},[_("path",{fill:"currentColor",d:"M2 2h20v10h-2V4H4v9.586l5-5L14.414 14L13 15.414l-4-4l-5 5V20h8v2H2zm13.547 5a1 1 0 1 0 0 2a1 1 0 0 0 0-2m-3 1a3 3 0 1 1 6 0a3 3 0 0 1-6 0m3.625 6.757L19 17.586l2.828-2.829l1.415 1.415L20.414 19l2.829 2.828l-1.415 1.415L19 20.414l-2.828 2.829l-1.415-1.415L17.586 19l-2.829-2.828z"})],-1)),_("span",null,B(p(_e)("image.loadError")),1)],!0)])):X("",!0)],8,J9e)}}}),[["__scopeId","data-v-046e82ac"]]);df.install=e=>{e.component(df.__name,df)};const ske={key:2},yc=ot({__name:"NodeChildRenderer",props:{node:{},components:{},customId:{},indexKey:{},fallbackToText:{type:Boolean,default:!1}},setup(e){const t=e,n=vs(()=>t.customId),i=en("markstreamHtmlPolicy",void 0),o=en("markstreamNestedRendererProps",void 0),s=D(()=>{var m;return(m=i?.value)!=null?m:"safe"}),r=D(()=>{var m,g;const y=(m=o?.value)!=null?m:{};return Dn(Bt({},y),{customId:(g=t.customId)!=null?g:y.customId,htmlPolicy:s.value})}),l=Xu({loader:()=>Promise.resolve().then(()=>Xx),suspensible:!1}),a=D(()=>t.components[String(t.node.type)]),u=D(()=>!!(a.value&&n.value[t.node.type]&&!v2(String(t.node.type)))),c=D(()=>u.value?$x(t.node,s.value):void 0),d=D(()=>Array.isArray(t.node.children)&&t.node.children.length>0),f=D(()=>{var m;return String((m=t.node.content)!=null?m:"")}),h=D(()=>{var m,g;return String((g=(m=t.node.content)!=null?m:t.node.raw)!=null?g:"")});return(m,g)=>a.value&&u.value?(b(),fe(To(a.value),ci({key:0},c.value,{node:e.node,loading:e.node.loading,"index-key":e.indexKey,"custom-id":e.customId,"is-dark":r.value.isDark}),{default:de(()=>[d.value?(b(),fe(p(l),ci({key:0},r.value,{nodes:e.node.children,"index-key":e.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):f.value?(b(),fe(p(l),ci({key:1},r.value,{content:f.value,final:!e.node.loading,"index-key":`${e.indexKey||"child"}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):X("",!0)]),_:1},16,["node","loading","index-key","custom-id","is-dark"])):a.value?(b(),fe(To(a.value),{key:1,node:e.node,"custom-id":e.customId,"index-key":e.indexKey},null,8,["node","custom-id","index-key"])):e.fallbackToText?(b(),N("span",ske,B(h.value),1)):X("",!0)}}),nF=Object.freeze({enabled:!0,contextLineCount:2,minimumLineCount:4,revealLineCount:5});function rke(e){var t;if(typeof e=="boolean")return e;if(e&&typeof e=="object"){const n=e;return Dn(Bt(Bt({},nF),n),{enabled:(t=n.enabled)==null||t})}return Bt({},nF)}function Wx(e,t){if(e.renderSideBySide===!1)return!0;if(e.useInlineViewWhenSpaceIsLimited!==!0)return!1;const n=e.renderSideBySideInlineBreakpoint,i=typeof n=="number"&&Number.isFinite(n)?n:900;return t>0&&t<=i}function Sq(e){var t,n;const i=(n=(t=String(e??"").split(/\r?\n/,1)[0])==null?void 0:t.trim())!=null?n:"";if(i.length<3)return"";const o=i[0];if(o!=="`"&&o!=="~"||i[1]!==o||i[2]!==o)return"";let s=3;for(;i[s]===o;)s+=1;return i.slice(s).trim()}function iF(e){var t;return((t=String(e??"").trim().split(/\s+/,1)[0])!=null?t:"")==="diff"}function lke(e){var t;return e.diff===!0||iF(e.language)||iF(Sq(String((t=e.raw)!=null?t:"")))}function ake(e,t,n){const i=(function(o){const s=Sq(o);if(!s)return"";const r=s.split(/\s+/).filter(Boolean);if(!r.length)return"";const l=r[0]==="diff"?r.slice(1):r;for(const a of l){const u=a.includes(":")?a.slice(a.indexOf(":")+1):a;if(u&&/[./\\-]/.test(u))return u}return""})(e);return{title:i||t,caption:i?n?`Diff / ${t}`:t:""}}const uke=["aria-busy","aria-label","data-language","data-markstream-line-numbers"],cke={key:0,translate:"no",class:"markstream-pre__diff-code"},dke={class:"markstream-pre__diff-pane-content"},fke={class:"markstream-pre__diff-number","aria-hidden":"true"},hke={class:"markstream-pre__diff-content"},pke={class:"markstream-pre__diff-content-inner"},mke={key:0,class:"markstream-pre__line-numbers","aria-hidden":"true"},gke=["textContent"],vke=["textContent"],bl=ot({__name:"PreCodeNode",props:{node:{},loading:{type:Boolean},showLineNumbers:{type:Boolean},diffInline:{type:Boolean},diffHideUnchangedRegions:{type:[Boolean,Object]},reservedHeightPx:{}},setup(e){const t=e;function n(ie,_e){const Z=String(ie??"");return _e?Z:Z.replace(/\r\n$|\n$|\r$/,"")}const i=D(()=>{var ie,_e,Z;const se=String((_e=(ie=t.node)==null?void 0:ie.language)!=null?_e:"");return String((Z=String(se).split(/\s+/g)[0])!=null?Z:"").toLowerCase().replace(/[^\w-]/g,"")||"plaintext"}),o=D(()=>`language-${i.value}`),s=D(()=>{var ie;return t.loading===!0||((ie=t.node)==null?void 0:ie.loading)===!0}),r=D(()=>{var ie;return n((ie=t.node)==null?void 0:ie.code,s.value)});let l="",a=1;const u=D(()=>(function(ie){let _e=0,Z=1;ie.startsWith(l)&&(_e=l.length,Z=a,_e>0&&ie[_e-1]==="\r"&&ie[_e]===` +`&&_e++);for(let se=_e;ser.value.split(/\r\n|\n|\r/));let d=0,f="";const h=D(()=>{const ie=u.value;ie{var ie;return t.showLineNumbers===!0&&((ie=t.node)==null?void 0:ie.diff)===!0}),g=D(()=>m.value&&t.diffInline===!0),y=D(()=>{const ie=Number(t.reservedHeightPx);if(!Number.isFinite(ie)||ie<=0)return;const _e=`${Math.ceil(ie)}px`;return s.value?{maxHeight:_e,overflow:"auto"}:{height:_e,minHeight:_e,maxHeight:_e,overflow:"auto"}}),k=["diff ","index ","--- ","+++ ","@@ "];function v(ie){return String(ie??"").trim().length===0}function C(ie,_e="context",Z={}){const se=v(ie);return{code:ie,kind:se&&_e!=="hunk"&&_e!=="spacer"&&!Z.preserveBlankKind?"context":_e,empty:se}}function w(ie){const _e=n(ie,s.value);return _e?_e.split(/\r\n|\n|\r/):[]}function M(ie,_e){return!v(ie[_e])||_ek.some(Z=>_e.startsWith(Z)))}function x(ie,_e){return _e||!ie.startsWith(" ")||ie.startsWith(" ")?ie:` ${ie}`}function A(ie,_e){const Z=ie.length,se=_e.length,he=[];let Y=0;for(;Y=Y&&Q>=Y&&ie[U]===_e[Q];)J.unshift({originalIndex:U,modifiedIndex:Q}),U--,Q--;const ue=U-Y+1,me=Q-Y+1;if(ue<=0||me<=0||s.value||(ue+1)*(me+1)>15e5)return he.concat(J);const pe=me+1,ee=new Uint32Array((ue+1)*(me+1));for(let Ce=ue-1;Ce>=0;Ce--)for(let ve=me-1;ve>=0;ve--){const ce=Ce*pe+ve;if(ie[Y+Ce]===_e[Y+ve])ee[ce]=ee[(Ce+1)*pe+ve+1]+1;else{const Te=ee[(Ce+1)*pe+ve],ke=ee[Ce*pe+ve+1];ee[ce]=Te>=ke?Te:ke}}const re=[];let ge=0,ae=0;for(;ge=ee[ge*pe+ae+1]?ge++:ae++;return he.concat(re,J)}function T(ie){var _e;const Z=(function(){var Q,ue;const me=t.diffHideUnchangedRegions;if(me==null||me===!1)return null;const pe=me===!0?{}:me;return pe.enabled===!1?null:{contextLineCount:Math.max(0,Math.floor((Q=pe.contextLineCount)!=null?Q:2)),minimumLineCount:Math.max(1,Math.floor((ue=pe.minimumLineCount)!=null?ue:4))}})();if(!Z||ie.length<1||ie.length>2||ie.length===2&&ie[0].lines.length!==ie[1].lines.length)return ie;const se=ie[0].lines,he=(_e=ie[1])==null?void 0:_e.lines,Y=Q=>se[Q].kind==="context"&&(he===void 0||he[Q].kind==="context"&&se[Q].code===he[Q].code),J=[];let U=0;for(;U=Z.minimumLineCount){const me=Q+(Q===0?0:Z.contextLineCount),pe=ue-(ue===se.length?0:Z.contextLineCount);pe-me>=Z.minimumLineCount&&J.push({start:me,end:pe})}U===Q&&U++}return J.length?ie.map((Q,ue)=>{const me=[];let pe=0;for(const ee of J)me.push(...Q.lines.slice(pe,ee.start)),me.push({code:ue===0?"Unmodified lines":"",kind:"collapsed",empty:!1,key:`${Q.key}-collapsed-${ee.start}-${ee.end}`,number:""}),pe=ee.end;return me.push(...Q.lines.slice(pe)),Dn(Bt({},Q),{lines:me})}):ie}const I=D(()=>{var ie,_e,Z,se;if(!m.value)return[];const he=(function(ue){const me=ue.some(ee=>L(ee)),pe=ue.some(ee=>E(ee));return me&&pe||(function(){var ee,re,ge,ae;if(i.value==="diff")return!0;const Ce=(ae=(ge=String((re=(ee=t.node)==null?void 0:ee.raw)!=null?re:"").split(/\r?\n/,1)[0])==null?void 0:ge.trim())!=null?ae:"";return/^`{3,}\s*diff(?:\s|$)|^~{3,}\s*diff(?:\s|$)/.test(Ce)})()&&(me||pe)})(c.value),Y=(function(){var ue,me;return((ue=t.node)==null?void 0:ue.originalCode)!=null||((me=t.node)==null?void 0:me.updatedCode)!=null})();if(g.value){const ue=Y?(function(me,pe){const ee=w(me),re=w(pe),ge=A(ee,re);if(ge.length>0){const ke=[];let Ae=0,Ne=0;for(const Ze of ge){for(;Ae=Ce&&ce>=Ce&&ee[ve]===re[ce];)Te.unshift(Dn(Bt({},C(re[ce])),{key:`inline-suffix-${ce}`,number:ce+1})),ve--,ce--;for(let ke=Ce;ke<=ve;ke++)ae.push(Dn(Bt({},C(ee[ke],"removed",{preserveBlankKind:M(ee,ke)})),{key:`inline-removed-source-${ke}`,number:ke+1}));for(let ke=Ce;ke<=ce;ke++)ae.push(Dn(Bt({},C(re[ke],"added",{preserveBlankKind:M(re,ke)})),{key:`inline-added-source-${ke}`,number:ke+1}));return ae.concat(Te)})((ie=t.node)==null?void 0:ie.originalCode,(_e=t.node)==null?void 0:_e.updatedCode):(function(me){const pe=[];let ee=1,re=1;const ge=S(me);for(const[ae,Ce]of me.entries())if(Ce.startsWith("@@")){const ve=Ce.match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);ve&&(ee=Number(ve[1]),re=Number(ve[2])),pe.push(Dn(Bt({},C(Ce,"hunk")),{key:`inline-hunk-${ae}`,number:""}))}else if(L(Ce))pe.push(Dn(Bt({},C(x(Ce.slice(1),ge),"removed",{preserveBlankKind:!0})),{key:`inline-removed-${ae}`,number:ee++}));else if(E(Ce))pe.push(Dn(Bt({},C(x(Ce.slice(1),ge),"added",{preserveBlankKind:!0})),{key:`inline-added-${ae}`,number:re++}));else{const ve=ge&&Ce.startsWith(" ")?Ce.slice(1):Ce;pe.push(Dn(Bt({},C(ve)),{key:`inline-context-${ae}`,number:re})),ee++,re++}return pe})(c.value);return T([{key:"inline",className:"markstream-pre__diff-pane--inline",lines:ue}])}if(!he&&Y)return(function(ue,me){const pe=w(ue),ee=w(me),re=A(pe,ee),ge=[],ae=[];let Ce=0,ve=0,ce=0;const Te=(ke,Ae)=>{const Ne=Math.max(ke-Ce,Ae-ve);for(let Ze=0;ZeDn(Bt({},ue),{key:`original-${me}`,number:me+1}))},{key:"modified",className:"markstream-pre__diff-pane--modified",lines:U.map((ue,me)=>Dn(Bt({},ue),{key:`modified-${me}`,number:me+1}))}])}),O=D(()=>{var ie,_e;if(t.showLineNumbers!==!0)return;let Z=m.value?1:u.value;if(m.value){Z=Math.max(Z,w((ie=t.node)==null?void 0:ie.originalCode).length,w((_e=t.node)==null?void 0:_e.updatedCode).length);for(const he of I.value)for(const Y of he.lines)typeof Y.number=="number"&&(Z=Math.max(Z,Y.number))}const se=`${Math.max(2,String(Z).length)}ch`;return{"--markstream-pre-line-number-width":se,"--markstream-pre-diff-line-number-width":se,"--markstream-code-padding-left":"calc(var(--markstream-pre-line-number-padding-left, 2ch) + var(--markstream-pre-line-number-width, 2ch) + var(--markstream-pre-line-number-padding-right, 1ch) + var(--markstream-pre-line-number-separator-width, 2px) + var(--markstream-pre-line-number-gap-to-code, 1ch))"}}),H=D(()=>I.value.some(ie=>ie.lines.some(_e=>_e.kind==="collapsed"))),R=D(()=>{const ie=i.value;return ie?`Code block: ${ie}`:"Code block"}),F=q(null),P=q([]);let z=null,W=!1,$=null;function K(ie){const _e=Number.parseFloat(String(ie??""));return Number.isFinite(_e)&&_e>0?_e:0}function ne(ie,_e){var Z;if(!ie)return _e;if(ie.classList.contains("markstream-pre__diff-line--collapsed"))return 32;const se=ie.querySelector(".markstream-pre__diff-content"),he=se?.getBoundingClientRect(),Y=(Z=he?.height)!=null?Z:0;return Math.max(_e,Math.ceil(Y))}function G(){W||typeof window>"u"||(z!=null&&window.cancelAnimationFrame(z),z=window.requestAnimationFrame(()=>{z=null,W||(function(){var ie,_e;z=null;const Z=F.value;if(!Z||!m.value||g.value||!Z.classList.contains("is-wrap"))return void(P.value.length&&(P.value=[]));const se=(function(me){const pe=window.getComputedStyle(me),ee=K(pe.getPropertyValue("--markstream-pre-diff-line-height"));if(ee>0)return ee;const re=K(pe.lineHeight);return re>0?re:18})(Z),he=Array.from(Z.querySelectorAll(".markstream-pre__diff-pane--original .markstream-pre__diff-line")),Y=Array.from(Z.querySelectorAll(".markstream-pre__diff-pane--modified .markstream-pre__diff-line")),J=Math.max(he.length,Y.length),U=[];for(let me=0;me{const ee=ue[pe];return ee&&Math.abs(me.rowHeight-ee.rowHeight)<=.5&&Math.abs(me.originalHeight-ee.originalHeight)<=.5&&Math.abs(me.modifiedHeight-ee.modifiedHeight)<=.5})||(P.value=U)})()}))}function te(ie){$?.disconnect(),$=null,ie&&m.value&&!g.value&&typeof ResizeObserver<"u"&&($=new ResizeObserver(()=>{G()}),$.observe(ie))}function le(ie,_e){const Z=P.value[ie];if(!Z)return;const se=_e==="original"?Z.originalHeight:Z.modifiedHeight;return{"--markstream-pre-diff-synced-row-height":`${Math.ceil(Z.rowHeight)}px`,"--markstream-pre-diff-content-height":`${Math.ceil(se)}px`}}return ze(F,ie=>{te(ie),ft(()=>G())},{flush:"post"}),ze([m,g,I],()=>{te(F.value),ft(()=>G())},{flush:"post",immediate:!0}),ii(()=>{W=!0,z!=null&&(window.cancelAnimationFrame(z),z=null),$?.disconnect(),$=null}),(ie,_e)=>(b(),N("pre",{ref_key:"preRef",ref:F,style:on([y.value,O.value]),class:De([o.value,{"markstream-pre--line-numbers":t.showLineNumbers,"markstream-pre--diff-preview":m.value,"markstream-pre--diff-inline":g.value,"markstream-pre--diff-collapsed":H.value}]),"aria-busy":s.value,"aria-label":R.value,"data-language":i.value,"data-markstream-line-numbers":t.showLineNumbers?"1":void 0,"data-markstream-pre":"1",tabindex:"0"},[m.value?(b(),N("code",cke,[(b(!0),N(Le,null,Ct(I.value,Z=>(b(),N("span",{key:Z.key,class:De(["markstream-pre__diff-pane",Z.className])},[_("span",dke,[(b(!0),N(Le,null,Ct(Z.lines,(se,he)=>(b(),N("span",{key:se.key,class:De(["markstream-pre__diff-line",[`markstream-pre__diff-line--${se.kind}`,{"markstream-pre__diff-line--empty":se.empty}]]),style:on(le(he,Z.key))},[_e[0]||(_e[0]=_("span",{class:"markstream-pre__diff-rail","aria-hidden":"true"},null,-1)),_("span",fke,B(se.number),1),_("span",hke,[_("span",pke,B(se.code),1)])],6))),128))])],2))),128))])):(b(),N(Le,{key:1},[t.showLineNumbers?(b(),N("span",mke,[_("span",{class:"markstream-pre__line-numbers-text",textContent:B(h.value)},null,8,gke)])):X("",!0),_("code",{translate:"no",class:"markstream-pre__code",textContent:B(r.value)},null,8,vke)],64))],14,uke))}});bl.install=e=>{e.component(bl.__name,bl)};const Fo=Ei(ot({__name:"TextNode",props:{node:{}},emits:["copy"],setup(e){const t=e,n=qm(),i=en("markstreamFade",void 0),o=en("markstreamTextStreamState",void 0),s=en("markstreamStreamVersion",void 0),r=D(()=>{const M=n.fade;return M===""||M===!0||M==="true"||M!==!1&&M!=="false"&&void 0}),l=D(()=>typeof r.value=="boolean"?r.value:typeof i?.value!="boolean"||i.value),a=D(()=>{var M;const L=(M=n["index-key"])!=null?M:n.indexKey;return L==null||L===""?"":String(L)}),u=q(t.node.content),c=q(""),d=q(0),f=q(t.node.content);let h;const m=q(null),g=q(null);let y="",k=null;function v(){h?.(),h=void 0}function C(){v(),c.value&&(u.value=u.value+c.value,c.value="")}ze([u,m,g],function(){var M,L;const E=m.value;if(!E)return;const S=String((M=u.value)!=null?M:""),x=g.value;return k||(k=E.firstChild,y=(L=k?.data)!=null?L:""),S.startsWith(y)?!k&&S?(E.textContent=S,k=E.firstChild,void(y=S)):void(S.length>y.length&&x&&(x.appendChild(document.createTextNode(S.slice(y.length))),y=S)):(E.textContent=S,k=E.firstChild,x&&(x.textContent=""),void(y=S))},{immediate:!0}),ze([()=>t.node.content,a,l],([M])=>{const L=String(M??""),E=a.value,S=lq({nextContent:L,persistedContent:E?o?.get(E):void 0,currentState:{settledContent:u.value,streamedDelta:c.value},typewriterEnabled:l.value});u.value=S.settledContent,c.value=S.streamedDelta,S.appended?(d.value+=1,(function(){if(!c.value||h||!s)return;const x=s.value;h=ze(()=>s.value,A=>{A!==x&&C()},{flush:"sync"})})()):c.value||v(),E&&o?.set(E,L)},{immediate:!0}),cd(v);const w=D(()=>d.value%2==0?"text-node-stream-delta--a":"text-node-stream-delta--b");return(M,L)=>(b(),N("span",{class:De([[e.node.center?"text-node-center":""],"text-node"])},[si(_("span",{ref_key:"settledTextEl",ref:m},B(f.value),513),[[Eo,u.value!==""]]),si(_("span",{ref_key:"settledAppendsEl",ref:g},null,512),[[Eo,u.value!==""]]),c.value?(b(),N("span",{key:0,class:De(["text-node-stream-delta",[w.value]]),onAnimationend:C},B(c.value),35)):X("",!0)],2))}}),[["__scopeId","data-v-fd79037c"]]);function d0(e,t,n){return ot({name:e,inheritAttrs:!1,setup(i,{attrs:o,slots:s}){var r,l;const a=Hx(),u=zx(),c=jx(),d=typeof window<"u"&&((l=(r=gs())==null?void 0:r.vnode.el)==null?void 0:l.nodeType)===1,f=q(typeof window>"u"||d||!c.value),h=_u(null);let m=null;function g(y){const k=y&&"$el"in y?y.$el:y;h.value=k instanceof HTMLElement?k:null}return typeof window<"u"&&ze([h,c],([y,k],v,C)=>{if(m?.destroy(),m=null,!k||f.value)return void(f.value=!0);if(!y)return;let w=!0;const M=a(y,{rootMargin:u?.value.heavyBlockMargin,allowIdle:!1});m=M,f.value=M.isVisible.value,M.whenVisible.then(()=>{w&&m===M&&(f.value=!0)}),C(()=>{w=!1,M.destroy(),m===M&&(m=null)})},{immediate:!0}),ii(()=>{m?.destroy(),m=null}),()=>Fn(f.value?t:n,Dn(Bt({},o),{ref:g}),s)}})}Fo.install=e=>{e.component(Fo.__name,Fo)};const gb=ot({name:"CodeBlockNodeLoading",inheritAttrs:!1,props:["node","isDark","loading","stream","theme","darkTheme","lightTheme","isShowPreview","monacoOptions","enableFontSizeControl","minWidth","maxWidth","themes","showHeader","showCopyButton","showExpandButton","showPreviewButton","showCollapseButton","showFontSizeButtons","showTooltips","htmlPreviewAllowScripts","htmlPreviewSandbox","customId","estimatedHeightPx","estimatedContentHeightPx","estimatedDiffInline"],emits:["previewCode","copy"],setup(e,{attrs:t}){const n=e;return()=>{var i,o,s,r,l,a,u;const c=U4(String((o=(i=n.node)==null?void 0:i.language)!=null?o:"")),d=ON[c]||(c?c.charAt(0).toUpperCase()+c.slice(1):ON[""]),f=lke(n.node),h=ake(String((r=(s=n.node)==null?void 0:s.raw)!=null?r:""),d,f),m=n.monacoOptions,g=f&&((l=n.estimatedDiffInline)!=null?l:Wx(m??{},typeof window>"u"?0:window.innerWidth)),y=m?.diffAppearance,k=y==="dark"||y!=="light"&&n.isDark===!0,v=typeof m?.fontSize=="number"&&Number.isFinite(m.fontSize)&&m.fontSize>0?m.fontSize:12,C=typeof m?.lineHeight=="number"&&Number.isFinite(m.lineHeight)&&m.lineHeight>0?m.lineHeight:v===12?18:Math.max(12,Math.round(1.5*v)),w=typeof m?.tabSize=="number"&&Number.isFinite(m.tabSize)&&m.tabSize>0?m.tabSize:4,M=f?0:8,L=typeof((a=m?.padding)==null?void 0:a.top)=="number"&&Number.isFinite(m.padding.top)&&m.padding.top>=0?m.padding.top:M,E=typeof((u=m?.padding)==null?void 0:u.bottom)=="number"&&Number.isFinite(m.padding.bottom)&&m.padding.bottom>=0?m.padding.bottom:M,S=typeof m?.fontFamily=="string"?m.fontFamily.trim():"",x=Bt(Bt({fontSize:`${v}px`,lineHeight:`${C}px`,tabSize:w,paddingTop:`${L}px`,paddingBottom:`${E}px`,"--markstream-pre-line-number-top":`${L}px`},f?{"--markstream-pre-diff-line-height":`${C}px`}:{}),S?{"--markstream-code-font-family":S}:{}),A=()=>Fn("button",{class:"code-action-btn inline-flex items-center justify-center p-[var(--ms-action-btn-padding)] rounded leading-none shrink-0","aria-hidden":"true",disabled:!0,tabindex:-1,type:"button"},[Fn("svg",{class:"action-icon",width:"14",height:"14"})]),T=n.isShowPreview!==!1&&(c==="html"||c==="svg"),I=n.showFontSizeButtons!==!1&&n.enableFontSizeControl!==!1||n.showExpandButton!==!1||T&&n.showPreviewButton!==!1,O=R=>{if(R!=null)return typeof R=="number"?`${R}px`:String(R)},H=Bt(Bt(Bt({"--markstream-code-layout-character-width":"1ch"},O(n.minWidth)?{minWidth:O(n.minWidth)}:{}),O(n.maxWidth)?{maxWidth:O(n.maxWidth)}:{}),f?{}:{color:"var(--vscode-editor-foreground, var(--markstream-code-fallback-fg, var(--code-fg)))",backgroundColor:"var(--markstream-code-fallback-bg, var(--code-bg, #fff))",borderColor:"var(--markstream-code-border-color, var(--code-border))"});return Fn("div",Dn(Bt({},t),{class:["code-block-container","rounded-lg","border",{dark:n.isDark===!0,"is-rendering":n.loading!==!1,"is-dark":k,"is-diff":f,"is-plain-text":c===""||c==="plaintext"||c==="text"},t.class],style:[H,t.style],"data-markstream-code-block":"1","data-markstream-enhanced":"false","data-markstream-code-block-state":n.loading?"streaming":"settled","data-markstream-code-loading":"1"}),[n.showHeader===!1?null:Fn("div",{class:"code-block-header flex justify-between items-center border-b px-[var(--ms-inset-panel-x)] py-[var(--ms-inset-panel-y)] border-[var(--code-border)] bg-[var(--code-header-bg)] text-[var(--code-fg)]"},[Fn("div",{class:"code-header-main",style:{minWidth:0,flex:"1 1 auto",display:"flex",alignItems:"center",gap:"var(--ms-gap-header-main, 0.625rem)",overflow:"hidden"}},[Fn("span",{class:"icon-slot h-4 w-4 flex-shrink-0","aria-hidden":"true",style:{display:"inline-flex",width:"1rem",height:"1rem",flex:"0 0 auto"}}),Fn("div",{class:"code-header-copy",style:{minWidth:0,display:"grid",gap:"2px"}},[Fn("div",{class:"code-header-title",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"var(--ms-text-label, 0.75rem)",fontWeight:"500",color:"var(--code-action-fg)"}},h.title),h.caption?Fn("div",{class:"code-header-caption",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.75rem",color:"var(--code-line-number)"}},h.caption):null])]),Fn("div",{class:"flex items-center gap-0.5",style:{visibility:"hidden"}},[f?Fn("div",{class:"code-diff-stats","aria-hidden":"true"},[Fn("span",{class:"code-diff-stat removed"},"-0"),Fn("span",{class:"code-diff-stat added"},"+0")]):null,n.showCopyButton===!1?null:A(),n.showCollapseButton===!1?null:A(),I?Fn("div",{class:"relative"},[A()]):null])]),Fn("div",{class:"code-block-shell-content",style:n.stream!==!1||n.loading===!1?void 0:{display:"none"}},[Fn(bl,{node:n.node,loading:n.loading,showLineNumbers:!0,reservedHeightPx:f?void 0:n.estimatedContentHeightPx,diffInline:g,diffHideUnchangedRegions:f?rke(m?.diffHideUnchangedRegions):void 0,class:"code-pre-fallback",style:x,"data-markstream-code-loading":"1"})]),Fn("div",{class:"code-loading-placeholder",style:n.stream===!1&&n.loading!==!1?void 0:{display:"none"}},[Fn("div",{class:"loading-skeleton"},[Fn("div",{class:"skeleton-line"}),Fn("div",{class:"skeleton-line"}),Fn("div",{class:"skeleton-line short"})])]),Fn("span",{class:"sr-only","aria-live":"polite",role:"status"})])}}}),k8=d0("ViewportDeferredCodeBlockNode",Xu({loader:()=>io(null,null,function*(){try{return(yield qo(()=>import("./CodeBlockNode-Dh6YGbd1.js"),__vite__mapDeps([4,5]))).default}catch(e){return console.warn('[markstream-vue] Failed to load the enhanced CodeBlockNode chunk; falling back to preformatted code rendering. Enhanced code blocks require the optional "stream-diffs" peer (or "stream-monaco" as a fallback).',e),bl}}),loadingComponent:gb,delay:0,suspensible:!1}),gb),Iu=Xu(()=>io(null,null,function*(){var e;if(((e=(function(){const t=Reflect.get(globalThis,"process");return t?.env})())==null?void 0:e.NODE_ENV)==="test"&&typeof window<"u")return t=>{var n,i,o,s;return Fn(Fo,Dn(Bt({},t),{node:{type:"text",content:(i=t.node.raw)!=null?i:`$${(n=t.node.content)!=null?n:""}$`,raw:(s=t.node.raw)!=null?s:`$${(o=t.node.content)!=null?o:""}$`}}))};try{return yield fq(),(yield qo(()=>import("./index7-CreDRl0J.js"),[])).default}catch(t){console.warn('[markstream-vue] Optional peer dependencies for MathInlineNode are missing. Falling back to text rendering. To enable full math rendering features, please install "katex".',t)}return t=>{var n,i,o,s;return Fn(Fo,Dn(Bt({},t),{node:{type:"text",content:(i=t.node.raw)!=null?i:`$${(n=t.node.content)!=null?n:""}$`,raw:(s=t.node.raw)!=null?s:`$${(o=t.node.content)!=null?o:""}$`}}))}})),_q=Xu(()=>io(null,null,function*(){try{return yield fq(),(yield qo(()=>import("./index6-BTRYPHWD.js"),[])).default}catch(e){console.warn('[markstream-vue] Optional peer dependencies for MathBlockNode are missing. Falling back to text rendering. To enable full math rendering features, please install "katex".',e)}return e=>{var t,n,i,o;return Fn(Fo,Dn(Bt({},e),{node:{type:"text",content:(n=e.node.raw)!=null?n:`$$${(t=e.node.content)!=null?t:""}$$`,raw:(o=e.node.raw)!=null?o:`$$${(i=e.node.content)!=null?i:""}$$`}}))}})),Qr=Ei(ot({__name:"ReferenceNode",props:{node:{},messageId:{},threadId:{}},emits:["click","mouseEnter","mouseLeave"],setup:e=>(t,n)=>(b(),N("span",{class:"reference-node cursor-pointer text-xs rounded-md px-1.5 mx-0.5",role:"button",tabindex:"0",onClick:n[0]||(n[0]=i=>t.$emit("click",i,e.node.id,e.messageId,e.threadId)),onMouseenter:n[1]||(n[1]=i=>t.$emit("mouseEnter",i,e.node.id,e.messageId,e.threadId)),onMouseleave:n[2]||(n[2]=i=>t.$emit("mouseLeave",i,e.node.id,e.messageId,e.threadId))},B(e.node.id),33))}),[["__scopeId","data-v-775c65e4"]]);Qr.install=e=>{e.component(Qr.__name,Qr)};const yke={class:"superscript-node"},Ml=Ei(ot({__name:"SuperscriptNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,html_inline:aa,strong:Yr,emphasis:el,footnote_reference:la,strikethrough:Jr,highlight:ua,insert:El,subscript:Tl,emoji:Il,math_inline:Iu,reference:Qr},n.value));return(o,s)=>(b(),N("sup",yke,[(b(!0),N(Le,null,Ct(e.node.children,(r,l)=>(b(),fe(p(yc),{key:`${e.indexKey||"superscript"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"superscript"}-${l}`,"fallback-to-text":""},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-24160b22"]]);Ml.install=e=>{e.component(Ml.__name,Ml)};const kke={class:"subscript-node"},Tl=Ei(ot({__name:"SubscriptNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,html_inline:aa,strong:Yr,emphasis:el,footnote_reference:la,strikethrough:Jr,highlight:ua,insert:El,superscript:Ml,emoji:Il,math_inline:Iu,reference:Qr},n.value));return(o,s)=>(b(),N("sub",kke,[(b(!0),N(Le,null,Ct(e.node.children,(r,l)=>(b(),fe(p(yc),{key:`${e.indexKey||"subscript"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"subscript"}-${l}`,"fallback-to-text":""},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-197fa13b"]]);Tl.install=e=>{e.component(Tl.__name,Tl)};const bke={class:"strong-node"},Yr=Ei(ot({__name:"StrongNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,html_inline:aa,emphasis:el,strikethrough:Jr,highlight:ua,insert:El,subscript:Tl,superscript:Ml,emoji:Il,footnote_reference:la,math_inline:Iu,reference:Qr},n.value));return(o,s)=>(b(),N("strong",bke,[(b(!0),N(Le,null,Ct(e.node.children,(r,l)=>(b(),fe(p(yc),{key:`${e.indexKey||"strong"}-${l}`,components:i.value,node:r,"index-key":`${e.indexKey||"strong"}-${l}`,"custom-id":t.customId},null,8,["components","node","index-key","custom-id"]))),128))]))}}),[["__scopeId","data-v-a8647104"]]);Yr.install=e=>{e.component(Yr.__name,Yr)};const wke={class:"strikethrough-node"},Jr=Ei(ot({__name:"StrikethroughNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,html_inline:aa,strong:Yr,emphasis:el,highlight:ua,insert:El,subscript:Tl,superscript:Ml,emoji:Il,footnote_reference:la,math_inline:Iu,reference:Qr},n.value));return(o,s)=>(b(),N("del",wke,[(b(!0),N(Le,null,Ct(e.node.children,(r,l)=>(b(),fe(p(yc),{key:`${e.indexKey||"strikethrough"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"strikethrough"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-b7a531fa"]]);Jr.install=e=>{e.component(Jr.__name,Jr)};const Cke=["href","title","aria-label","aria-hidden","target","rel"],Ake=["aria-hidden"],xke={class:"link-text-wrapper relative inline-flex"},Ske={class:"leading-[normal] link-text"},Xr=Ei(ot({__name:"LinkNode",props:{node:{},indexKey:{},customId:{},showTooltip:{type:Boolean,default:!0},color:{},underlineHeight:{},underlineBottom:{},animationDuration:{},animationOpacity:{},animationTiming:{},animationIteration:{}},setup(e){const t=e,n=en("markstreamShowTooltips",void 0),i=D(()=>{const k=n?.value;return typeof k=="boolean"?k:t.showTooltip}),o=D(()=>{var k,v,C,w,M;const L=t.underlineBottom!==void 0?typeof t.underlineBottom=="number"?`${t.underlineBottom}px`:String(t.underlineBottom):"-3px",E=(k=t.animationOpacity)!=null?k:.35,S=Math.max(.12,Math.min(.5*E,E)),x={"--underline-height":`${(v=t.underlineHeight)!=null?v:2}px`,"--underline-bottom":L,"--underline-opacity":String(E),"--underline-rest-opacity":String(S),"--underline-duration":`${(C=t.animationDuration)!=null?C:1.6}s`,"--underline-timing":(w=t.animationTiming)!=null?w:"ease-in-out","--underline-iteration":typeof t.animationIteration=="number"?String(t.animationIteration):(M=t.animationIteration)!=null?M:"infinite"};return t.color&&(x["--link-color"]=t.color),x}),s=vs(()=>t.customId),r=D(()=>Bt({text:Fo,strong:Yr,strikethrough:Jr,emphasis:el,image:df,html_inline:aa,inline_code:Er},s.value)),l=qm(),a=D(()=>{var k,v;const C=(k=t.node)==null?void 0:k.attrs;if(!C||typeof C!="object")return{};const w={};if(Array.isArray(C))for(const M of C)Array.isArray(M)&&M[0]&&(w[String(M[0])]=String((v=M[1])!=null?v:""));else for(const[M,L]of Object.entries(C))M&&L!=null&&L!==!1&&(w[M]=L===!0?"":String(L));return GN(w,"safe","a")}),u=D(()=>Bt(Bt({},l),a.value)),c=D(()=>{var k,v;return GN({href:String((v=(k=t.node)==null?void 0:k.href)!=null?v:"")},"safe","a").href}),d=D(()=>{if(!c.value)return;const k=u.value.target;return(typeof k=="string"?k.trim():String(k??"").trim())||(lme(c.value)?"_blank":void 0)}),f=D(()=>{var k;return String((k=d.value)!=null?k:"").trim().toLowerCase()==="_blank"}),h=D(()=>{if(!c.value)return;const k=u.value.rel,v=new Set((typeof k=="string"?k:String(k??"")).split(/\s+/).filter(Boolean)),C=new Set(Array.from(v).filter(w=>w.toLowerCase()!=="opener"));return f.value&&(C.add("noopener"),C.add("noreferrer")),C.size>0?Array.from(C).join(" "):void 0}),m=D(()=>{const k=Bt({},u.value);return delete k.title,delete k.href,delete k.target,delete k.rel,k});function g(){i.value&&U9e()}const y=D(()=>{var k,v;const C=(k=t.node)==null?void 0:k.title;return typeof C=="string"&&C.trim().length>0?C:String((v=c.value)!=null?v:"")});return(k,v)=>{var C,w;return e.node.loading?(b(),N("span",ci({key:1,class:"link-loading inline-flex items-baseline gap-1.5","aria-hidden":e.node.loading?"false":"true"},p(l),{style:o.value}),[_("span",xke,[_("span",Ske,[V(p(Fo),{class:"leading-[normal] link-text",node:{type:"text",content:String((C=e.node.text)!=null?C:""),raw:String((w=e.node.text)!=null?w:"")},"index-key":`${e.indexKey||"link-text"}-loading`},null,8,["node","index-key"])]),v[1]||(v[1]=_("span",{class:"link-loading-indicator","aria-hidden":"true"},null,-1))])],16,Ake)):(b(),N("a",ci({key:0,class:"link-node",href:c.value,title:i.value?"":y.value,"aria-label":`Link: ${y.value}`,"aria-hidden":e.node.loading?"true":"false",target:d.value,rel:h.value},m.value,{style:o.value,onMouseenter:v[0]||(v[0]=M=>(function(L){var E,S,x,A;if(!i.value)return;const T=L,I=T?.clientX!=null&&T?.clientY!=null?{x:T.clientX,y:T.clientY}:void 0,O=((E=t.node)==null?void 0:E.title)||((S=c.value)!=null&&S.includes("xn--")&&((A=(x=t.node)==null?void 0:x.text)!=null&&A.includes("://"))?t.node.text:c.value)||"";q9e(L.currentTarget,O,"top",!1,I)})(M)),onMouseleave:g}),[(b(!0),N(Le,null,Ct(e.node.children,(M,L)=>(b(),fe(p(yc),{key:`${e.indexKey||"emphasis"}-${L}`,components:r.value,node:M,"custom-id":t.customId,"index-key":`${e.indexKey||"link-text"}-${L}`},null,8,["components","node","custom-id","index-key"]))),128))],16,Cke))}}}),[["__scopeId","data-v-367e6ca4"]]);Xr.install=e=>{e.component(Xr.__name,Xr)};const _ke={class:"insert-node"},El=Ei(ot({__name:"InsertNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,html_inline:aa,strong:Yr,emphasis:el,strikethrough:Jr,highlight:ua,subscript:Tl,superscript:Ml,emoji:Il,footnote_reference:la,math_inline:Iu,reference:Qr},n.value));return(o,s)=>(b(),N("ins",_ke,[(b(!0),N(Le,null,Ct(e.node.children,(r,l)=>(b(),fe(p(yc),{key:`${e.indexKey||"insert"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"insert"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-1e2c29d4"]]);El.install=e=>{e.component(El.__name,El)};const Ike={class:"highlight-node"},ua=Ei(ot({__name:"HighlightNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,html_inline:aa,strong:Yr,emphasis:el,strikethrough:Jr,insert:El,subscript:Tl,superscript:Ml,emoji:Il,footnote_reference:la,math_inline:Iu,reference:Qr},n.value));return(o,s)=>(b(),N("mark",Ike,[(b(!0),N(Le,null,Ct(e.node.children,(r,l)=>(b(),fe(p(yc),{key:`${e.indexKey||"highlight"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"highlight"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-7a62982a"]]);ua.install=e=>{e.component(ua.__name,ua)};const Mke={class:"emphasis-node"},el=Ei(ot({__name:"EmphasisNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,html_inline:aa,strong:Yr,strikethrough:Jr,highlight:ua,insert:El,subscript:Tl,superscript:Ml,emoji:Il,footnote_reference:la,math_inline:Iu,reference:Qr},n.value));return(o,s)=>(b(),N("em",Mke,[(b(!0),N(Le,null,Ct(e.node.children,(r,l)=>(b(),fe(p(yc),{key:`${e.indexKey||"emphasis"}-${l}`,components:i.value,node:r,"custom-id":t.customId,"index-key":`${e.indexKey||"emphasis"}-${l}`},null,8,["components","node","custom-id","index-key"]))),128))]))}}),[["__scopeId","data-v-2a5aafbf"]]);el.install=e=>{e.component(el.__name,el)};const Tke={class:"hard-break"},ff=Ei(ot({__name:"HardBreakNode",props:{node:{}},setup:e=>(t,n)=>(b(),N("br",Tke))}),[["__scopeId","data-v-50c58f70"]]);ff.install=e=>{e.component(ff.__name,ff)};const Pv=ot({__name:"SimpleInlineRenderer",props:{nodes:{},customId:{},indexKey:{}},setup(e){const t=e,n=Lt({checkbox:ra,checkbox_input:ra,emoji:Il,emphasis:el,hardbreak:ff,highlight:ua,inline_code:Er,insert:El,link:Xr,reference:Qr,strikethrough:Jr,strong:Yr,subscript:Tl,superscript:Ml,text:Fo}),i=vs(()=>t.customId),o=D(()=>{const s=i.value;return Object.keys(s).length>0?Bt(Bt({},n),s):n});return(s,r)=>(b(!0),N(Le,null,Ct(e.nodes,(l,a)=>(b(),fe(p(yc),{key:a,components:o.value,node:l,"custom-id":t.customId,"index-key":`${e.indexKey||"inline"}-${a}`},null,8,["components","node","custom-id","index-key"]))),128))}});function BA(e){if(!e||typeof e!="object")return!1;const t=`|${e.type}|`;if(!"|checkbox|checkbox_input|emoji|emphasis|hardbreak|highlight|inline_code|insert|link|reference|strikethrough|strong|subscript|superscript|text|".includes(t))return!1;if(!"|emphasis|highlight|insert|link|strikethrough|strong|subscript|superscript|".includes(t))return!0;const n=e.children;return Array.isArray(n)&&n.every(BA)}function vb(e,t=!0,n=!1){if(!e||!n&&e.length===0)return null;if(e.every(BA))return e;if(!t||e.length!==1)return null;const i=e[0];if(i?.type!=="paragraph"||!Array.isArray(i.children))return null;const o=i.children;return(n||o.length>0)&&o.every(BA)?o:null}function vp(e){var t,n;if(!e?.length)return null;let i="";for(const o of e){if(o?.type!=="text"||o.center===!0)return null;i+=String((n=(t=o.content)!=null?t:o.raw)!=null?n:"")}return i}const Eke=["cite"],Lke={key:0,dir:"auto",class:"paragraph-node"},Nke=["custom-id"],j9=Ei(ot({__name:"BlockquoteNode",props:{node:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},customId:{},showTooltips:{type:Boolean}},emits:["copy"],setup(e){const t=e,n=vs(()=>t.customId),i=D(()=>!!n.value.paragraph),o=D(()=>!!n.value.text),s=D(()=>vb(t.node.children,!i.value)),r=D(()=>t.fade!==!1||o.value?null:vp(s.value));return Gn("markstreamShowTooltips",D(()=>t.showTooltips)),Gn("markstreamFade",D(()=>t.fade)),(l,a)=>(b(),N("blockquote",{class:"blockquote blockquote-node",dir:"auto",cite:e.node.cite},[s.value?(b(),N("p",Lke,[r.value!==null?(b(),N("span",{key:0,class:"text-node","custom-id":t.customId},B(r.value),9,Nke)):(b(),fe(p(Pv),{key:1,nodes:s.value,"custom-id":t.customId,"index-key":`blockquote-${t.indexKey}-paragraph`},null,8,["nodes","custom-id","index-key"]))])):(b(),fe(p(Ll),{key:1,"show-tooltips":t.showTooltips,"index-key":`blockquote-${t.indexKey}`,nodes:t.node.children||[],"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:a[0]||(a[0]=u=>l.$emit("copy",u))},null,8,["show-tooltips","index-key","nodes","custom-id","typewriter","fade"]))],8,Eke))}}),[["__scopeId","data-v-abfecebc"]]);j9.install=e=>{e.component(j9.__name,j9)};const Fke={class:"definition-list"},Dke={class:"definition-term"},Rke={class:"definition-desc"},H9=Ei(ot({__name:"DefinitionListNode",props:{node:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},emits:["copy"],setup(e){const t=e;return(n,i)=>(b(),N("dl",Fke,[(b(!0),N(Le,null,Ct(t.node.items,(o,s)=>(b(),N(Le,{key:s},[_("dt",Dke,[V(p(Ll),{"index-key":`definition-term-${t.indexKey}-${s}`,nodes:o.term,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:i[0]||(i[0]=r=>n.$emit("copy",r))},null,8,["index-key","nodes","custom-id","typewriter","fade"])]),_("dd",Rke,[V(p(Ll),{"index-key":`definition-desc-${t.indexKey}-${s}`,nodes:o.definition,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:i[1]||(i[1]=r=>n.$emit("copy",r))},null,8,["index-key","nodes","custom-id","typewriter","fade"])])],64))),128))]))}}),[["__scopeId","data-v-4e103b30"]]);H9.install=e=>{e.component(H9.__name,H9)};const Oke=["href","title"],K0=Ei(ot({__name:"FootnoteAnchorNode",props:{node:{}},setup(e){const t=e;function n(i){var o;if(i.preventDefault(),typeof document>"u")return;const s=`fnref-${String((o=t.node.id)!=null?o:"")}`,r=document.getElementById(s);r&&r.scrollIntoView({behavior:"smooth",block:"center"})}return(i,o)=>(b(),N("a",{class:"footnote-anchor text-sm hover:underline cursor-pointer",href:`#fnref-${e.node.id}`,title:`返回引用 ${e.node.id}`,onClick:n}," ↩︎ ",8,Oke))}}),[["__scopeId","data-v-e1eb37b6"]]);K0.install=e=>{e.component(K0.__name,K0)};const Pke=["id"],Bke={class:"flex-1"},W9=ot({__name:"FootnoteNode",props:{node:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},emits:["copy"],setup(e){const t=e;return(n,i)=>(b(),N("div",{id:`fnref--${e.node.id}`,class:"footnote-node flex text-sm leading-relaxed border-t border-[var(--footnote-border)] pt-2"},[_("div",Bke,[V(p(Ll),{"index-key":`footnote-${t.indexKey}`,nodes:t.node.children,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,onCopy:i[0]||(i[0]=o=>n.$emit("copy",o))},null,8,["index-key","nodes","custom-id","typewriter","fade"])])],8,Pke))}});W9.install=e=>{e.component(W9.__name,W9)};const $ke=["custom-id"],$A=Ei(ot({__name:"HeadingNode",props:{node:{},customId:{},indexKey:{}},setup(e){const t=e,n=vs(()=>t.customId),i=en("markstreamFade",void 0),o=D(()=>i?.value!==!1||n.value.text?null:vp(t.node.children)),s=D(()=>Bt({text:Fo,inline_code:Er,link:Xr,image:df,strong:Yr,emphasis:el,strikethrough:Jr,highlight:ua,insert:El,subscript:Tl,superscript:Ml,emoji:Il,checkbox:ra,checkbox_input:ra,footnote_reference:la,hardbreak:ff,math_inline:Iu,reference:Qr},n.value));return(r,l)=>(b(),fe(To(`h${e.node.level}`),ci({class:["heading-node",[`heading-${e.node.level}`]],dir:"auto"},e.node.attrs),{default:de(()=>[o.value!==null?(b(),N("span",{key:0,class:"text-node","custom-id":t.customId},B(o.value),9,$ke)):(b(!0),N(Le,{key:1},Ct(e.node.children,(a,u)=>(b(),fe(p(yc),{key:u,components:s.value,"custom-id":t.customId,node:a,"index-key":`${e.indexKey||"heading"}-${u}`},null,8,["components","custom-id","node","index-key"]))),128))]),_:1},16,["class"]))}}),[["__scopeId","data-v-7122dbe1"]]),Z4=$A;Z4.install=e=>{e.component($A.__name,$A)};const zke={key:0,dir:"auto",class:"paragraph-node"},jke=["custom-id"],Hke={dir:"auto",class:"paragraph-node"},Wke=["custom-id"],am=Ei(ot({__name:"ListItemNode",props:{node:{},item:{},indexKey:{},customId:{},typewriter:{type:Boolean},fade:{type:Boolean},showTooltips:{type:Boolean},value:{},isDark:{type:Boolean}},emits:["copy"],setup(e){const t=e,n=D(()=>{var h;return(h=t.node)!=null?h:t.item}),i=vs(()=>t.customId),o=D(()=>!!i.value.paragraph),s=D(()=>!!i.value.text),r=D(()=>{var h;return vb((h=n.value)==null?void 0:h.children,!o.value)}),l=D(()=>{var h;if(o.value)return null;const m=(h=n.value)==null?void 0:h.children;if(!Array.isArray(m)||m.length<2)return null;const g=m[0];if(g?.type!=="paragraph"||!Array.isArray(g.children))return null;const y=m.slice(1);if(!y.every(v=>v?.type==="list"))return null;const k=vb([g]);return k?{paragraphChildren:k,nestedLists:y}:null});function a(){return t.fade===!1&&!s.value}const u=D(()=>a()?vp(r.value):null),c=D(()=>{var h;return a()?vp((h=l.value)==null?void 0:h.paragraphChildren):null}),d=Object.freeze({}),f=D(()=>{const{value:h}=t;return typeof h=="number"&&Number.isFinite(h)?{value:h}:d});return Gn("markstreamShowTooltips",D(()=>t.showTooltips)),Gn("markstreamFade",D(()=>t.fade)),(h,m)=>{var g,y;return b(),N("li",ci({class:"list-item",dir:"auto"},f.value),[r.value?(b(),N("p",zke,[u.value!==null?(b(),N("span",{key:0,class:"text-node","custom-id":t.customId},B(u.value),9,jke)):(b(),fe(p(Pv),{key:1,nodes:r.value,"custom-id":t.customId,"index-key":`list-item-${t.indexKey}-paragraph`},null,8,["nodes","custom-id","index-key"]))])):l.value?(b(),N(Le,{key:1},[_("p",Hke,[c.value!==null?(b(),N("span",{key:0,class:"text-node","custom-id":t.customId},B(c.value),9,Wke)):(b(),fe(p(Pv),{key:1,nodes:l.value.paragraphChildren,"custom-id":t.customId,"index-key":`list-item-${t.indexKey}-paragraph`},null,8,["nodes","custom-id","index-key"]))]),(b(!0),N(Le,null,Ct(l.value.nestedLists,(k,v)=>(b(),fe(p(Ll),{key:v,nodes:[k],"custom-id":t.customId,"index-key":`list-item-${t.indexKey}-nested-${v}`,"show-tooltips":t.showTooltips,typewriter:t.typewriter,fade:t.fade,"is-dark":t.isDark,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0,onCopy:m[0]||(m[0]=C=>h.$emit("copy",C))},null,8,["nodes","custom-id","index-key","show-tooltips","typewriter","fade","is-dark"]))),128))],64)):(b(),fe(p(Ll),{key:2,"show-tooltips":t.showTooltips,"index-key":`list-item-${t.indexKey}`,nodes:(y=(g=n.value)==null?void 0:g.children)!=null?y:[],"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,"is-dark":t.isDark,"batch-rendering":!1,onCopy:m[1]||(m[1]=k=>h.$emit("copy",k))},null,8,["show-tooltips","index-key","nodes","custom-id","typewriter","fade","is-dark"]))],16)}}}),[["__scopeId","data-v-617214f9"]]);am.install=e=>{e.component(am.__name,am)};const um=Ei(ot({__name:"ListNode",props:{node:{},customId:{},indexKey:{},typewriter:{type:Boolean},fade:{type:Boolean},showTooltips:{type:Boolean},isDark:{type:Boolean}},emits:["copy"],setup(e){const t=vs(()=>e.customId),n=D(()=>t.value.list_item||am);return(i,o)=>(b(),fe(To(e.node.ordered?"ol":"ul"),{class:De(["list-node",{"list-decimal":e.node.ordered,"list-disc":!e.node.ordered}])},{default:de(()=>[(b(!0),N(Le,null,Ct(e.node.items,(s,r)=>{var l;return b(),fe(To(n.value),ci({key:`${e.indexKey||"list"}-${r}`},{ref_for:!0},{showTooltips:e.showTooltips},{node:s,"custom-id":e.customId,"index-key":`${e.indexKey||"list"}-${r}`,typewriter:e.typewriter,fade:e.fade,"is-dark":e.isDark,value:e.node.ordered?((l=e.node.start)!=null?l:1)+r:void 0,onCopy:o[0]||(o[0]=a=>i.$emit("copy",a))}),null,16,["node","custom-id","index-key","typewriter","fade","is-dark","value"])}),128))]),_:1},8,["class"]))}}),[["__scopeId","data-v-99cb95e0"]]);um.install=e=>{e.component(um.__name,um)};const qke={key:2,class:"html-block-node__raw"},Uke=["innerHTML"],Vke={key:1,class:"html-block-node__placeholder"},Z0=Ei(ot({__name:"HtmlBlockNode",props:{node:{},customId:{},htmlPolicy:{}},setup(e){const t=e,n=en("markstreamHtmlPolicy",void 0),i=en("markstreamNestedRendererProps",void 0),o=D(()=>{var I,O;return(O=(I=t.htmlPolicy)!=null?I:n?.value)!=null?O:"safe"}),s=D(()=>{var I,O;const H=(I=i?.value)!=null?I:{};return Dn(Bt({},H),{customId:(O=t.customId)!=null?O:H.customId,htmlPolicy:o.value})}),r=Xu({loader:()=>Promise.resolve().then(()=>Xx),suspensible:!1}),l=D(()=>{const I=P9(t.node.attrs,o.value);if(!I)return;const O=W0(I);return Object.keys(O).length>0?O:void 0}),a=D(()=>{const I=String(t.node.tag||"").trim(),O=P9(t.node.attrs,o.value,I);if(!O)return;const H=W0(O);return Object.keys(H).length>0?H:void 0}),u=vs(()=>t.customId),c=ot({name:"DynamicRenderer",props:{nodes:{type:Array,required:!0}},render(){return this.nodes}}),d=q(null),f=q(typeof window>"u"),h=q(t.node.content),m=D(()=>Array.isArray(t.node.children)?t.node.children:[]),g=D(()=>String(t.node.tag||"div")),y=D(()=>{var I;if(g.value.trim().toLowerCase()!=="details"||(I=t.node.attrs)!=null&&I.some(([H])=>String(H).toLowerCase()==="open"))return null;const O=m.value[0];return O?.type==="html_block"&&String(O.tag||"").toLowerCase()==="summary"?O:null}),k=D(()=>{var I;return vp((I=y.value)==null?void 0:I.children)}),v=D(()=>{const I=y.value;if(!I)return;const O=P9(I.attrs,o.value,"summary");if(!O)return;const H=W0(O);return Object.keys(H).length>0?H:void 0}),C=D(()=>k.value==null?m.value:m.value.slice(1)),w=D(()=>{const I=g.value.trim().toLowerCase();return VH.has(I)||Dx(I,o.value)}),M=D(()=>m.value.length>0&&!!t.node.tag&&!w.value),L=D(()=>{var I,O,H;if(M.value)return{mode:"structured"};if(!f.value)return{mode:"html",content:(I=h.value)!=null?I:""};const R=(O=h.value)!=null?O:t.node.content;if(!R)return{mode:"html",content:""};if(o.value==="escape")return{mode:"html",content:lm(R,o.value)};if(t.node.loading){const P=mb(R,u.value,o.value);return P===null?{mode:"text",content:(H=t.node.raw)!=null?H:R}:{mode:"dynamic",nodes:P}}if(!kq(R,u.value))return{mode:"html",content:lm(R,o.value)};const F=mb(R,u.value,o.value);return F===null?{mode:"html",content:lm(R,o.value)}:{mode:"dynamic",nodes:F}}),E=Hx(),S=zx(),x=jx(),A=_u(null),T=!!t.node.loading;return typeof window<"u"?(ze([()=>d.value,()=>S?.value.heavyBlockMargin,()=>S?.value.rootMargin],([I],O,H)=>{var R,F,P,z;if((F=(R=A.value)==null?void 0:R.destroy)==null||F.call(R),A.value=null,!T)return f.value=!0,void(h.value=t.node.content);if(!I)return void(f.value=!1);let W=!0;const $=(z=(P=S?.value.heavyBlockMargin)!=null?P:S?.value.rootMargin)!=null?z:gp,K=E(I,{rootMargin:$,allowIdle:!x.value});A.value=K,f.value=f.value||K.isVisible.value,K.whenVisible.then(()=>{W&&A.value===K&&(f.value=!0)}),H(()=>{W=!1,K.destroy(),A.value===K&&(A.value=null)})},{immediate:!0}),ze(()=>t.node.content,I=>{T&&!f.value||(h.value=I)})):f.value=!0,ii(()=>{var I,O;(O=(I=A.value)==null?void 0:I.destroy)==null||O.call(I),A.value=null}),(I,O)=>(b(),fe(To(M.value?g.value:"div"),ci({ref_key:"htmlRef",ref:d,class:"html-block-node","data-markstream-viewport-pending":p(x)&&!f.value?"true":void 0},M.value?a.value:void 0),{default:de(()=>[f.value?(b(),N(Le,{key:0},[L.value.mode==="structured"?(b(),N(Le,{key:0},[k.value!==null?(b(),N(Le,{key:0},[_("summary",iJ(C$(v.value)),B(k.value),17),C.value.length?(b(),fe(p(r),ci({key:0},s.value,{nodes:C.value,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes"])):X("",!0)],64)):(b(),fe(p(r),ci({key:1},s.value,{nodes:m.value,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes"]))],64)):L.value.mode==="dynamic"?(b(),fe(p(c),{key:1,nodes:L.value.nodes},null,8,["nodes"])):L.value.mode==="text"?(b(),N("pre",qke,B(L.value.content),1)):(b(),N("div",ci({key:3},l.value,{innerHTML:L.value.content}),null,16,Uke))],64)):(b(),N("div",Vke,[Hn(I.$slots,"placeholder",{node:e.node},()=>[O[0]||(O[0]=_("span",{class:"html-block-node__placeholder-bar"},null,-1)),O[1]||(O[1]=_("span",{class:"html-block-node__placeholder-bar w-4/5"},null,-1)),O[2]||(O[2]=_("span",{class:"html-block-node__placeholder-bar w-2/3"},null,-1))],!0)]))]),_:3},16,["data-markstream-viewport-pending"]))}}),[["__scopeId","data-v-e140a874"]]);Z0.install=e=>{e.component(Z0.__name,Z0)};const Kke={dir:"auto",class:"paragraph-node"},Zke=["custom-id"],rp=Ei(ot({__name:"ParagraphNode",props:{node:{},customId:{},indexKey:{},customHtmlTags:{},parseOptions:{},customMarkdownIt:{type:Function}},setup(e){const t=e,n=vs(()=>t.customId),i=en("markstreamHtmlPolicy",void 0),o=en("markstreamFade",void 0),s=en("markstreamParseOptions",void 0),r=en("markstreamCustomMarkdownIt",void 0),l=en("markstreamNestedRendererProps",void 0),a=D(()=>{var S;return(S=i?.value)!=null?S:"safe"}),u=D(()=>{var S;return(S=t.parseOptions)!=null?S:s?.value}),c=D(()=>{var S;return(S=t.customMarkdownIt)!=null?S:r?.value}),d=D(()=>{var S,x;return(x=t.customHtmlTags)!=null?x:(S=l?.value)==null?void 0:S.customHtmlTags}),f=D(()=>{var S,x;const A=(S=l?.value)!=null?S:{};return Dn(Bt({},A),{customId:(x=t.customId)!=null?x:A.customId,customHtmlTags:d.value,parseOptions:u.value,customMarkdownIt:c.value,htmlPolicy:a.value})}),h=Xu({loader:()=>Promise.resolve().then(()=>Xx),suspensible:!1});function m(S){var x;return S.type==="text"&&String((x=S.content)!=null?x:"").trim()===""}const g=D(()=>t.node.children.filter(S=>!m(S))),y=D(()=>g.value.length>0&&g.value.every(S=>S.type==="image"||(function(x){var A;const T=(function(I){return I.type==="link"&&Array.isArray(I.children)?I.children.filter(O=>!m(O)):[]})(x);return T.length===1&&((A=T[0])==null?void 0:A.type)==="image"})(S))),k=D(()=>new Set(Np(d.value))),v=D(()=>{if(!y.value||g.value.length<=1)return t.node.children;const S=[];for(let x=0;x0,I=t.node.children.slice(x+1).some(O=>!m(O));T&&I&&S.push(Dn(Bt({},A),{content:" ",raw:" "}))}return S}),C=D(()=>o?.value===!1&&!n.value.text),w=D(()=>C.value?vp(v.value):null);function M(S,x){return{node:S,"index-key":`${t.indexKey}-${x}`,"custom-id":t.customId,"custom-html-tags":d.value}}const L=D(()=>Bt({inline_code:Er,image:df,link:Xr,hardbreak:ff,emphasis:el,strong:Yr,strikethrough:Jr,highlight:ua,insert:El,subscript:Tl,superscript:Ml,html_inline:aa,html_block:Z0,emoji:Il,checkbox:ra,math_inline:Iu,checkbox_input:ra,reference:Qr,footnote_anchor:K0,footnote_reference:la,text:Fo},n.value)),E=D(()=>v.value.map((S,x)=>{var A;const T=(function(I){var O,H,R,F;if(I.type==="html_block"||I.type==="html_inline"){const P=String((O=I.tag)!=null?O:"").trim().toLowerCase()||YH(I.content);if(P&&!k.value.has(P)&&JH((H=I.content)!=null?H:I.raw,P)){const z=String((F=(R=I.content)!=null?R:I.raw)!=null?F:"");return{child:{type:"text",content:z,raw:z},component:Fo,isCustomComponent:!1}}}return{child:I,component:L.value[I.type],isCustomComponent:!!(n.value[I.type]&&!v2(String(I.type)))}})(S);return Dn(Bt({},T),{index:x,key:`${t.indexKey||"paragraph"}-${x}`,customAttrs:T.isCustomComponent?$x(T.child,a.value):void 0,hasSlotChildren:Array.isArray(T.child.children)&&T.child.children.length>0,slotContent:String((A=T.child.content)!=null?A:""),originalChild:S})}));return(S,x)=>(b(),N("p",Kke,[w.value!==null?(b(),N("span",{key:0,class:"text-node","custom-id":t.customId},B(w.value),9,Zke)):(b(!0),N(Le,{key:1},Ct(E.value,A=>{return b(),N(Le,{key:A.key},[y.value&&m(A.originalChild)?(b(),N(Le,{key:0},[Be(B((T=A.originalChild,String((I=T.content)!=null?I:""))),1)],64)):A.isCustomComponent?(b(),fe(To(A.component),ci({key:1,ref_for:!0},A.customAttrs,{node:A.child,loading:A.child.loading,"index-key":A.key,"custom-id":t.customId,"custom-html-tags":d.value,"is-dark":f.value.isDark}),{default:de(()=>[A.hasSlotChildren?(b(),fe(p(h),ci({key:0,ref_for:!0},f.value,{nodes:A.child.children,"index-key":A.key,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):A.slotContent?(b(),fe(p(h),ci({key:1,ref_for:!0},f.value,{content:A.slotContent,final:!A.child.loading,"index-key":`${A.key}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):X("",!0)]),_:2},1040,["node","loading","index-key","custom-id","custom-html-tags","is-dark"])):(b(),fe(To(A.component),ci({key:2,ref_for:!0},M(A.child,A.index)),null,16))],64);var T,I}),128))]))}}),[["__scopeId","data-v-c59ff506"]]);rp.install=e=>{e.component(rp.__name,rp)};const Gke={class:"table-node-wrapper"},Qke=["aria-busy"],Yke={key:0},Jke=["custom-id"],Xke=["aria-label","onPointerdown"],ebe=["custom-id"],tbe={key:0,class:"table-node__loading",role:"status","aria-live":"polite"},G0=Ei(ot({__name:"TableNode",props:{node:{},indexKey:{},isDark:{type:Boolean},typewriter:{type:Boolean},fade:{type:Boolean},customId:{},showTooltips:{type:Boolean}},emits:["copy"],setup(e){const t=e,n=D(()=>{var k;return(k=t.node.loading)!=null&&k}),i=D(()=>{var k;return(k=t.node.rows)!=null?k:[]}),o=q(null),s=q([]);let r=null;const l=D(()=>t.node.header.cells.length),a=D(()=>s.value.some(k=>Number.isFinite(k)&&k>0)),u=D(()=>a.value?s.value.map(k=>k>0?{width:`${k}px`}:void 0):[]);Gn("markstreamShowTooltips",D(()=>t.showTooltips)),Gn("markstreamFade",D(()=>t.fade));const c=vs(()=>t.customId),d=D(()=>!!c.value.text),f=D(()=>!!c.value.paragraph),h=new WeakMap;function m(k){const v=t.fade===!1&&!d.value,C=!f.value,w=h.get(k);if(w?.children===k.children&&w.textFastPath===v&&w.paragraphFastPath===C)return w.info;const M=vb(k.children,C,!0),L={simpleChildren:M,plainText:M&&v?vp(M):null};return h.set(k,{children:k.children,textFastPath:v,paragraphFastPath:C,info:L}),L}function g(k){if(!r)return;k.preventDefault();const v=r.startWidth+r.nextStartWidth,C=Math.min(48,Math.floor(v/2)),w=Math.max(C,Math.min(v-C,Math.round(r.startWidth+k.clientX-r.startX))),M=[...r.widths];M[r.index]=w,M[r.index+1]=v-w,s.value=M}function y(){r&&(window.removeEventListener("pointermove",g),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),r=null)}return ze(l,()=>{y(),s.value=[]}),ii(y),(k,v)=>(b(),N("div",Gke,[_("table",{ref_key:"tableRef",ref:o,class:De(["table-node",{"table-node--loading":n.value}]),"aria-busy":n.value},[a.value?(b(),N("colgroup",Yke,[(b(!0),N(Le,null,Ct(e.node.header.cells,(C,w)=>(b(),N("col",{key:w,style:on(u.value[w])},null,4))),128))])):X("",!0),_("thead",null,[_("tr",null,[(b(!0),N(Le,null,Ct(e.node.header.cells,(C,w)=>(b(),N("th",{key:w,dir:"auto",class:De([C.align==="right"?"text-right":C.align==="center"?"text-center":"text-left"])},[m(C).plainText!==null?(b(),N("span",{key:0,class:"text-node","custom-id":t.customId},B(m(C).plainText),9,Jke)):m(C).simpleChildren?(b(),fe(p(Pv),{key:1,nodes:m(C).simpleChildren,"custom-id":t.customId,"index-key":`table-th-${t.indexKey}-${w}`},null,8,["nodes","custom-id","index-key"])):(b(),fe(p(Ll),{key:2,nodes:C.children,"index-key":`table-th-${t.indexKey}`,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,"show-tooltips":t.showTooltips,onCopy:v[0]||(v[0]=M=>k.$emit("copy",M))},null,8,["nodes","index-key","custom-id","typewriter","fade","show-tooltips"])),w(function(L,E){if(E.button!==0)return;const S=(function(){var T;const I=(T=o.value)==null?void 0:T.querySelectorAll("thead th");return Array.from(I??[],O=>Math.round(O.getBoundingClientRect().width))})(),x=S[L],A=S[L+1];x&&A&&(E.preventDefault(),r={index:L,startX:E.clientX,startWidth:x,nextStartWidth:A,widths:S},s.value=S,window.addEventListener("pointermove",g),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y))})(w,M)},null,40,Xke)):X("",!0)],2))),128))])]),_("tbody",null,[(b(!0),N(Le,null,Ct(i.value,(C,w)=>(b(),N("tr",{key:w},[(b(!0),N(Le,null,Ct(C.cells,(M,L)=>(b(),N("td",{key:L,class:De([M.align==="right"?"text-right":M.align==="center"?"text-center":"text-left"]),dir:"auto"},[m(M).plainText!==null?(b(),N("span",{key:0,class:"text-node","custom-id":t.customId},B(m(M).plainText),9,ebe)):m(M).simpleChildren?(b(),fe(p(Pv),{key:1,nodes:m(M).simpleChildren,"custom-id":t.customId,"index-key":`table-td-${t.indexKey}-${w}-${L}`},null,8,["nodes","custom-id","index-key"])):(b(),fe(p(Ll),{key:2,nodes:M.children,"index-key":`table-td-${t.indexKey}`,"custom-id":t.customId,typewriter:t.typewriter,fade:t.fade,"show-tooltips":t.showTooltips,onCopy:v[1]||(v[1]=E=>k.$emit("copy",E))},null,8,["nodes","index-key","custom-id","typewriter","fade","show-tooltips"]))],2))),128))]))),128))])],10,Qke),V(mo,{name:"table-node-fade"},{default:de(()=>[n.value?(b(),N("div",tbe,[Hn(k.$slots,"loading",{isLoading:n.value},()=>[v[2]||(v[2]=_("span",{class:"table-node__spinner animate-spin","aria-hidden":"true"},null,-1)),v[3]||(v[3]=_("span",{class:"sr-only"},"Loading",-1))],!0)])):X("",!0)]),_:3})]))}}),[["__scopeId","data-v-39f87b5d"]]);G0.install=e=>{e.component(G0.__name,G0)};const nbe={class:"hr-node"},q9=Ei({},[["render",function(e,t){return b(),N("hr",nbe)}],["__scopeId","data-v-39b2349c"]]);q9.install=e=>{e.component(q9.__name,q9)};const ibe={class:"unknown-node"},zA=ot({__name:"FallbackComponent",props:{node:{}},setup:e=>(t,n)=>(b(),N("div",ibe,B(e.node.raw),1))}),U9=Ei(ot({__name:"VmrContainerNode",props:{node:{},indexKey:{},isDark:{type:Boolean},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},setup(e){const t=e,n=D(()=>`vmr-container vmr-container-${t.node.name}`),i=vs(()=>t.customId),o=D(()=>Bt({text:Fo,paragraph:rp,heading:Z4,inline_code:Er,link:Xr,image:df,strong:Yr,emphasis:el,strikethrough:Jr,insert:El,subscript:Tl,superscript:Ml,checkbox:ra,checkbox_input:ra,hardbreak:ff,math_inline:Iu,reference:Qr,list:um,math_block:_q,table:G0},i.value));return(s,r)=>(b(),N("div",ci({class:n.value},e.node.attrs),[(b(!0),N(Le,null,Ct(e.node.children,(l,a)=>{return b(),fe(To((u=l.type,o.value[u]||zA)),{key:`${e.indexKey||"vmr-container"}-${a}`,"custom-id":t.customId,node:l,"index-key":`${e.indexKey||"vmr-container"}-${a}`,typewriter:t.typewriter,fade:t.fade},null,8,["custom-id","node","index-key","typewriter","fade"]);var u}),128))],16))}}),[["__scopeId","data-v-911e41c4"]]);U9.install=e=>{e.component(U9.__name,U9)};const obe=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","ON","ON","ET","ET","ET","ON","ON","ON","ON","ON","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","ON","ET","ET","ET","ET","ON","ON","ON","ON","L","ON","ON","BN","ON","ON","ET","ET","EN","EN","ON","L","ON","ON","ON","EN","L","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L"],oF=[[697,698,"ON"],[706,719,"ON"],[722,735,"ON"],[741,749,"ON"],[751,767,"ON"],[768,879,"NSM"],[884,885,"ON"],[894,894,"ON"],[900,901,"ON"],[903,903,"ON"],[1014,1014,"ON"],[1155,1161,"NSM"],[1418,1418,"ON"],[1421,1422,"ON"],[1423,1423,"ET"],[1424,1424,"R"],[1425,1469,"NSM"],[1470,1470,"R"],[1471,1471,"NSM"],[1472,1472,"R"],[1473,1474,"NSM"],[1475,1475,"R"],[1476,1477,"NSM"],[1478,1478,"R"],[1479,1479,"NSM"],[1480,1535,"R"],[1536,1541,"AN"],[1542,1543,"ON"],[1544,1544,"AL"],[1545,1546,"ET"],[1547,1547,"AL"],[1548,1548,"CS"],[1549,1549,"AL"],[1550,1551,"ON"],[1552,1562,"NSM"],[1563,1610,"AL"],[1611,1631,"NSM"],[1632,1641,"AN"],[1642,1642,"ET"],[1643,1644,"AN"],[1645,1647,"AL"],[1648,1648,"NSM"],[1649,1749,"AL"],[1750,1756,"NSM"],[1757,1757,"AN"],[1758,1758,"ON"],[1759,1764,"NSM"],[1765,1766,"AL"],[1767,1768,"NSM"],[1769,1769,"ON"],[1770,1773,"NSM"],[1774,1775,"AL"],[1776,1785,"EN"],[1786,1808,"AL"],[1809,1809,"NSM"],[1810,1839,"AL"],[1840,1866,"NSM"],[1867,1957,"AL"],[1958,1968,"NSM"],[1969,1983,"AL"],[1984,2026,"R"],[2027,2035,"NSM"],[2036,2037,"R"],[2038,2041,"ON"],[2042,2044,"R"],[2045,2045,"NSM"],[2046,2069,"R"],[2070,2073,"NSM"],[2074,2074,"R"],[2075,2083,"NSM"],[2084,2084,"R"],[2085,2087,"NSM"],[2088,2088,"R"],[2089,2093,"NSM"],[2094,2136,"R"],[2137,2139,"NSM"],[2140,2143,"R"],[2144,2191,"AL"],[2192,2193,"AN"],[2194,2198,"AL"],[2199,2207,"NSM"],[2208,2249,"AL"],[2250,2273,"NSM"],[2274,2274,"AN"],[2275,2306,"NSM"],[2362,2362,"NSM"],[2364,2364,"NSM"],[2369,2376,"NSM"],[2381,2381,"NSM"],[2385,2391,"NSM"],[2402,2403,"NSM"],[2433,2433,"NSM"],[2492,2492,"NSM"],[2497,2500,"NSM"],[2509,2509,"NSM"],[2530,2531,"NSM"],[2546,2547,"ET"],[2555,2555,"ET"],[2558,2558,"NSM"],[2561,2562,"NSM"],[2620,2620,"NSM"],[2625,2626,"NSM"],[2631,2632,"NSM"],[2635,2637,"NSM"],[2641,2641,"NSM"],[2672,2673,"NSM"],[2677,2677,"NSM"],[2689,2690,"NSM"],[2748,2748,"NSM"],[2753,2757,"NSM"],[2759,2760,"NSM"],[2765,2765,"NSM"],[2786,2787,"NSM"],[2801,2801,"ET"],[2810,2815,"NSM"],[2817,2817,"NSM"],[2876,2876,"NSM"],[2879,2879,"NSM"],[2881,2884,"NSM"],[2893,2893,"NSM"],[2901,2902,"NSM"],[2914,2915,"NSM"],[2946,2946,"NSM"],[3008,3008,"NSM"],[3021,3021,"NSM"],[3059,3064,"ON"],[3065,3065,"ET"],[3066,3066,"ON"],[3072,3072,"NSM"],[3076,3076,"NSM"],[3132,3132,"NSM"],[3134,3136,"NSM"],[3142,3144,"NSM"],[3146,3149,"NSM"],[3157,3158,"NSM"],[3170,3171,"NSM"],[3192,3198,"ON"],[3201,3201,"NSM"],[3260,3260,"NSM"],[3276,3277,"NSM"],[3298,3299,"NSM"],[3328,3329,"NSM"],[3387,3388,"NSM"],[3393,3396,"NSM"],[3405,3405,"NSM"],[3426,3427,"NSM"],[3457,3457,"NSM"],[3530,3530,"NSM"],[3538,3540,"NSM"],[3542,3542,"NSM"],[3633,3633,"NSM"],[3636,3642,"NSM"],[3647,3647,"ET"],[3655,3662,"NSM"],[3761,3761,"NSM"],[3764,3772,"NSM"],[3784,3790,"NSM"],[3864,3865,"NSM"],[3893,3893,"NSM"],[3895,3895,"NSM"],[3897,3897,"NSM"],[3898,3901,"ON"],[3953,3966,"NSM"],[3968,3972,"NSM"],[3974,3975,"NSM"],[3981,3991,"NSM"],[3993,4028,"NSM"],[4038,4038,"NSM"],[4141,4144,"NSM"],[4146,4151,"NSM"],[4153,4154,"NSM"],[4157,4158,"NSM"],[4184,4185,"NSM"],[4190,4192,"NSM"],[4209,4212,"NSM"],[4226,4226,"NSM"],[4229,4230,"NSM"],[4237,4237,"NSM"],[4253,4253,"NSM"],[4957,4959,"NSM"],[5008,5017,"ON"],[5120,5120,"ON"],[5760,5760,"WS"],[5787,5788,"ON"],[5906,5908,"NSM"],[5938,5939,"NSM"],[5970,5971,"NSM"],[6002,6003,"NSM"],[6068,6069,"NSM"],[6071,6077,"NSM"],[6086,6086,"NSM"],[6089,6099,"NSM"],[6107,6107,"ET"],[6109,6109,"NSM"],[6128,6137,"ON"],[6144,6154,"ON"],[6155,6157,"NSM"],[6158,6158,"BN"],[6159,6159,"NSM"],[6277,6278,"NSM"],[6313,6313,"NSM"],[6432,6434,"NSM"],[6439,6440,"NSM"],[6450,6450,"NSM"],[6457,6459,"NSM"],[6464,6464,"ON"],[6468,6469,"ON"],[6622,6655,"ON"],[6679,6680,"NSM"],[6683,6683,"NSM"],[6742,6742,"NSM"],[6744,6750,"NSM"],[6752,6752,"NSM"],[6754,6754,"NSM"],[6757,6764,"NSM"],[6771,6780,"NSM"],[6783,6783,"NSM"],[6832,6877,"NSM"],[6880,6891,"NSM"],[6912,6915,"NSM"],[6964,6964,"NSM"],[6966,6970,"NSM"],[6972,6972,"NSM"],[6978,6978,"NSM"],[7019,7027,"NSM"],[7040,7041,"NSM"],[7074,7077,"NSM"],[7080,7081,"NSM"],[7083,7085,"NSM"],[7142,7142,"NSM"],[7144,7145,"NSM"],[7149,7149,"NSM"],[7151,7153,"NSM"],[7212,7219,"NSM"],[7222,7223,"NSM"],[7376,7378,"NSM"],[7380,7392,"NSM"],[7394,7400,"NSM"],[7405,7405,"NSM"],[7412,7412,"NSM"],[7416,7417,"NSM"],[7616,7679,"NSM"],[8125,8125,"ON"],[8127,8129,"ON"],[8141,8143,"ON"],[8157,8159,"ON"],[8173,8175,"ON"],[8189,8190,"ON"],[8192,8202,"WS"],[8203,8205,"BN"],[8207,8207,"R"],[8208,8231,"ON"],[8232,8232,"WS"],[8233,8233,"B"],[8234,8238,"BN"],[8239,8239,"CS"],[8240,8244,"ET"],[8245,8259,"ON"],[8260,8260,"CS"],[8261,8286,"ON"],[8287,8287,"WS"],[8288,8303,"BN"],[8304,8304,"EN"],[8308,8313,"EN"],[8314,8315,"ES"],[8316,8318,"ON"],[8320,8329,"EN"],[8330,8331,"ES"],[8332,8334,"ON"],[8352,8399,"ET"],[8400,8432,"NSM"],[8448,8449,"ON"],[8451,8454,"ON"],[8456,8457,"ON"],[8468,8468,"ON"],[8470,8472,"ON"],[8478,8483,"ON"],[8485,8485,"ON"],[8487,8487,"ON"],[8489,8489,"ON"],[8494,8494,"ET"],[8506,8507,"ON"],[8512,8516,"ON"],[8522,8525,"ON"],[8528,8543,"ON"],[8585,8587,"ON"],[8592,8721,"ON"],[8722,8722,"ES"],[8723,8723,"ET"],[8724,9013,"ON"],[9083,9108,"ON"],[9110,9257,"ON"],[9280,9290,"ON"],[9312,9351,"ON"],[9352,9371,"EN"],[9450,9899,"ON"],[9901,10239,"ON"],[10496,11123,"ON"],[11126,11263,"ON"],[11493,11498,"ON"],[11503,11505,"NSM"],[11513,11519,"ON"],[11647,11647,"NSM"],[11744,11775,"NSM"],[11776,11869,"ON"],[11904,11929,"ON"],[11931,12019,"ON"],[12032,12245,"ON"],[12272,12287,"ON"],[12288,12288,"WS"],[12289,12292,"ON"],[12296,12320,"ON"],[12330,12333,"NSM"],[12336,12336,"ON"],[12342,12343,"ON"],[12349,12351,"ON"],[12441,12442,"NSM"],[12443,12444,"ON"],[12448,12448,"ON"],[12539,12539,"ON"],[12736,12773,"ON"],[12783,12783,"ON"],[12829,12830,"ON"],[12880,12895,"ON"],[12924,12926,"ON"],[12977,12991,"ON"],[13004,13007,"ON"],[13175,13178,"ON"],[13278,13279,"ON"],[13311,13311,"ON"],[19904,19967,"ON"],[42128,42182,"ON"],[42509,42511,"ON"],[42607,42610,"NSM"],[42611,42611,"ON"],[42612,42621,"NSM"],[42622,42623,"ON"],[42654,42655,"NSM"],[42736,42737,"NSM"],[42752,42785,"ON"],[42888,42888,"ON"],[43010,43010,"NSM"],[43014,43014,"NSM"],[43019,43019,"NSM"],[43045,43046,"NSM"],[43048,43051,"ON"],[43052,43052,"NSM"],[43064,43065,"ET"],[43124,43127,"ON"],[43204,43205,"NSM"],[43232,43249,"NSM"],[43263,43263,"NSM"],[43302,43309,"NSM"],[43335,43345,"NSM"],[43392,43394,"NSM"],[43443,43443,"NSM"],[43446,43449,"NSM"],[43452,43453,"NSM"],[43493,43493,"NSM"],[43561,43566,"NSM"],[43569,43570,"NSM"],[43573,43574,"NSM"],[43587,43587,"NSM"],[43596,43596,"NSM"],[43644,43644,"NSM"],[43696,43696,"NSM"],[43698,43700,"NSM"],[43703,43704,"NSM"],[43710,43711,"NSM"],[43713,43713,"NSM"],[43756,43757,"NSM"],[43766,43766,"NSM"],[43882,43883,"ON"],[44005,44005,"NSM"],[44008,44008,"NSM"],[44013,44013,"NSM"],[64285,64285,"R"],[64286,64286,"NSM"],[64287,64296,"R"],[64297,64297,"ES"],[64298,64335,"R"],[64336,64450,"AL"],[64451,64466,"ON"],[64467,64829,"AL"],[64830,64847,"ON"],[64848,64911,"AL"],[64912,64913,"ON"],[64914,64967,"AL"],[64968,64975,"ON"],[64976,65007,"BN"],[65008,65020,"AL"],[65021,65023,"ON"],[65024,65039,"NSM"],[65040,65049,"ON"],[65056,65071,"NSM"],[65072,65103,"ON"],[65104,65104,"CS"],[65105,65105,"ON"],[65106,65106,"CS"],[65108,65108,"ON"],[65109,65109,"CS"],[65110,65118,"ON"],[65119,65119,"ET"],[65120,65121,"ON"],[65122,65123,"ES"],[65124,65126,"ON"],[65128,65128,"ON"],[65129,65130,"ET"],[65131,65131,"ON"],[65136,65278,"AL"],[65279,65279,"BN"],[65281,65282,"ON"],[65283,65285,"ET"],[65286,65290,"ON"],[65291,65291,"ES"],[65292,65292,"CS"],[65293,65293,"ES"],[65294,65295,"CS"],[65296,65305,"EN"],[65306,65306,"CS"],[65307,65312,"ON"],[65339,65344,"ON"],[65371,65381,"ON"],[65504,65505,"ET"],[65506,65508,"ON"],[65509,65510,"ET"],[65512,65518,"ON"],[65520,65528,"BN"],[65529,65533,"ON"],[65534,65535,"BN"],[65793,65793,"ON"],[65856,65932,"ON"],[65936,65948,"ON"],[65952,65952,"ON"],[66045,66045,"NSM"],[66272,66272,"NSM"],[66273,66299,"EN"],[66422,66426,"NSM"],[67584,67870,"R"],[67871,67871,"ON"],[67872,68096,"R"],[68097,68099,"NSM"],[68100,68100,"R"],[68101,68102,"NSM"],[68103,68107,"R"],[68108,68111,"NSM"],[68112,68151,"R"],[68152,68154,"NSM"],[68155,68158,"R"],[68159,68159,"NSM"],[68160,68324,"R"],[68325,68326,"NSM"],[68327,68408,"R"],[68409,68415,"ON"],[68416,68863,"R"],[68864,68899,"AL"],[68900,68903,"NSM"],[68904,68911,"AL"],[68912,68921,"AN"],[68922,68927,"AL"],[68928,68937,"AN"],[68938,68968,"R"],[68969,68973,"NSM"],[68974,68974,"ON"],[68975,69215,"R"],[69216,69246,"AN"],[69247,69290,"R"],[69291,69292,"NSM"],[69293,69311,"R"],[69312,69327,"AL"],[69328,69336,"ON"],[69337,69369,"AL"],[69370,69375,"NSM"],[69376,69423,"R"],[69424,69445,"AL"],[69446,69456,"NSM"],[69457,69487,"AL"],[69488,69505,"R"],[69506,69509,"NSM"],[69510,69631,"R"],[69633,69633,"NSM"],[69688,69702,"NSM"],[69714,69733,"ON"],[69744,69744,"NSM"],[69747,69748,"NSM"],[69759,69761,"NSM"],[69811,69814,"NSM"],[69817,69818,"NSM"],[69826,69826,"NSM"],[69888,69890,"NSM"],[69927,69931,"NSM"],[69933,69940,"NSM"],[70003,70003,"NSM"],[70016,70017,"NSM"],[70070,70078,"NSM"],[70089,70092,"NSM"],[70095,70095,"NSM"],[70191,70193,"NSM"],[70196,70196,"NSM"],[70198,70199,"NSM"],[70206,70206,"NSM"],[70209,70209,"NSM"],[70367,70367,"NSM"],[70371,70378,"NSM"],[70400,70401,"NSM"],[70459,70460,"NSM"],[70464,70464,"NSM"],[70502,70508,"NSM"],[70512,70516,"NSM"],[70587,70592,"NSM"],[70606,70606,"NSM"],[70608,70608,"NSM"],[70610,70610,"NSM"],[70625,70626,"NSM"],[70712,70719,"NSM"],[70722,70724,"NSM"],[70726,70726,"NSM"],[70750,70750,"NSM"],[70835,70840,"NSM"],[70842,70842,"NSM"],[70847,70848,"NSM"],[70850,70851,"NSM"],[71090,71093,"NSM"],[71100,71101,"NSM"],[71103,71104,"NSM"],[71132,71133,"NSM"],[71219,71226,"NSM"],[71229,71229,"NSM"],[71231,71232,"NSM"],[71264,71276,"ON"],[71339,71339,"NSM"],[71341,71341,"NSM"],[71344,71349,"NSM"],[71351,71351,"NSM"],[71453,71453,"NSM"],[71455,71455,"NSM"],[71458,71461,"NSM"],[71463,71467,"NSM"],[71727,71735,"NSM"],[71737,71738,"NSM"],[71995,71996,"NSM"],[71998,71998,"NSM"],[72003,72003,"NSM"],[72148,72151,"NSM"],[72154,72155,"NSM"],[72160,72160,"NSM"],[72193,72198,"NSM"],[72201,72202,"NSM"],[72243,72248,"NSM"],[72251,72254,"NSM"],[72263,72263,"NSM"],[72273,72278,"NSM"],[72281,72283,"NSM"],[72330,72342,"NSM"],[72344,72345,"NSM"],[72544,72544,"NSM"],[72546,72548,"NSM"],[72550,72550,"NSM"],[72752,72758,"NSM"],[72760,72765,"NSM"],[72850,72871,"NSM"],[72874,72880,"NSM"],[72882,72883,"NSM"],[72885,72886,"NSM"],[73009,73014,"NSM"],[73018,73018,"NSM"],[73020,73021,"NSM"],[73023,73029,"NSM"],[73031,73031,"NSM"],[73104,73105,"NSM"],[73109,73109,"NSM"],[73111,73111,"NSM"],[73459,73460,"NSM"],[73472,73473,"NSM"],[73526,73530,"NSM"],[73536,73536,"NSM"],[73538,73538,"NSM"],[73562,73562,"NSM"],[73685,73692,"ON"],[73693,73696,"ET"],[73697,73713,"ON"],[78912,78912,"NSM"],[78919,78933,"NSM"],[90398,90409,"NSM"],[90413,90415,"NSM"],[92912,92916,"NSM"],[92976,92982,"NSM"],[94031,94031,"NSM"],[94095,94098,"NSM"],[94178,94178,"ON"],[94180,94180,"NSM"],[113821,113822,"NSM"],[113824,113827,"BN"],[117760,117973,"ON"],[118e3,118009,"EN"],[118010,118012,"ON"],[118016,118451,"ON"],[118458,118480,"ON"],[118496,118512,"ON"],[118528,118573,"NSM"],[118576,118598,"NSM"],[119143,119145,"NSM"],[119155,119162,"BN"],[119163,119170,"NSM"],[119173,119179,"NSM"],[119210,119213,"NSM"],[119273,119274,"ON"],[119296,119361,"ON"],[119362,119364,"NSM"],[119365,119365,"ON"],[119552,119638,"ON"],[120513,120513,"ON"],[120539,120539,"ON"],[120571,120571,"ON"],[120597,120597,"ON"],[120629,120629,"ON"],[120655,120655,"ON"],[120687,120687,"ON"],[120713,120713,"ON"],[120745,120745,"ON"],[120771,120771,"ON"],[120782,120831,"EN"],[121344,121398,"NSM"],[121403,121452,"NSM"],[121461,121461,"NSM"],[121476,121476,"NSM"],[121499,121503,"NSM"],[121505,121519,"NSM"],[122880,122886,"NSM"],[122888,122904,"NSM"],[122907,122913,"NSM"],[122915,122916,"NSM"],[122918,122922,"NSM"],[123023,123023,"NSM"],[123184,123190,"NSM"],[123566,123566,"NSM"],[123628,123631,"NSM"],[123647,123647,"ET"],[124140,124143,"NSM"],[124398,124399,"NSM"],[124643,124643,"NSM"],[124646,124646,"NSM"],[124654,124655,"NSM"],[124661,124661,"NSM"],[124928,125135,"R"],[125136,125142,"NSM"],[125143,125251,"R"],[125252,125258,"NSM"],[125259,126063,"R"],[126064,126143,"AL"],[126144,126207,"R"],[126208,126287,"AL"],[126288,126463,"R"],[126464,126703,"AL"],[126704,126705,"ON"],[126706,126719,"AL"],[126720,126975,"R"],[126976,127019,"ON"],[127024,127123,"ON"],[127136,127150,"ON"],[127153,127167,"ON"],[127169,127183,"ON"],[127185,127221,"ON"],[127232,127242,"EN"],[127243,127247,"ON"],[127279,127279,"ON"],[127338,127343,"ON"],[127405,127405,"ON"],[127584,127589,"ON"],[127744,128728,"ON"],[128732,128748,"ON"],[128752,128764,"ON"],[128768,128985,"ON"],[128992,129003,"ON"],[129008,129008,"ON"],[129024,129035,"ON"],[129040,129095,"ON"],[129104,129113,"ON"],[129120,129159,"ON"],[129168,129197,"ON"],[129200,129211,"ON"],[129216,129217,"ON"],[129232,129240,"ON"],[129280,129623,"ON"],[129632,129645,"ON"],[129648,129660,"ON"],[129664,129674,"ON"],[129678,129734,"ON"],[129736,129736,"ON"],[129741,129756,"ON"],[129759,129770,"ON"],[129775,129784,"ON"],[129792,129938,"ON"],[129940,130031,"ON"],[130032,130041,"EN"],[130042,130042,"ON"],[131070,131071,"BN"],[196606,196607,"BN"],[262142,262143,"BN"],[327678,327679,"BN"],[393214,393215,"BN"],[458750,458751,"BN"],[524286,524287,"BN"],[589822,589823,"BN"],[655358,655359,"BN"],[720894,720895,"BN"],[786430,786431,"BN"],[851966,851967,"BN"],[917502,917759,"BN"],[917760,917999,"NSM"],[918e3,921599,"BN"],[983038,983039,"BN"],[1048574,1048575,"BN"],[1114110,1114111,"BN"]];function sbe(e){if(e<=255)return obe[e];let t=0,n=oF.length-1;for(;t<=n;){const i=t+n>>1,o=oF[i];if(eo[1]))return o[2];t=i+1}}return"L"}const rbe=/[ \t\n\r\f]+/g,lbe=/[\t\n\r\f]| {2,}|^ | $/;let b8=null;const abe=new RegExp("\\p{Script=Arabic}","u"),Mf=new RegExp("\\p{M}","u"),qx=new RegExp("\\p{Nd}","u");function sF(e){return abe.test(e)}function rF(e){return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=183984&&e<=191471||e>=191472&&e<=192093||e>=194560&&e<=195103||e>=196608&&e<=201551||e>=201552&&e<=205743||e>=205744&&e<=210041||e>=63744&&e<=64255||e>=12288&&e<=12351||e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12592&&e<=12687||e>=44032&&e<=55215||e>=65280&&e<=65519}function tc(e){for(let t=0;t=55296&&n<=56319&&t+1=56320&&i<=57343){if(rF(i-56320+(n-55296<<10)+65536))return!0;t++;continue}}if(rF(n))return!0}}return!1}const ube=new Set([" "," ","⁠","\uFEFF"]),cbe=new Set(["-","‐","–","—"]);function Iq(e,t){return!((function(n){const i=Q0(n);return i!==null&&ube.has(i)})(e)||t&&((function(n){const i=Q0(n);return i!==null&&(Ux.has(i)||yp.has(i))})(e)||(function(n){const i=Q0(n);return i!==null&&cbe.has(i)})(e)))}const Ux=new Set([",",".","!",":",";","?","、","。","・",")","〕","〉","》","」","』","】","〗","〙","〛","ー","々","〻","ゝ","ゞ","ヽ","ヾ"]),G4=new Set(['"',"(","[","{","¡","¿","“","‘","‚","„","«","‹","⸘","(","〔","〈","《","「","『","【","〖","〘","〚"]),Vx=new Set(["'","’"]),yp=new Set([".",",","!","?",":",";","،","؛","؟","।","॥","၊","။","၌","၍","၏",")","]","}","%",'"',"”","’","»","›","…"]),dbe=new Set([":",".","،","؛"]),fbe=new Set(["၏"]),hbe=new Set(["”","’","»","›","」","』","】","》","〉","〕",")"]);function pbe(e){if(Kx(e))return!0;let t=!1;for(const n of e)if(yp.has(n)||kb(n))t=!0;else if(!t||!Mf.test(n))return!1;return t}function mbe(e){for(const t of e)if(!Ux.has(t)&&!yp.has(t))return!1;return e.length>0}function gbe(e){if(Kx(e))return!0;for(const t of e)if(!(G4.has(t)||Vx.has(t)||Mf.test(t)||kb(t)))return!1;return e.length>0}function Kx(e){let t=!1;for(const n of e)if(n!=="\\"&&!Mf.test(n)){if(!(G4.has(n)||yp.has(n)||Vx.has(n)))return!1;t=!0}return t}function yb(e,t){const n=t-1;if(n<=0)return Math.max(n,0);const i=e.charCodeAt(n);if(i<56320||i>57343)return n;const o=n-1;if(o<0)return n;const s=e.charCodeAt(o);return s>=55296&&s<=56319?o:n}function Q0(e){if(e.length===0)return null;const t=yb(e,e.length);return e.slice(t)}const vbe=[36,37,43,43,92,92,162,165,176,177,1423,1423,1545,1547,1642,1642,2046,2047,2546,2547,2553,2555,2801,2801,3065,3065,3449,3449,3647,3647,6107,6107,8240,8247,8279,8279,8352,8399,8451,8451,8457,8457,8470,8470,8722,8723,43064,43064,65020,65020,65129,65130,65284,65285,65504,65505,65509,65510,73693,73696,123647,123647,126124,126124,126128,126128];function kb(e){const t=e.codePointAt(0);return t!==void 0&&(function(n,i){for(let o=0;o=i[o]&&n<=i[o+1])return!0;return!1})(t,vbe)}function ybe(e){const t=(function(n){for(const i of n)if(!Mf.test(i))return i;return null})(e);return t!==null&&qx.test(t)}function kbe(e){const t=Array.from(e);let n=t.length;for(;n>0;){const i=t[n-1];if(Mf.test(i))n--;else{if(!G4.has(i)&&!Vx.has(i))break;n--}}return n<=0||n===t.length?null:{head:t.slice(0,n).join(""),tail:t.slice(n).join("")}}function bbe(e,t,n){return n!=="text"||t||e.length!==1||e==="-"||e==="—"?null:e}function lF(e,t,n,i){const o=t[i],s=e[i];if(o==null)return s;const r=n[i];if(s.length===r)return s;const l=o.repeat(r);return e[i]=l,l}function aF(e,t){return e&&t!==null&&dbe.has(t)}function wbe(e){const t=Q0(e);return t!==null&&fbe.has(t)}function Cbe(e){if(e.length<2||e[0]!==" ")return null;const t=e.slice(1);return new RegExp("^\\p{M}+$","u").test(t)?{space:" ",marks:t}:null}function jA(e){let t=e.length;for(;t>0;){const n=yb(e,t),i=e.slice(n,t);if(hbe.has(i))return!0;if(!yp.has(i))return!1;t=n}return!1}function Abe(e,t){if(t.preserveOrdinarySpaces||t.preserveHardBreaks){if(e===" ")return"preserved-space";if(e===" ")return"tab";if(t.preserveHardBreaks&&e===` +`)return"hard-break"}return e===" "?"space":e===" "||e===" "||e==="⁠"||e==="\uFEFF"?"glue":e==="​"?"zero-width-break":e==="­"?"soft-hyphen":"text"}const xbe=/[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;function ru(e){return e.length===1?e[0]:e.join("")}function Sbe(e,t){const n=[];for(let i=e.length-1;i>=0;i--)n.push(e[i]);return n.push(t),ru(n)}function _be(e,t,n,i){if(!xbe.test(e))return[{text:e,isWordLike:t,kind:"text",start:n}];const o=[];let s=null,r=[],l=n,a=!1,u=0;for(const c of e){const d=Abe(c,i),f=d==="text"&&t;s===null||d!==s||f!==a?(s!==null&&o.push({text:ru(r),isWordLike:a,kind:s,start:l}),s=d,r=[c],l=n+u,a=f,u+=c.length):(r.push(c),u+=c.length)}return s!==null&&o.push({text:ru(r),isWordLike:a,kind:s,start:l}),o}function w8(e){return e==="space"||e==="preserved-space"||e==="zero-width-break"||e==="hard-break"}const Ibe=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function Mbe(e,t){const n=e.texts[t];return!!n.startsWith("www.")||Ibe.test(n)&&t+1=33&&n<=47&&n!==45||n>=58&&n<=64&&n!==63||n>=91&&n<=96||n>=123&&n<=126})(t):!Fbe.has(e)&&!Nbe.test(e)&&Lbe.test(e)}function uF(e){let t=!1;for(const n of e)if(!Mf.test(n)){if(!Mq(n))return!1;t=!0}return t}function Dbe(e,t,n,i){const o=!t&&uF(e),s=!i&&uF(n),r=(function(a){const u=(function(c){for(let d=c.length;d>0;){const f=yb(c,d),h=c.slice(f,d);if(!Mf.test(h))return h;d=f}return null})(a);return u!==null&&kb(u)})(e),l=(t||r)&&(function(a){for(let u=a.length;u>0;){const c=yb(a,u),d=a.slice(c,u);if(!Mf.test(d))return Mq(d)||kb(d);u=c}return!1})(e);return!!(o||s||l)&&!tc(e)&&!tc(n)&&(t||o||r)&&(i||s)}function cF(e){for(const t of e)if(qx.test(t))return!0;return!1}function V9(e){if(e.length===0)return!1;for(const t of e)if(!qx.test(t)&&!Ebe.has(t))return!1;return!0}function Rbe(e,t){if(e.len===0)return[];if(!t.preserveHardBreaks)return[{startSegmentIndex:0,endSegmentIndex:e.len,consumedEndSegmentIndex:e.len}];const n=[];let i=0;for(let o=0;o0&&u.charCodeAt(u.length-1)===32&&(u=u.slice(0,-1)),u})(e);if(s.length===0)return{normalized:s,chunks:[],len:0,texts:[],isWordLike:[],kinds:[],starts:[]};const r=(function(a,u,c){var d,f,h;const m=(b8===null&&(b8=new Intl.Segmenter(void 0,{granularity:"word"})),b8);let g=0;const y=[],k=[],v=[],C=[],w=[],M=[],L=[],E=[],S=[],x=[],A=[],T=[];for(const F of m.segment(a))for(const P of _be(F.segment,(d=F.isWordLike)!=null&&d,F.index,c)){let z=function(){M[ie]!==null&&(k[ie]=[lF(y,M,L,ie)],M[ie]=null),k[ie].push(P.text),v[ie]=v[ie]||P.isWordLike,E[ie]=E[ie]||K,S[ie]=S[ie]||ne,x[ie]=te,A[ie]=le,T[ie]=aF(S[ie],G)};const W=P.kind==="text",$=bbe(P.text,P.isWordLike,P.kind),K=tc(P.text),ne=sF(P.text),G=Q0(P.text),te=jA(P.text),le=wbe(P.text),ie=g-1;u.carryCJKAfterClosingQuote&&W&&g>0&&C[ie]==="text"&&K&&E[ie]&&x[ie]||W&&g>0&&C[ie]==="text"&&mbe(P.text)&&E[ie]||W&&g>0&&C[ie]==="text"&&A[ie]?z():W&&g>0&&C[ie]==="text"&&P.isWordLike&&ne&&T[ie]?(z(),v[ie]=!0):$!==null&&g>0&&C[ie]==="text"&&M[ie]===$?L[ie]=((f=L[ie])!=null?f:1)+1:W&&!P.isWordLike&&g>0&&C[ie]==="text"&&!E[ie]&&(pbe(P.text)||P.text==="-"&&v[ie])?z():(y[g]=P.text,k[g]=[P.text],v[g]=P.isWordLike,C[g]=P.kind,w[g]=P.start,M[g]=$,L[g]=$===null?0:1,E[g]=K,S[g]=ne,x[g]=te,A[g]=le,T[g]=aF(ne,G),g++)}for(let F=0;Fnull);let O=-1;for(let F=g-1;F>=0;F--){const P=y[F];if(P.length!==0){if(C[F]==="text"&&!v[F]&&O>=0&&C[O]==="text"&&(gbe(P)||P==="-"&&ybe(y[O]))){const z=(h=I[O])!=null?h:[];z.push(P),I[O]=z,w[O]=w[F],y[F]="";continue}O=F}}for(let F=0;FK+1){P.push(ru(le)),z.push(_e),W.push("text"),$.push(F.starts[K]),K=ie;continue}}P.push(ne),z.push(te),W.push(G),$.push(F.starts[K]),K++}return{len:P.length,texts:P,isWordLike:z,kinds:W,starts:$}})((function(F){const P=[],z=[],W=[],$=[];for(let K=0;K1;for(let le=0;le=F.len||w8(F.kinds[G]))continue;const te=[],le=F.starts[G];let ie=G;for(;ie0&&(P.push(ru(te)),z.push(!0),W.push("text"),$.push(le),K=ie-1)}return{len:P.length,texts:P,isWordLike:z,kinds:W,starts:$}})((function(F){const P=F.texts.slice(),z=F.isWordLike.slice(),W=F.kinds.slice(),$=F.starts.slice();for(let ne=0;ne=0&&!Iq(u.texts[C-1],c)&&v(C),g<0&&(g=C),y=y||tc(w))}return v(u.len),{len:d.length,texts:d,isWordLike:f,kinds:h,starts:m}})(s,r,t.breakKeepAllAfterPunctuation):r;return Bt({normalized:s,chunks:Rbe(l,o)},l)}let u1=null;const dF=new Map;let c1=null;const Pbe=new RegExp("\\p{Emoji_Presentation}","u"),Bbe=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u;let C8=null;const fF=new Map;function HA(){if(u1!==null)return u1;if(typeof OffscreenCanvas<"u")return u1=new OffscreenCanvas(1,1).getContext("2d"),u1;if(typeof document<"u")return u1=document.createElement("canvas").getContext("2d"),u1;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function Nd(e,t){let n=t.get(e);return n===void 0&&(n={width:HA().measureText(e).width,containsCJK:tc(e)},t.set(e,n)),n}function bb(){if(c1!==null)return c1;if(typeof navigator>"u")return c1={lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,breakKeepAllAfterPunctuation:!0,preferPrefixWidthsForBreakableRuns:!1,preferEarlySoftHyphenBreak:!1},c1;const e=navigator.userAgent,t=navigator.vendor==="Apple Computer, Inc."&&e.includes("Safari/")&&!e.includes("Chrome/")&&!e.includes("Chromium/")&&!e.includes("CriOS/")&&!e.includes("FxiOS/")&&!e.includes("EdgiOS/"),n=e.includes("Chrome/")||e.includes("Chromium/")||e.includes("CriOS/")||e.includes("Edg/");return c1={lineFitEpsilon:t?1/64:.005,carryCJKAfterClosingQuote:n,breakKeepAllAfterPunctuation:!t,preferPrefixWidthsForBreakableRuns:t,preferEarlySoftHyphenBreak:t},c1}function Tq(){return C8===null&&(C8=new Intl.Segmenter(void 0,{granularity:"grapheme"})),C8}function $be(e){return Pbe.test(e)||e.includes("️")}function mh(e,t,n){return n===0?t.width:t.width-(function(i,o){return o.emojiCount===void 0&&(o.emojiCount=(function(s){let r=0;const l=Tq();for(const a of l.segment(s))$be(a.segment)&&r++;return r})(i)),o.emojiCount})(e,t)*n}function zbe(e){return e==="space"||e==="zero-width-break"||e==="soft-hyphen"}function hF(e){return e==="space"||e==="preserved-space"||e==="tab"||e==="zero-width-break"||e==="soft-hyphen"}function pF(e,t,n=e.widths.length){for(;t0?e.letterSpacing:0}function Zx(e,t){return t===0?0:e+t}function Wbe(e,t,n,i,o){return Zx(i,t==="tab"?o+(function(s,r){return s.letterSpacing!==0&&s.spacingGraphemeCounts[r]>0?s.letterSpacing:0})(e,n):e.lineEndFitAdvances[n])}function mF(e,t,n,i){return Zx(i,t==="tab"?0:e.lineEndFitAdvances[n])}function gF(e,t,n,i,o){return Zx(i,t==="tab"?o:e.lineEndPaintAdvances[n])}function qbe(e,t,n){return e.letterSpacing!==0&&t?n+e.letterSpacing:n}function Ube(e,t){return e.letterSpacing===0?t:t+e.letterSpacing}function Ry(e,t,n){let i=t;for(;iz){if(me!==null&&ee>U){ie(J,ee,re),ge=ee,pe=Ry(me,pe,ge+1),ee=-1,re=0;continue}ie(),Z(J,ge,ae)}else $+=ae,ne=J,G=ge+1;else Z(J,ge,ae);const Ce=ge+1;me!==null&&me[pe]===Ce&&(ee=Ce,re=$,pe++),ge++}K&&ne===J&&G===ue.length&&(ne=J+1,G=0)}let Y=0;for(;Y=H.length)));){const J=H[Y],U=hF(R[Y]);if(K)if($+J>z){if(U){se(Y,J),ie(Y+1,0,$-J),Y++;continue}if(te>=0){if(ne>te||ne===te&&G>0){ie();continue}ie(te,0,le);continue}if(J>z&&F[Y]!==null){ie(),he(Y,0),Y++;continue}ie()}else se(Y,J),U&&(te=Y+1,le=$-J),Y++;else J>z&&F[Y]!==null?he(Y,0):_e(Y,J),U&&(te=Y+1,le=$-J),Y++}return K&&ie(),W})(n,i);const{widths:o,kinds:s,breakableFitAdvances:r,breakablePreferredBreaks:l,discretionaryHyphenWidth:a,chunks:u}=n;if(o.length===0||u.length===0)return 0;const c=bb(),d=i+c.lineFitEpsilon;let f=0,h=0,m=!1,g=0,y=0,k=-1,v=0,C=null;function w(){k=-1,v=0,C=null}function M(I=g,O=y,H){f++,h=0,m=!1,w()}function L(I,O){m=!0,g=I+1,y=0,h=O}function E(I,O,H){m=!0,g=I,y=O+1,h=H}function S(I,O){m?(h+=O,g=I+1,y=0):L(I,O)}function x(I,O,H,R,F,P){if(!O)return;const z=mF(n,I,H,F);gF(n,I,H,F,R),k=H+1,v=h-P+z,C=I}function A(I,O){var H;const R=r[I],F=(H=l[I])!=null?H:null;let P=F===null?-1:Ry(F,0,O+1),z=-1,W=O;for(;Wd){if(F!==null&&z>O){M(I,z),W=z,P=Ry(F,P,W+1),z=-1;continue}M(),E(I,W,$)}else h=G,g=I,y=W+1}else E(I,W,$);const K=W+1;F!==null&&F[P]===K&&(z=K,P++),W++}m&&g===I&&y===R.length&&(g=I+1,y=0)}function T(I){f++,w()}for(let I=0;I=O.endSegmentIndex)));){const R=s[H],F=hF(R),P=Hbe(n,m,H),z=R==="tab"?jbe(h+P,n.tabStopAdvance):o[H],W=P+z,$=Wbe(n,R,H,P,z);if(R!=="soft-hyphen")if(m){if(h+$>d){const K=h+mF(n,R,H,P);if(gF(n,R,H,P,z),C==="soft-hyphen"&&c.preferEarlySoftHyphenBreak&&v<=d){M(k,0);continue}if(F&&K<=d){S(H,W),M(H+1,0),H++;continue}if(k>=0&&v<=d){if(g>k||g===k&&y>0){M();continue}const ne=k;M(ne,0),H=ne;continue}if($>d&&r[H]!==null){M(),A(H,0),H++;continue}M();continue}S(H,W),x(R,F,H,z,P,W),H++}else $>d&&r[H]!==null?A(H,0):L(H,z),x(R,F,H,z,P,W),H++;else m&&(g=H+1,y=0,k=H+1,v=h+a,C=R),H++}m&&(O.consumedEndSegmentIndex,M(O.consumedEndSegmentIndex,0))}return f})(e,t)}let A8=null;function Gx(){return A8===null&&(A8=new Intl.Segmenter(void 0,{granularity:"grapheme"})),A8}function Kbe(e,t){const n=[];let i=[],o=0,s=!1,r=!1,l=!1;function a(){i.length!==0&&(n.push({text:i.length===1?i[0]:i.join(""),start:o}),i=[],s=!1,r=!1,l=!1)}function u(d,f,h){i=[d],o=f,s=h,r=jA(d),l=G4.has(d)}function c(d,f){i.push(d),s=s||f;const h=jA(d);r=d.length===1&&yp.has(d)&&r||h,l=!1}for(const d of Gx().segment(e)){const f=d.segment,h=tc(f);i.length!==0?l||Ux.has(f)||yp.has(f)||t.carryCJKAfterClosingQuote&&h&&r?c(f,h):s||h?(a(),u(f,d.index,h)):c(f,h):u(f,d.index,h)}return a(),n}function Zbe(e,t,n){if(t.length<=1)return t;const i=[];let o=-1,s=!1;function r(l){if(!(o<0)){if(s)o+1===l?i.push(t[o]):(function(a,u){const c=t[a].start,d=u=0&&!Iq(t[l-1].text,n)&&r(l),o<0&&(o=l),s=s||tc(a.text)}return r(t.length),i}function vF(e,t){if(t==="zero-width-break"||t==="soft-hyphen"||t==="hard-break")return 0;if(t==="tab")return 1;let n=0;const i=Gx();for(const o of i.segment(e))n++;return n}function Gbe(e){return e==="-"||e==="֊"||e==="‐"||e==="‒"||e==="–"||e==="—"}function Qbe(e,t,n,i,o){const s=bb(),{cache:r,emojiCorrection:l}=(function(T,I){HA().font=T;const O=(function(F){let P=dF.get(F);return P||(P=new Map,dF.set(F,P)),P})(T),H=(function(F){const P=F.match(/(\d+(?:\.\d+)?)\s*px/);return P?parseFloat(P[1]):16})(T),R=I?(function(F,P){let z=fF.get(F);if(z!==void 0)return z;const W=HA();W.font=F;const $=W.measureText("😀").width;if(z=0,$>P+.5&&typeof document<"u"&&document.body!==null){const K=document.createElement("span");K.style.font=F,K.style.display="inline-block",K.style.visibility="hidden",K.style.position="absolute",K.textContent="😀",document.body.appendChild(K);const ne=K.getBoundingClientRect().width;document.body.removeChild(K),$-ne>.5&&(z=$-ne)}return fF.set(F,z),z})(T,H):0;return{cache:O,fontSize:H,emojiCorrection:R}})(t,(a=e.normalized,Bbe.test(a)));var a;const u=mh("-",Nd("-",r),l)+(o===0?0:2*o),c=8*mh(" ",Nd(" ",r),l),d=o!==0;if(e.len===0)return{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],breakablePreferredBreaks:[],letterSpacing:0,spacingGraphemeCounts:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[]};const f=[],h=[],m=[],g=[];let y=e.chunks.length<=1&&!d;const k=null,v=[],C=[],w=[],M=null,L=Array.from({length:e.len});function E(T,I,O,H,R,F,P,z,W){R!=="text"&&R!=="space"&&R!=="zero-width-break"&&(y=!1),f.push(I),h.push(O),m.push(H),g.push(R),v.push(P),C.push(z),d&&w.push(W)}function S(T,I,O,H,R){const F=Nd(T,r),P=d?vF(T,I):0,z=(function(ne,G,te){return G>1?ne+(G-1)*te:ne})(mh(T,F,l),P,o),W=I==="space"||I==="preserved-space"||I==="zero-width-break"?0:z,$=W===0?0:W+(P>0?o:0),K=I==="space"||I==="zero-width-break"?0:z;if(R&&H&&T.length>1){let ne="sum-graphemes";o!==0?ne="segment-prefixes":V9(T)?ne="pair-context":s.preferPrefixWidthsForBreakableRuns&&(ne="segment-prefixes");const G=(function(le,ie,_e,Z,se){if(ie.breakableFitAdvances!==void 0&&ie.breakableFitMode===se)return ie.breakableFitAdvances;ie.breakableFitMode=se;const he=Tq(),Y=[];for(const ue of he.segment(le))Y.push(ue.segment);if(Y.length<=1)return ie.breakableFitAdvances=null,ie.breakableFitAdvances;if(se==="sum-graphemes"){const ue=[];for(const me of Y){const pe=Nd(me,_e);ue.push(mh(me,pe,Z))}return ie.breakableFitAdvances=ue,ie.breakableFitAdvances}if(se==="pair-context"||Y.length>96){const ue=[];let me=null,pe=0;for(const ee of Y){const re=mh(ee,Nd(ee,_e),Z);if(me===null)ue.push(re);else{const ge=me+ee,ae=Nd(ge,_e);ue.push(mh(ge,ae,Z)-pe)}me=ee,pe=re}return ie.breakableFitAdvances=ue,ie.breakableFitAdvances}const J=[];let U="",Q=0;for(const ue of Y){U+=ue;const me=mh(U,Nd(U,_e),Z);J.push(me-Q),Q=me}return ie.breakableFitAdvances=J,ie.breakableFitAdvances})(T,F,r,l,ne),te=G===null||i==="keep-all"?null:(function(le){if(!/[-\u058A\u2010\u2012\u2013\u2014]/u.test(le))return null;const ie=[];let _e=0;for(const Z of Gx().segment(le))_e++,Gbe(Z.segment)&&ie.push(_e);return ie.length===0?null:ie})(T);return void E(T,z,$,K,I,O,G,te,P)}E(T,z,$,K,I,O,null,null,P)}for(let T=0;T=55296&&le<=56319&&te+1=56320&&se<=57343&&(ie=se-56320+(le-55296<<10)+65536,_e=2)}const Z=sbe(ie);Z!=="R"&&Z!=="AL"&&Z!=="AN"||(z=!0);for(let se=0;se<_e;se++)P[te+se]=Z;te+=_e}if(!z)return null;let W=0;for(let te=0;te=0&&P[le]==="ET";le--)P[le]="EN";for(le=te+1;le0?P[te-1]:ne)!=="L"?"R":"L";if(ie===((le{const e=globalThis;if(e[x8])return e[x8];const t={configs:{},controllers:{},revision:_u(0),preparedCache:new Map,blockEstimateCache:new Map};return e[x8]=t,t})();let Bg=null;const S8=_s.revision;function yF(e){var t;return e&&(t=_s.configs[e])!=null?t:null}function kF(e,t){const n=Number.parseFloat(String(e??""));return Number.isFinite(n)&&n>0?n:t}function Jbe(e){return e?.type==="text"||e?.type==="emoji"||e?.type==="hardbreak"}function _8(e){var t,n,i;if(!Array.isArray(e)||e.length===0)return null;let o="";for(const s of e){if(!Jbe(s))return null;s.type==="text"?o+=String((t=s.content)!=null?t:""):s.type==="emoji"?o+=String((i=(n=s.name)!=null?n:s.raw)!=null?i:""):s.type==="hardbreak"&&(o+=` +`)}return o.length>0?o:null}function I8(e,t,n){var i,o;if(!e||!Number.isFinite(t)||t<=0||!(function(){var s;if(Bg!=null)return Bg;if(typeof document>"u")return!1;try{const r=document.createElement("canvas");return Bg=!!((s=r.getContext)!=null&&s.call(r,"2d")),Bg}catch{return Bg=!1,!1}})())return null;try{const s=Math.round(100*t)/100,r=[(i=n.whiteSpace)!=null?i:"pre-wrap",n.font,n.lineHeight,n.wrapperOverhead,n.widthAdjustment,s,e].join("\0"),l=_s.blockEstimateCache.get(r);if(l)return _s.blockEstimateCache.delete(r),_s.blockEstimateCache.set(r,l),{kind:"simple-text",height:l.height,contentHeight:l.contentHeight};const a=(o=n.whiteSpace)!=null?o:"pre-wrap",u=(function(h,m,g){const y=`${g}\0${m}\0${h}`,k=_s.preparedCache.get(y);if(k)return _s.preparedCache.delete(y),_s.preparedCache.set(y,k),k.prepared;const v=(function(C,w,M){return(function(L,E,S,x){var A,T;const I=(A=x?.wordBreak)!=null?A:"normal",O=(T=x?.letterSpacing)!=null?T:0;return Qbe(Obe(L,bb(),x?.whiteSpace,I),E,!1,I,O)})(C,w,0,M)})(h,m,{whiteSpace:g});for(_s.preparedCache.set(y,{prepared:v});_s.preparedCache.size>240;){const C=_s.preparedCache.keys().next().value;if(!C)break;_s.preparedCache.delete(C)}return v})(e,n.font,a),c=(function(h,m,g){const y=Vbe(h,m);return{lineCount:y,height:y*g}})(u,Math.max(24,s-n.widthAdjustment),n.lineHeight),d=Math.max(n.lineHeight,c.height),f=Math.max(n.lineHeight,Math.round(d+n.wrapperOverhead));for(_s.blockEstimateCache.set(r,{height:f,contentHeight:Math.round(d)});_s.blockEstimateCache.size>4e3;){const h=_s.blockEstimateCache.keys().next().value;if(!h)break;_s.blockEstimateCache.delete(h)}return{kind:"simple-text",height:f,contentHeight:Math.round(d)}}catch{return null}}function Eq(e,t,n){var i,o;if(!n||!e||!Number.isFinite(t)||t<=0)return null;if(e.type==="paragraph"){const s=_8(e.children);return s&&n.paragraph?I8(s,t,n.paragraph):null}if(e.type==="heading"){const s=Number(e.level||0),r=_8(e.children),l=n.headings[s];return r&&l?I8(r,t,l):null}if(e.type==="list_item"){const s=Array.isArray(e.children)?e.children:[];if(s.length!==1||((i=s[0])==null?void 0:i.type)!=="paragraph"||!n.listItem)return null;const r=_8((o=s[0])==null?void 0:o.children);return r?I8(r,t,n.listItem):null}if(e.type==="list"){const s=Array.isArray(e.items)?e.items:[];if(!s.length)return null;let r=Math.max(0,n.listWrapperOverhead);for(const l of s){const a=Eq(l,t,n);if(!a)return null;r+=a.height}return{kind:"simple-text",height:Math.max(1,Math.round(r)),contentHeight:Math.max(1,Math.round(r))}}return null}function $g(e){if(!e)return 1;const t=String(e).split(/\r?\n/);return Math.max(1,t.length)}function gh(e,t){const n=String(e??"");return t?n:n.replace(/\r\n$|\n$|\r$/,"")}function M8(e,t,n=0){return e.diff?Wx(t??{},n)?(function(i){const o=gh(i.raw);if(o){const s=o.split(/\r?\n/);return i.originalCode!=null||i.updatedCode!=null?Math.max(1,s.filter(r=>!Ybe.some(l=>r.startsWith(l))).length):Math.max(1,s.length)}return $g(gh(i.originalCode))+$g(gh(i.updatedCode))})(e):(function(i){const o=i.originalCode,s=i.updatedCode;if(o!=null||s!=null)return Math.max($g(gh(o)),$g(gh(s)));const r=gh(i.code).split(/\r?\n/);let l=0,a=0;for(const u of r)u.startsWith("+")&&!u.startsWith("+++")?a++:u.startsWith("-")&&!u.startsWith("---")?l++:(l++,a++);return Math.max(1,l,a)})(e):$g(gh(e.code,e.loading===!0))}function Xbe(e){return e?`${e.fontStyle||"normal"} ${e.fontWeight||"400"} ${e.fontSize||"16px"} ${e.fontFamily||"sans-serif"}`:""}function T8(e,t,n="pre-wrap"){if(!e||!t||typeof window>"u")return null;const i=window.getComputedStyle(t),o=e.offsetHeight,s=kF(i.lineHeight,1.5*kF(i.fontSize,16)),r=e.getBoundingClientRect().width,l=t.getBoundingClientRect().width;return{font:Xbe(i),lineHeight:s,wrapperOverhead:Math.max(0,o-s),widthAdjustment:Math.max(0,r-l),whiteSpace:n}}const e4e=new Set(["node","key","ref","ctx","renderNode","indexKey","__proto__","prototype","constructor"]);function bF(e,t={}){var n;const i={},o=new Set((n=t.omit)!=null?n:[]);if(!e||typeof e!="object")return i;const s=Object.getOwnPropertyDescriptors(e);for(const[r,l]of Object.entries(s))e4e.has(r)||o.has(r)||l.enumerable&&"value"in l&&(i[r]=l.value);return i}function wF(e,t,n,i){var o;const s=(function(f){return Math.max(0,Math.ceil(f.scrollHeight||0)-Math.ceil(f.clientHeight||0))})(e),r=(function(f,h){return Number.isFinite(f)?Math.min(Math.max(0,f),h):0})(n,s);if(!i.isReverseFlexScrollRoot(e))return void(e.scrollTop=r);const l=Math.max(0,s-r),a=[-l,l];let u=a[0],c=Number.POSITIVE_INFINITY;for(const f of a){e.scrollTop=f;const h=i.getNormalizedScrollTop(e,t,!1),m=Math.abs(h-r);md&&(e.scrollTop=u)}function CF(e,t){let n=0,i=null,o=null;const s=()=>{const r=o;o=null,i=null,r&&(n=Date.now(),e(...r))};return function(...r){const l=Date.now(),a=t-(l-n);o=r,a<=0?(i&&(clearTimeout(i),i=null),n=l,o=null,e(...r)):i||(i=setTimeout(s,a))}}function AF(e){return e==="simple"?"simple":e===!0||e==="true"||e==="precise"?"precise":"off"}const Lq=Symbol("MarkstreamMathBlockMinHeightCache");function U8t(){return en(Lq,null)}const t4e=new Set(["text","inline_code","emoji","footnote_reference"]),n4e=new Set(["strong","emphasis","strikethrough","highlight","insert","subscript","superscript","link"]);function zg(e){const t=Number(e);return!Number.isFinite(t)||t<=0?-1:Math.round(t/32)}function vh(e,t,n,i=22){const o=String(e??"");if(!o)return n;const s=Math.max(18,Math.floor(Math.max(320,t)/8)),r=o.split(/\r?\n/).length,l=Math.ceil(o.length/s),a=Math.max(1,r,l);return Math.max(n,Math.ceil(a*i+12))}function Nq(e){var t;if(!e||typeof e!="object")return!1;const n=e,i=String((t=n.type)!=null?t:"");if(t4e.has(i))return!0;if(!n4e.has(i))return!1;const o=n.children;return!Array.isArray(o)||!o.length||o.every(Nq)}function WA(e){var t,n,i,o,s,r,l,a;if(!e||typeof e!="object")return"";const u=e,c=String((t=u.type)!=null?t:"");if(c==="text")return String((i=(n=u.content)!=null?n:u.raw)!=null?i:"");if(c==="inline_code")return String((r=(s=(o=u.code)!=null?o:u.content)!=null?s:u.raw)!=null?r:"");if(c==="emoji")return String((a=(l=u.name)!=null?l:u.raw)!=null?a:"");if(typeof u.text=="string")return u.text;const d=[];for(const f of["children","items","cells","rows"]){const h=u[f];if(Array.isArray(h)){const m=h.map(WA).filter(Boolean).join(" ");m&&d.push(m)}}return d.join(" ").replace(/\s+/g," ").trim()}function Fq(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="inline_code"||["children","items","cells","rows"].some(n=>{const i=t[n];return Array.isArray(i)&&i.some(Fq)})}function i4e(e,t){if(!e)return 30;const n=Math.max(18,Math.floor(Math.max(320,t)/8)),i=e.split(/\r?\n/).length,o=Math.ceil(e.length/n),s=Math.max(1,i,o);return 30+26*Math.max(0,s-1)}function o4e(e,t){var n,i,o,s,r,l,a,u,c,d,f,h,m,g;if(!e||typeof e!="object")return 32;const y=e,k=String((n=y.type)!=null?n:""),v=Number.isFinite(t)&&t>0?t:640;switch(k){case"heading":return(function(C){var w;const M=Number((w=C.level)!=null?w:C.depth);return M>=4?20:M===3?30:M===2?32:44})(y);case"paragraph":return(function(C,w){const M=String(C??"");if(!M)return 28;const L=Math.max(18,Math.floor(Math.max(320,w)/8)),E=M.split(/\r?\n/).length,S=Math.ceil(M.length/L);return Math.max(1,E,S)<=1?28:vh(M,w,34)})(String((o=(i=y.raw)!=null?i:y.content)!=null?o:""),v);case"list":return(function(C,w){var M;const L=Array.isArray(C.items)?C.items:[];if(!L.length)return 48;const E=Math.max(48,30*L.length+12);let S=12;for(const T of L)S+=i4e(WA(T)||String((M=T.raw)!=null?M:""),w);const x=Math.max(0,S-E);if(L.length>20){const T=Math.round(2.4*L.length);return Math.round(E+Math.max(T,Math.min(x,3*L.length)))}if(x<=0)return E;const A=L.length>8?8*L.length:x;return Math.round(E+Math.min(x,A))})(y,v);case"list_item":return vh(String((r=(s=y.raw)!=null?s:y.content)!=null?r:""),v,34);case"blockquote":return vh(String((a=(l=y.raw)!=null?l:y.content)!=null?a:""),v,56);case"table":return(function(C,w){const M=[...C.header?[C.header]:[],...Array.isArray(C.rows)?C.rows:[]];if(!M.length){const L=Array.isArray(C.children)?C.children.length:3;return Math.max(120,38*L+48)}return Math.max(120,Math.round(4+M.reduce((L,E)=>L+(function(S,x){const A=Math.max(1,S.length),T=Math.max(80,(x-32)/A),I=Math.max(10,Math.floor(T/8)),O=Math.max(1,...S.map(H=>{var R;const F=WA(H)||String((R=H?.raw)!=null?R:"");return Math.ceil(F.length/I)||1}));return 54+34*Math.max(0,O-1)+(A<=3&&S.some(Fq)?14:0)})((function(S){var x;return Array.isArray(S?.cells)&&(x=S.cells)!=null?x:[]})(E),w),0)))})(y,v);case"code_block":{const C=String((u=y.language)!=null?u:"").trim().toLowerCase(),w=String((d=(c=y.code)!=null?c:y.raw)!=null?d:"");return C==="mermaid"?fb(cb(w)):C==="infographic"?hb(db(w)):vh(w,v,96,20)}case"math_block":return 72;case"image":return 220;case"admonition":case"vmr_container":case"html_block":return(function(C,w){var M,L,E;const S=C.match(/^\s*]*)>/i);return S&&!/(?:^|\s)open(?:\s|=|$)/i.test((M=S[1])!=null?M:"")?vh(((E=(L=C.match(/]*>([\s\S]*?)<\/summary>/i))==null?void 0:L[1])==null?void 0:E.replace(/<[^>]*>/g,"").trim())||"Details",w,28,28):vh(C,w,96)})(String((h=(f=y.raw)!=null?f:y.content)!=null?h:""),v);case"thematic_break":return 24;default:return vh(String((g=(m=y.raw)!=null?m:y.content)!=null?g:""),v,40)}}function xF(e,t,n){return Math.min(Math.max(e,t),n)}const s4e=["total","cacheHits","appendHits","tailHits","fullParses","chunkedParses"],r4e=["tokenCloneMs","processTokensInputTokens","processTokensReusedTopLevelNodes","processTokensMs","safeMarkdownMs","tokenizeMs","htmlBlockPassesMs","parseMarkdownToStructureTotalMs"],l4e=new Set(["attrs","data","items","header","payload","props","rows","cells","term","definition","sourceMap"]),Dq=["raw","content","code","originalCode","updatedCode"],SF=new WeakMap,_F=new WeakMap;let a4e=1;function ou(){return typeof performance<"u"?performance.now():Date.now()}function IF(e){const t=e.stream;return t&&typeof t.stats=="function"?t.stats():null}function na(e){if(typeof e!="object"&&typeof e!="function"||e===null)return"";const t=e;let n=SF.get(t);return n||(n=a4e++,SF.set(t,n)),String(n)}function MF(e,t,n,i={}){var o,s;const r=i.includeFinal!==!1,l={md:na(t),customMarkdownIt:na(n),requireClosingStrong:e.requireClosingStrong===!0,customHtmlTags:(o=e.customHtmlTags)!=null?o:[],includeSourceMap:e.includeSourceMap===!0,streamParse:(s=e.streamParse)!=null?s:"auto",validateLink:na(e.validateLink),preTransformTokens:na(e.preTransformTokens),postTransformTokens:na(e.postTransformTokens),postTransformNodes:na(e.postTransformNodes)};return r&&(l.final=e.final===!0),JSON.stringify(l)}function TF(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===10;)t-=1;const n=e.lastIndexOf(` +`,t-1)+1;return e.slice(n,t).trim()}function EF(e){const t=Rq(e);return t.length>=2&&t.every(n=>{const i=n.trim();return i.length>=1&&i.replace(/^:/,"").replace(/:$/,"").split("").every(o=>o==="-")})}function Rq(e){return e.includes("|")?e.replace(/^\|/,"").replace(/\|$/,"").split("|"):[]}function Oq(e){let t=2166136261;for(let n=0;n>>0).toString(36)}function Qx(e){const t=String(e??"");return`${t.length}:${Oq(t)}`}function qA(e,t=new WeakMap,n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return String(e);if(typeof e=="string")return`s:${(function(r){return r.length<=8192?Qx(r):`${r.length}:${Oq(r.slice(0,8192))}:truncated`})(e)}`;if(typeof e=="function")return`fn:${na(e)}`;if(typeof e!="object")return typeof e;const i=e,o=t.get(i);if(o)return`cycle:${o}`;if(n>=6)return`object:${na(i)}`;const s=na(i);if(t.set(i,s),Array.isArray(e)){const r=e.slice(0,200);return`a:${e.length}:${r.map(l=>qA(l,t,n+1)).join(",")}`}if(typeof e=="object"){const r=e,l=Object.keys(r).sort(),a=l.slice(0,80);return`o:${l.length}:${a.sort().map(u=>`${u}:${qA(r[u],t,n+1)}`).join(";")}`}return typeof e}function wb(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.raw=="string"}function Pq(e,t=new WeakMap,n=0){return Array.isArray(e)?`a:${e.length}:${e.slice(0,200).map(i=>wb(i)?Tf(i,t,n+1):Pq(i,t,n+1)).join(",")}`:wb(e)?Tf(e,t,n):qA(e,t,n)}function u4e(e,t,n){return Object.keys(e).sort().filter(i=>i!=="children"&&!Dq.includes(i)).map(i=>{const o=e[i];return typeof o=="string"?`${i}=s:${Qx(o)}`:typeof o=="number"||typeof o=="boolean"||o==null?`${i}=${String(o)}`:typeof o=="function"?`${i}=fn:${na(o)}`:l4e.has(i)&&(Array.isArray(o)||typeof o=="object")?`${i}=${Pq(o,t,n+1)}`:o&&typeof o=="object"?`${i}=object:${na(o)}`:""}).filter(Boolean).join(";")}function c4e(e){return Dq.map(t=>{const n=e[t];return typeof n=="string"?`${t}=s:${Qx(n)}`:""}).filter(Boolean).join(";")}function Tf(e,t=new WeakMap,n=0){const i=_F.get(e);if(i)return i;const o=e,s=t.get(o);if(s)return`node-cycle:${s}`;if(n>=6)return`node:${e.type}:${na(o)}`;const r=na(o);t.set(o,r);const l=(function(a,u,c){const d=a,f=Array.isArray(d.children)?d.children:[],h=f.length?f.slice(0,200).map(m=>Tf(m,u,c+1)).join("|"):"";return[a.type,c4e(d),u4e(d,u,c),f.length,h].join(":")})(e,t,n);return _F.set(o,l),l}function Bq(e,t){return Tf(e)===Tf(t)}function Yx(e,t,n){const i=ou(),o=t==="stabilizeSignatureMs"?"stabilizeSignatureCallCount":"primeSignatureCallCount";try{return n()}finally{e[t]+=ou()-i,e[o]+=1,e.signatureMs=e.stabilizeSignatureMs+e.primeSignatureMs,e.signatureCallCount=e.stabilizeSignatureCallCount+e.primeSignatureCallCount}}function LF(e,t,n){return Yx(t,n,()=>Tf(e))}function $q(e,t,n){return LF(e,n,"stabilizeSignatureMs")===LF(t,n,"stabilizeSignatureMs")}function Oy(e){return{reusedNodeCount:0,dirtyStartIndex:e>0?0:-1,stablePrefixNodeCount:0,dirtyTailNodeCount:e}}function NF(e,t,n){return e<0?0:Math.max(t.length,n.length)-e}function FF(e){return e.__markstreamHasCustomParserExtensions===!0||(function(t){var n;return Number((n=t.__markstreamRegisteredPluginCount)!=null?n:0)>0})(e)}function d4e(e,t){return e.length===t.length&&e===t}function Jx(e,t,n=0){if(n>=4)return null;if(e.type!==t.type)return!1;const i=e,o=t,s=Object.keys(i).filter(c=>c!=="type"&&c!=="children").sort(),r=Object.keys(o).filter(c=>c!=="type"&&c!=="children").sort();if(s.length!==r.length)return!1;for(let c=0;c{i=Jx(e,t)}),i??$q(e,t,n)}function p4e(e,t){const n={};for(const i of s4e){const o=e[i],s=t?.[i];typeof o=="number"&&(n[i]=o-(typeof s=="number"?s:0))}return n}function m4e(e,t){var n;const i=TN(t.instanceMsgId),o=new Map,s=(n=t.smoothStreamingEnabled)!=null?n:D(()=>!1),r=q(t.renderContent.value);let l=[],a="",u="",c="",d=!1;const f=(function(){let H="",R=0,F=!1,P=!1,z=!1,W=!1;function $(){H="",R=0,F=!1,P=!1,z=!1,W=!1}function K(ne){let G=!1;for(let te=0;te{if(!ne||!G.startsWith(ne)||G.length<=ne.length)return $(),[!0,0];let te=0;H!==ne&&($(),K(ne),te=ne.length);const le=G.slice(ne.length),ie=K(le);return H=G,[ie,te+le.length]}})();let h,m=0,g=0,y=ou(),k=-1,v=0;function C(H){k=Number.isInteger(H)?H:0,v+=1}function w(){h&&(clearTimeout(h),h=void 0)}function M(){w();const H=t.renderContent.value;r.value!==H&&(r.value=H),y=ou()}ze([t.renderContent,t.effectiveFinal,s],([H,R,F])=>{r.value!==H&&(!F||R||(function(P,z){if(!P&&z||z.length<=80||z.length\s*|`{3,}|~{3,})/.test(W))||W.endsWith(` +`)&&!(function($){const K=TF($);if(EF(K))return!1;const ne=Rq(K);return ne.length>=2&&ne.some(G=>G.trim())})(z))})(r.value,H)?M():(function(){if(g+=1,h)return;const P=Math.max(0,(function(z){const W=z.parseCoalesceMs;return typeof W=="number"&&Number.isFinite(W)&&W>=0?W:80})(e)-(ou()-y));P<=0?M():h=setTimeout(M,P)})())},{flush:"sync",immediate:!0}),cd(w);const L=D(()=>{var H,R,F,P;return hme(e.customHtmlTags,(H=e.parseOptions)==null?void 0:H.customHtmlTags,(P=(F=(R=t.customComponentsMap)==null?void 0:R.value)!=null?F:{},Object.entries(P).map(([z,W])=>{const $=Va(z);return W==null||!$||v2($)||UH.has($)||f2.has($)?"":$}).filter(Boolean)))}),E=D(()=>{const{key:H,tags:R}=pme(L.value);if(!H)return i;const F=o.get(H);if(F)return F;const P=TN(t.instanceMsgId,{customHtmlTags:R});return o.set(H,P),P}),S=D(()=>{const H=E.value;if(!e.customMarkdownIt)return H;const R=e.customMarkdownIt(H);return H.__markstreamHasCustomParserExtensions=!0,R.__markstreamHasCustomParserExtensions=!0,R}),x=D(()=>{var H,R;const F=(H=e.parseOptions)!=null?H:{},P=t.effectiveFinal.value,z=L.value,W=P!=null,$=z.length>0;return W||$||F.streamParse==null?Bt(Bt(Dn(Bt({},F),{streamParse:(R=F.streamParse)==null||R}),W?{final:P}:{}),$?{customHtmlTags:z}:{}):F}),A=D(()=>{var H;return new Set(((H=x.value.customHtmlTags)!=null?H:[]).map(R=>String(R).trim().toLowerCase()).filter(Boolean))}),T=D(()=>MF(x.value,S.value,e.customMarkdownIt,{includeFinal:!0})),I=D(()=>MF(x.value,S.value,e.customMarkdownIt,{includeFinal:!1}));ze([T,I],([H,R],[F,P])=>{F&&(H===F&&R===P||(M(),R!==P&&(l=[],c="")))},{flush:"sync"});const O=D(()=>{var H,R,F,P,z,W,$,K,ne,G,te;if((H=e.nodes)!=null&&H.length)return l=[],c="",C(0),Lt(e.nodes.slice());const le=r.value;if(!le)return l=[],c="",C(-1),[];const ie=t.debugPerformanceEnabled.value,_e=ie?ou():0,Z=S.value,se=T.value,he=I.value;a&&se!==a&&(function(Ae){var Ne,Ze;(Ze=(Ne=Ae.stream)==null?void 0:Ne.reset)==null||Ze.call(Ne)})(Z),u&&he!==u&&(l=[],c="");const Y=Object.keys((F=(R=t.customComponentsMap)==null?void 0:R.value)!=null?F:{}).length>0||typeof x.value.postTransformNodes=="function";Y!==d&&(l=[],c="");const J=!Y&&l.length>0&&le.startsWith(c)&&he===u,U=ie?IF(Z):null,Q=ie?{}:void 0,ue=FF(Z),me=!ue&&!Y,pe=Bt(Bt(Dn(Bt({},x.value),{__reuseStableTopLevelNodes:me}),ue?{__disableStreamParse:!0}:{}),Q?{__timing:Q}:{}),ee=GW(le,Z,pe),re=ie?ou():0,ge=ie?{signatureMs:0,stabilizeSignatureMs:0,primeSignatureMs:0,signatureCallCount:0,stabilizeSignatureCallCount:0,primeSignatureCallCount:0}:void 0;let ae,Ce=ie?Oy(ee.length):void 0,ve=0,ce=0,Te=0;if(J){const Ae=ie?ou():0,[Ne,Ze]=(function(pt){var Rt,Ot;const[Fe,Pe]=pt.scanGlobalReferenceAppend(pt.previousContent,pt.content),be=pt.parseOptions;return[pt.previousDirtyStartIndex>0&&be.final!==!0&&!pt.customMarkdownIt&&!FF(pt.md)&&!Fe&&typeof be.preTransformTokens!="function"&&typeof be.postTransformTokens!="function"&&typeof be.postTransformNodes!="function"&&((Ot=(Rt=be.customHtmlTags)==null?void 0:Rt.length)!=null?Ot:0)===0?pt.previousDirtyStartIndex:0,Pe]})({content:le,previousContent:c,previousDirtyStartIndex:k,parseOptions:x.value,customMarkdownIt:e.customMarkdownIt,md:Z,scanGlobalReferenceAppend:f});Te=Ze;const rt=Ne<=0;if(ge){const pt=(function(Rt,Ot,Fe,Pe={}){var be;if(!Ot.length)return{nodes:Rt,metrics:Oy(Rt.length)};const Oe=(be=Pe.scanStartIndex)!=null?be:0,Ke=Pe.reuseDirtyTail!==!1,Qe=(function(Se,We,ut,Tt=0){const tt=Math.min(Se.length,We.length);for(let Ve=Math.min(tt,Math.max(0,Tt));VeTf(Ae[rt]))})(ae,ge,ce):(function(Ae,Ne=0){for(let Ze=Math.max(0,Ne);Ze((z=U?.total)!=null?z:0);t.logPerf(Ne?"parse(stream)":"parse(sync)",Bt(Bt(Bt({rendererId:t.instanceMsgId,ms:Math.round(ou()-_e),nodes:ae.length,contentLength:le.length,parseCommitCount:m,parseCoalescedCount:g,nodeReuseMs:ke,referenceDefinitionScanChars:Te,signatureMs:(W=ge?.signatureMs)!=null?W:0,stabilizeSignatureMs:($=ge?.stabilizeSignatureMs)!=null?$:0,primeSignatureMs:(K=ge?.primeSignatureMs)!=null?K:0,signatureCallCount:(ne=ge?.signatureCallCount)!=null?ne:0,stabilizeSignatureCallCount:(G=ge?.stabilizeSignatureCallCount)!=null?G:0,primeSignatureCallCount:(te=ge?.primeSignatureCallCount)!=null?te:0,stabilizeMs:ve},Ce??{}),Q?Object.fromEntries(r4e.map(Ze=>{var rt;return[Ze,(rt=Q[Ze])!=null?rt:0]})):{}),Ae?{streamMode:Ae.lastMode,streamDelta:p4e(Ae,U),streamStats:Ae}:{}))}return Lt(ae)});return{effectiveCustomHtmlTags:L,effectiveCustomHtmlTagsSet:A,mdBase:E,mdInstance:S,mergedParseOptions:x,getParsedNodesDirtyStartIndex:()=>k,getParsedNodesRevision:()=>v,parsedNodes:O}}function g4e(e){const{isClient:t}=e,n=q(new Set),i=new Map,o=new Map,s=new Map;function r(u){if(!t)return;const c=s.get(u);c!=null&&(window.clearTimeout(c),s.delete(u))}function l(){if(t)for(const u of s.values())window.clearTimeout(u);s.clear()}function a(){n.value=new Set}return{visibleNodeIndices:n,nodeVisibilityHandles:i,nodeVisibilityWatchStops:o,nodeVisibilityFallbackTimers:s,clearVisibilityFallback:r,clearAllVisibilityFallbacks:l,markNodeVisible:function(u,c=!0){var d;c&&r(u),(function(f,h){if((g=(m=e.shouldTrackVisibleNodeIndices)==null?void 0:m.call(e))!=null&&!g)return;var m,g;const y=n.value,k=y.has(f);if(h){if(k)return;const C=new Set(y);return C.add(f),void(n.value=C)}if(!k)return;const v=new Set(y);v.delete(f),n.value=v})(u,c),c&&((d=e.onNodeMarkedVisible)==null||d.call(e,u))},resetNodeVisibleState:a,cleanupNodeVisibility:function(u){var c;if(e.shouldCleanupNodeVisibility&&!e.shouldCleanupNodeVisibility())return;for(const[f,h]of o.entries())f{const c=o.getSnapshot();t.value=c.source,n.value=c.visible,i.value=c.done},r=o.subscribe(s);s();const l=D(()=>Math.max(0,t.value.length-n.value.length)),a=D(()=>l.value===0),u=D(()=>i.value&&a.value);return jm()&&cd(()=>{r(),o.destroy()}),{source:t,visible:n,done:i,final:u,caughtUp:a,pendingChars:l,enqueue:c=>o.enqueue(c),finish:c=>o.finish(c),flush:()=>o.flush(),reset:c=>o.reset(c),pause:()=>o.pause(),resume:()=>o.resume()}}const y4e={maxCharsPerSecond:3e3,maxCommitFps:20,maxCharsPerCommit:160,catchUpLatencyMs:220,catchUpThreshold:400},DF=/auto|scroll|overlay/i;function k4e(e){if(!e)return!1;const t=(e.overflowY||"").toLowerCase(),n=(e.overflow||"").toLowerCase();return DF.test(t)||DF.test(n)}function b4e(e){const t=Math.ceil(e.scrollHeight)>Math.ceil(e.clientHeight)+1,n=Math.ceil(e.scrollWidth)>Math.ceil(e.clientWidth)+1;return t||n}const w4e={class:"m-0 p-0"},C4e=["data-probe"],A4e=Ei(ot(Dn(Bt({},{name:"HeightEstimationProbes"}),{__name:"HeightEstimationProbes",props:{width:{},flowRoot:{type:Boolean},paragraphNode:{},listItemNode:{},listNode:{},headingNodes:{},setParagraphWrapper:{type:Function},setListItemWrapper:{type:Function},setListWrapper:{type:Function},setHeadingWrapper:{type:Function}},setup(e){const t=e;function n(i){var o,s;return(s=(o=t.headingNodes)==null?void 0:o[i])!=null?s:null}return(i,o)=>(b(),N("div",{class:"height-estimation-probes",style:on({width:`${e.width}px`}),"aria-hidden":"true"},[_("div",{ref:s=>e.setParagraphWrapper(s),class:De(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":"paragraph"},[V(p(rp),{node:e.paragraphNode,"index-key":"probe-paragraph"},null,8,["node"])],2),_("div",{ref:s=>e.setListItemWrapper(s),class:De(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":"list-item"},[_("ul",w4e,[V(p(am),{node:e.listItemNode,"index-key":"probe-list-item"},null,8,["node"])])],2),_("div",{ref:s=>e.setListWrapper(s),class:De(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":"list"},[V(p(um),{node:e.listNode,"index-key":"probe-list"},null,8,["node"])],2),(b(),N(Le,null,Ct(6,s=>_("div",{key:`probe-heading-${s}`,ref_for:!0,ref:r=>e.setHeadingWrapper(s,r),class:De(["node-content",{"node-content-flow-root":e.flowRoot}]),"data-probe":`heading-${s}`},[V(p(Z4),{node:n(s),"index-key":`probe-heading-${s}`},null,8,["node","index-key"])],10,C4e)),64))],4))}})),[["__scopeId","data-v-3e0766e2"]]),RF=ot({name:"InfographicBlockNodeLoading",props:{node:{type:Object,required:!0},showHeader:{type:Boolean,default:!0},estimatedPreviewHeightPx:{type:Number,default:void 0}},setup(e){const t=D(()=>{var n,i;return hb((i=O1(e.estimatedPreviewHeightPx))!=null?i:db(String((n=e.node.code)!=null?n:"")))});return()=>{var n;return Fn("div",{class:"infographic-block-container rounded-lg border overflow-hidden",style:{margin:"var(--ms-flow-diagram-y) 0",background:"var(--diagram-bg)",borderColor:"var(--diagram-border)",color:"hsl(var(--ms-foreground))"},"data-markstream-infographic":"1","data-markstream-mode":"pending"},[e.showHeader?Fn("div",{class:"infographic-block-header flex justify-between items-center border-b",style:{padding:"var(--ms-inset-panel-y) var(--ms-inset-panel-x)",background:"var(--diagram-header-bg)",borderColor:"var(--diagram-border)",minHeight:"calc(var(--ms-action-btn-icon) + var(--ms-action-btn-padding) + var(--ms-action-btn-padding) + var(--ms-inset-panel-y) + var(--ms-inset-panel-y) + 1px)"}},[Fn("div",{class:"flex items-center gap-x-2 overflow-hidden"},[Fn("span",{class:"icon-slot action-icon shrink-0",style:{display:"inline-flex",width:"var(--ms-action-btn-icon)",height:"var(--ms-action-btn-icon)"}}),Fn("span",{class:"infographic-label font-medium font-mono truncate",style:{fontSize:"var(--ms-text-label)",color:"hsl(var(--ms-muted-foreground))"}},"Infographic")]),Fn("div",{class:"infographic-header-actions flex items-center opacity-0 pointer-events-none",style:{gap:"var(--ms-gap-header-actions)"},"aria-hidden":"true"},Array.from({length:4},()=>Fn("span",{class:"infographic-action-btn inline-flex items-center justify-center p-[var(--ms-action-btn-padding)] rounded",style:{width:"calc(var(--ms-action-btn-icon) + var(--ms-action-btn-padding) + var(--ms-action-btn-padding))",height:"calc(var(--ms-action-btn-icon) + var(--ms-action-btn-padding) + var(--ms-action-btn-padding))"}})))]):null,Fn("div",{class:"infographic-preview relative overflow-hidden block",style:{height:`${t.value}px`,minHeight:"var(--ms-size-diagram-min-height)",background:"var(--diagram-bg)"}},[Fn("pre",{class:"infographic-pending-source text-sm font-mono whitespace-pre-wrap",style:{position:"absolute",inset:"0",zIndex:"1",margin:"0",padding:"var(--ms-inset-panel-body)",overflow:"auto",textAlign:"left"}},String((n=e.node.code)!=null?n:"")),Fn("div",{class:"absolute inset-0"},[Fn("div",{class:"w-full text-center flex items-center justify-center min-h-full"})])])])}}}),OF=ot({name:"MermaidBlockNodeLoading",props:{node:{type:Object,required:!0},showHeader:{type:Boolean,default:!0},estimatedPreviewHeightPx:{type:Number,default:void 0}},setup(e){const t=D(()=>{var n,i;return fb((i=O1(e.estimatedPreviewHeightPx))!=null?i:cb(String((n=e.node.code)!=null?n:"")))});return()=>{var n;return Fn("div",{class:"mermaid-block-container rounded-lg border overflow-hidden",style:{margin:"var(--ms-flow-diagram-y) 0",borderColor:"var(--diagram-border)"},"data-markstream-mermaid":"1","data-markstream-mode":"pending"},[e.showHeader?Fn("div",{class:"mermaid-block-header flex justify-between items-center border-b px-[var(--ms-inset-panel-x)] py-[var(--ms-inset-panel-y)]",style:{background:"var(--diagram-header-bg)",borderColor:"var(--diagram-border)"}},[Fn("div",{class:"flex items-center gap-x-2 overflow-hidden"},[Fn("span",{class:"mermaid-label-text text-[length:var(--ms-text-label)] font-medium font-mono truncate",style:{color:"var(--code-action-fg)"}},"Mermaid")]),Fn("div",{class:"mermaid-header-actions flex items-center gap-[var(--ms-gap-header-actions)] opacity-0 pointer-events-none","aria-hidden":"true"},Array.from({length:4},()=>Fn("span",{class:"mermaid-action-btn inline-flex items-center justify-center p-[var(--ms-action-btn-padding)] rounded"},[Fn("span",{class:"action-icon block"})])))]):null,Fn("div",{class:"mermaid-preview-area relative overflow-hidden block",style:{height:`${t.value}px`,minHeight:"var(--ms-size-diagram-min-height)",background:"var(--diagram-bg)"}},[Fn("pre",{class:"mermaid-source-code text-sm font-mono whitespace-pre-wrap",style:{position:"absolute",inset:"0",margin:"0",padding:"var(--ms-inset-panel-body)",overflow:"auto",textAlign:"left"}},String((n=e.node.code)!=null?n:"")),Fn("div",{class:"_mermaid w-full text-center flex items-center justify-center min-h-full",style:{fontFamily:"inherit",contentVisibility:"auto",contain:"content",containIntrinsicSize:"var(--ms-size-diagram-min-height) 240px"}})])])}}}),x4e={docs:{showTooltips:!0,fade:!0,batchRendering:!0,initialRenderBatchSize:40,renderBatchSize:80,renderBatchDelay:16,renderBatchBudgetMs:6,renderBatchIdleTimeoutMs:120,deferNodesUntilVisible:!0,maxLiveNodes:220,liveNodeBuffer:60,nodeVirtual:"auto"},chat:{showTooltips:!1,fade:!1,batchRendering:!0,initialRenderBatchSize:32,renderBatchSize:48,renderBatchDelay:6,renderBatchBudgetMs:8,renderBatchIdleTimeoutMs:60,deferNodesUntilVisible:!0,maxLiveNodes:0,liveNodeBuffer:0,nodeVirtual:"auto"},minimal:{showTooltips:!1,fade:!1,batchRendering:!0,initialRenderBatchSize:32,renderBatchSize:48,renderBatchDelay:6,renderBatchBudgetMs:8,renderBatchIdleTimeoutMs:60,deferNodesUntilVisible:!0,maxLiveNodes:0,liveNodeBuffer:0,nodeVirtual:"auto"}};function Vs(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}const S4e=["data-custom-id"],_4e=["data-node-index","data-node-type"],PF="typewriter-simple-cursor-target",zq=Ei(ot(Dn(Bt({},{name:"NodeRenderer"}),{__name:"NodeRenderer",props:{content:{},nodes:{},final:{type:Boolean},parseOptions:{},customMarkdownIt:{},debugPerformance:{type:Boolean,default:!1},customHtmlTags:{},mode:{},domMode:{},htmlPolicy:{},viewportPriority:{type:Boolean,default:void 0},viewportPriorityOptions:{},codeBlockStream:{type:Boolean,default:!0},codeBlockDarkTheme:{},codeBlockLightTheme:{},codeBlockMonacoOptions:{},codeRenderer:{},renderCodeBlocksAsPre:{type:Boolean,default:void 0},codeBlockMinWidth:{},codeBlockMaxWidth:{},codeBlockProps:{},mermaidProps:{},d2Props:{},infographicProps:{},showTooltips:{type:Boolean,default:void 0},themes:{},langs:{},isDark:{type:Boolean},customId:{},indexKey:{},typewriter:{type:[Boolean,String],default:!1},smoothStreaming:{type:[Boolean,String],default:"auto"},smoothStreamingOptions:{},parseCoalesceMs:{},fade:{type:Boolean,default:void 0},batchRendering:{type:Boolean,default:void 0},initialRenderBatchSize:{},renderBatchSize:{},renderBatchDelay:{},renderBatchBudgetMs:{},renderBatchIdleTimeoutMs:{},deferNodesUntilVisible:{type:Boolean,default:void 0},maxLiveNodes:{},liveNodeBuffer:{},nodeVirtual:{type:[Boolean,String],default:void 0},virtualScroll:{},renderAsFragment:{type:Boolean}},emits:["copy","copy-code","handleArtifactClick","click","mouseover","mouseout","virtual-state-change","height-change","render-settled","render-final","anchor-change"],setup(e,{expose:t,emit:n}){const i=e,o=n;function s(j){if(!(typeof Event<"u"&&j instanceof Event))return typeof j=="string"&&o("copy-code",j),void o("copy",j)}const r=gs(),l=en("markstreamNestedRendererProps",void 0);function a(j){const oe=r?.vnode.props;return!!oe&&(Object.prototype.hasOwnProperty.call(oe,j)||Object.prototype.hasOwnProperty.call(oe,String(j).replace(/[A-Z]/g,ye=>`-${ye.toLowerCase()}`)))}function u(j){var oe,ye;const we=i[j];return a(j)?we:(ye=(oe=l?.value)==null?void 0:oe[j])!=null?ye:we}const c=D(()=>{return(j=u("mode"))==="chat"||j==="minimal"||j==="docs"?j:"docs";var j}),d=D(()=>AF(u("typewriter"))),f=D(()=>d.value!=="off"),h=D(()=>u("domMode")==="minimal"?"minimal":"full"),m=D(()=>{return(j={mode:c.value,codeRenderer:u("codeRenderer"),renderCodeBlocksAsPre:u("renderCodeBlocksAsPre")}).renderCodeBlocksAsPre===!0?"pre":j.codeRenderer==="pre"||j.codeRenderer==="shiki"||j.codeRenderer==="monaco"?j.codeRenderer:j.renderCodeBlocksAsPre===!1||j.mode==="docs"?"monaco":"pre";var j}),g=D(()=>x4e[c.value]),y=D(()=>{var j;return(j=u("showTooltips"))!=null?j:g.value.showTooltips}),k=D(()=>{var j;return(j=u("fade"))!=null?j:g.value.fade}),v=D(()=>{var j;return(j=u("batchRendering"))!=null?j:g.value.batchRendering}),C=D(()=>{var j;return(j=u("initialRenderBatchSize"))!=null?j:g.value.initialRenderBatchSize}),w=D(()=>{var j;return(j=u("renderBatchSize"))!=null?j:g.value.renderBatchSize}),M=D(()=>{var j;return(j=u("renderBatchDelay"))!=null?j:g.value.renderBatchDelay}),L=D(()=>{var j;return(j=u("renderBatchBudgetMs"))!=null?j:g.value.renderBatchBudgetMs}),E=D(()=>{var j;return(j=u("renderBatchIdleTimeoutMs"))!=null?j:g.value.renderBatchIdleTimeoutMs}),S=D(()=>{var j;return(j=u("deferNodesUntilVisible"))!=null?j:g.value.deferNodesUntilVisible}),x=D(()=>{var j;return(j=u("maxLiveNodes"))!=null?j:g.value.maxLiveNodes}),A=D(()=>{var j;return(j=u("liveNodeBuffer"))!=null?j:g.value.liveNodeBuffer}),T=D(()=>{var j;return(j=u("nodeVirtual"))!=null?j:g.value.nodeVirtual}),I={get content(){return i.content},get nodes(){return i.nodes},get final(){return i.final},get parseOptions(){return u("parseOptions")},get customMarkdownIt(){return u("customMarkdownIt")},get debugPerformance(){return i.debugPerformance},get customHtmlTags(){return u("customHtmlTags")},get mode(){return u("mode")},get domMode(){return h.value},get htmlPolicy(){return u("htmlPolicy")},get viewportPriority(){return u("viewportPriority")},get viewportPriorityOptions(){return u("viewportPriorityOptions")},get codeBlockStream(){return u("codeBlockStream")},get codeBlockDarkTheme(){return u("codeBlockDarkTheme")},get codeBlockLightTheme(){return u("codeBlockLightTheme")},get codeBlockMonacoOptions(){return u("codeBlockMonacoOptions")},get codeRenderer(){return u("codeRenderer")},get renderCodeBlocksAsPre(){return u("renderCodeBlocksAsPre")},get codeBlockMinWidth(){return u("codeBlockMinWidth")},get codeBlockMaxWidth(){return u("codeBlockMaxWidth")},get codeBlockProps(){return u("codeBlockProps")},get mermaidProps(){return u("mermaidProps")},get d2Props(){return u("d2Props")},get infographicProps(){return u("infographicProps")},get showTooltips(){return y.value},get themes(){return u("themes")},get langs(){return u("langs")},get isDark(){return u("isDark")},get customId(){return u("customId")},get indexKey(){return i.indexKey},get typewriter(){return u("typewriter")},get smoothStreaming(){return i.smoothStreaming},get smoothStreamingOptions(){return u("smoothStreamingOptions")},get parseCoalesceMs(){return u("parseCoalesceMs")},get fade(){return k.value},get batchRendering(){return v.value},get initialRenderBatchSize(){return C.value},get renderBatchSize(){return w.value},get renderBatchDelay(){return M.value},get renderBatchBudgetMs(){return L.value},get renderBatchIdleTimeoutMs(){return E.value},get deferNodesUntilVisible(){return S.value},get maxLiveNodes(){return x.value},get liveNodeBuffer(){return A.value},get nodeVirtual(){return T.value},get virtualScroll(){return i.virtualScroll},get renderAsFragment(){return i.renderAsFragment}};function O(j){o("height-change",j)}function H(j){o("virtual-state-change",j)}function R(j){o("anchor-change",j)}const F=q(),P=q(null),z=q(null),W=q(null),$=po({1:null,2:null,3:null,4:null,5:null,6:null}),K=q(!1),ne=new Map,G=q(0),te=q(0),le=q({paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}});function ie(j,oe){return typeof j!="string"?oe:j.trim()||oe}function _e(j){const oe=Number(j);return Number.isFinite(oe)&&oe>0?Math.max(1,Math.trunc(oe)):640}const Z=D(()=>{var j;const oe=(j=I.viewportPriorityOptions)!=null?j:{},ye=ie(oe.rootMargin,gp);return{rootMargin:ye,heavyBlockMargin:ie(oe.heavyBlockMargin,ye),maxTargets:_e(oe.maxTargets)}}),se=D(()=>{var j;return(j=Z.value.rootMargin)!=null?j:gp}),he=D(()=>{var j;return(j=Z.value.maxTargets)!=null?j:640});function Y(){var j,oe;if(((j=i.virtualScroll)==null?void 0:j.enabled)!==!0)return null;const ye=(oe=i.virtualScroll)==null?void 0:oe.scrollRoot;return J(typeof ye=="function"?ye():ye)}function J(j){return j?typeof HTMLElement<"u"&&j instanceof HTMLElement?j:typeof j=="object"&&"value"in j?J(j.value):typeof j=="object"&&"$el"in j?J(j.$el):null:null}Gn(Aq,Z);const{isClient:U,renderAsFragment:Q,debugPerformanceEnabled:ue,resolvedShowTooltips:me,resolvedHtmlPolicy:pe,inheritedSmoothStreaming:ee,ownsTypewriterCursor:re}=(function(j){const oe=typeof window<"u",ye=qm(),we=en("markstreamHtmlPolicy",void 0),Ee=en("markstreamTypewriterCursor",void 0),He=en("markstreamSmoothStreaming",void 0),Je=D(()=>j.renderAsFragment===!0),nt=D(()=>!!(j.debugPerformance&&oe&&typeof console<"u")),vt=D(()=>{var gt;if(typeof j.showTooltips=="boolean")return j.showTooltips;const Xe=(gt=ye.showTooltips)!=null?gt:ye["show-tooltips"];return Xe===""||Xe===!0||Xe==="true"||Xe!==!1&&Xe!=="false"&&void 0}),it=D(()=>{var gt,Xe;return(Xe=(gt=j.htmlPolicy)!=null?gt:we?.value)!=null?Xe:"safe"}),lt=D(()=>Ee?.value!==!0);return{isClient:oe,renderAsFragment:Je,debugPerformanceEnabled:nt,resolvedShowTooltips:vt,resolvedHtmlPolicy:it,inheritedSmoothStreaming:He,inheritedTypewriterCursor:Ee,ownsTypewriterCursor:lt}})(I),{resolveViewportRoot:ge,resolveScrollContainer:ae,isReverseFlexScrollRoot:Ce,getNormalizedScrollTop:ve,getOffsetTopWithinRoot:ce}=(function(j,oe){function ye(){var nt,vt;return(vt=(nt=oe.scrollRoot)==null?void 0:nt.call(oe))!=null?vt:null}function we(nt){if(typeof window>"u")return null;const vt=ye();if(vt)return vt;const it=nt??j.value;if(!it)return null;const lt=it.ownerDocument||document,gt=lt.scrollingElement||lt.documentElement;let Xe=it;for(;Xe&&Xe!==lt.body&&Xe!==gt;){if(k4e(window.getComputedStyle(Xe))&&b4e(Xe))return Xe;Xe=Xe.parentElement}return null}function Ee(nt){if(!oe.isClient)return!1;try{const vt=window.getComputedStyle(nt);return!!(vt.display||"").toLowerCase().includes("flex")&&(vt.flexDirection||"").toLowerCase().endsWith("reverse")}catch{return!1}}function He(nt,vt,it){var lt,gt;if(it)return Je(vt);const Xe=nt.scrollTop;if(!Ee(nt))return Xe;const at=Xe<0?-Xe:Xe;return Math.max(0,((lt=nt.scrollHeight)!=null?lt:0)-((gt=nt.clientHeight)!=null?gt:0))-at}function Je(nt){var vt,it,lt,gt,Xe;const at=Number((vt=nt.scrollingElement)==null?void 0:vt.scrollTop),It=Number((lt=(it=nt.documentElement)==null?void 0:it.scrollTop)!=null?lt:0),At=Number((Xe=(gt=nt.body)==null?void 0:gt.scrollTop)!=null?Xe:0);return Math.max(0,Number.isFinite(at)?at:0,Number.isFinite(It)?It:0,Number.isFinite(At)?At:0)}return{resolveViewportRoot:we,resolveScrollContainer:function(nt){var vt,it,lt,gt;const Xe=ye();if(Xe)return Xe;const at=we((vt=nt??j.value)!=null?vt:null);if(at)return at;const It=(gt=(lt=nt?.ownerDocument)!=null?lt:(it=j.value)==null?void 0:it.ownerDocument)!=null?gt:typeof document<"u"?document:null;return It?.scrollingElement||It?.documentElement||null},isReverseFlexScrollRoot:Ee,getNormalizedScrollTop:He,getOffsetTopWithinRoot:function(nt,vt){const it=vt.ownerDocument||nt.ownerDocument||document;if((function(at,It){return at===It.documentElement||at===It.body||at===It.scrollingElement})(vt,it))return nt.getBoundingClientRect().top+Je(it);const lt=vt.getBoundingClientRect(),gt=nt.getBoundingClientRect(),Xe=He(vt,it,!1);return gt.top-lt.top+Xe}}})(F,{isClient:U,scrollRoot:Y});Gn("markstreamShowTooltips",me),Gn("markstreamHtmlPolicy",pe),Gn("markstreamTypewriter",f),Gn("markstreamFade",D(()=>I.fade!==!1)),Gn("markstreamTypewriterCursor",D(()=>!0)),Gn("markstreamTextStreamState",ne),Gn("markstreamStreamVersion",G),Gn("markstreamParseOptions",D(()=>I.parseOptions)),Gn("markstreamCustomMarkdownIt",D(()=>I.customMarkdownIt));const{smoothStreamingEnabled:Te,renderContent:ke,requestedFinal:Ae,effectiveFinal:Ne}=(function(j,oe){const ye=v4e(Bt(Bt({},y4e),j.smoothStreamingOptions)),we=D(()=>{var Xe,at,It;return j.smoothStreaming!==!1&&!((Xe=j.nodes)!=null&&Xe.length)&&(j.smoothStreaming===!0||!((at=oe.inheritedSmoothStreaming)!=null&&at.value))&&(j.smoothStreaming===!0||AF(j.typewriter)!=="off"||((It=j.maxLiveNodes)!=null?It:0)<=0)}),Ee=q(!oe.isClient||j.smoothStreaming===!0);gn(()=>{Ee.value=!0});const He=D(()=>Ee.value&&we.value),Je=D(()=>{var Xe;return He.value?ye.visible.value:(Xe=j.content)!=null?Xe:""}),nt=D(()=>{var Xe,at;const It=(Xe=j.parseOptions)!=null?Xe:{};return(at=j.final)!=null?at:It.final}),vt=D(()=>{const Xe=nt.value;return He.value&&Xe!=null?!!Xe&&ye.caughtUp.value:Xe});let it=0,lt=!1;function gt(){it=0,lt=!1}return ze([()=>j.content,()=>j.nodes,He,nt],([Xe,at,It,At])=>{if(at?.length)return gt(),void ye.reset("");const Ut=Xe??"";if(!It)return gt(),ye.reset(Ut),void(At&&ye.finish({flush:!0}));const Dt=ye.source.value;if(Ut){if(Ut!==Dt)if(Ut.startsWith(Dt)){const rn=Ut.slice(Dt.length),cn=ye.pendingChars.value;rn.length<=8?(it++,lt||it>=2&&cn<=8?(lt=!0,ye.reset(Ut)):ye.enqueue(rn)):(gt(),ye.enqueue(rn))}else gt(),ye.reset(Ut)}else gt(),ye.reset("");At&&ye.finish()},{immediate:!0}),{smoothStream:ye,smoothStreamingEligible:we,smoothStreamingEnabled:He,renderContent:Je,requestedFinal:nt,effectiveFinal:vt}})(I,{isClient:U,inheritedSmoothStreaming:ee}),Ze=Ae.value===!0;Gn("markstreamSmoothStreaming",Te);const rt=q(!1),pt=q(!1),Rt=q(!1);let Ot="",Fe=!1,Pe=null;function be(){U&&Pe!=null&&(window.clearTimeout(Pe),Pe=null)}function Oe(){rt.value=!1,be()}function Ke(j,oe){if(!ue.value)return;const ye=(function(){if(!ue.value)return null;const we=We(Qe),Ee=We(mt),He=Math.max(Se,Ee);if(we<=0&&He<=0)return null;const Je={total:we,maxPerFrame:He,byLabel:(nt=Qe,Object.fromEntries(Array.from(nt.entries()).sort((vt,it)=>it[1]-vt[1]||vt[0].localeCompare(it[0]))))};var nt;return Qe.clear(),mt.clear(),Se=0,Je})();console.info(`[markstream-vue][perf] ${j}`,ye?Dn(Bt({},oe),{layoutReads:ye}):oe)}ze([()=>I.indexKey,()=>I.customId],()=>{var j,oe;Oe(),pt.value=!1,Rt.value=!((j=i.nodes)!=null&&j.length)&&Ae.value!==!0&&!!i.content,Ot=(oe=ke.value)!=null?oe:"",Fe=Ot.length>0},{flush:"sync"}),ze([()=>i.content,()=>i.nodes,Ae],([j,oe,ye])=>{!oe?.length&&ye!==!0&&j&&(Rt.value=!0)},{flush:"sync",immediate:!0}),ze([ke,()=>i.nodes,Ae],([j,oe,ye])=>{const we=j??"";return oe?.length||ye===!0?(Oe(),pt.value=!1,Ot=we,void(Fe=!0)):(we.length>0&&(Rt.value=!0),Fe?(Ot&&we.length>Ot.length&&we.startsWith(Ot)?(rt.value=!0,pt.value=!0,U&&(be(),Pe=window.setTimeout(()=>{var Ee;Pe=null,Ne.value===!0||(Ee=i.nodes)!=null&&Ee.length||(Gp(),rt.value=!1,_c())},1200))):(we.length"u")return null;const He=window;if(He.__markstreamLayoutReadPerformance)return He.__markstreamLayoutReadPerformance;const Je={total:0,maxPerFrame:0,byLabel:{}};return He.__markstreamLayoutReadPerformance=Je,Je})();Ee&&(Ee.total=Number(Ee.total||0)+1,Ee.byLabel[we]=Number(Ee.byLabel[we]||0)+1,Ee.currentFrameTotal=Number(Ee.currentFrameTotal||0)+1,Ee.frameScheduled||(Ee.frameScheduled=!0,typeof window.requestAnimationFrame!="function"?typeof queueMicrotask!="function"?setTimeout(()=>Tt(Ee),0):queueMicrotask(()=>Tt(Ee)):window.requestAnimationFrame(()=>Tt(Ee))))})(j),dt||(dt=!0,U&&typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(ut):typeof queueMicrotask!="function"?setTimeout(ut,0):queueMicrotask(ut)))}function Ve(j,oe){return tt(j),oe()}const kt=I.customId?`renderer-${I.customId}`:`renderer-${Date.now()}-${Math.random().toString(36).slice(2)}`,Wt=(function(j){const oe=new Map;return{scope:j,cache:oe,clear:()=>oe.clear()}})(kt),Nn=kt;Gn(Lq,Wt);const Sn=vs(()=>I.customId),{effectiveCustomHtmlTagsSet:Yi,mergedParseOptions:Ji,parsedNodes:Zt,getParsedNodesDirtyStartIndex:Ro,getParsedNodesRevision:Js}=m4e(I,{instanceMsgId:kt,renderContent:ke,effectiveFinal:Ne,smoothStreamingEnabled:Te,debugPerformanceEnabled:ue,customComponentsMap:Sn,logPerf:Ke});ze(Zt,()=>{rt.value||Wt.clear(),G.value+=1},{immediate:!0});const ji=D(()=>({customId:I.customId,customHtmlTags:Ji.value.customHtmlTags,parseOptions:I.parseOptions,customMarkdownIt:I.customMarkdownIt,htmlPolicy:pe.value,viewportPriority:I.viewportPriority,viewportPriorityOptions:Z.value,mode:c.value,domMode:I.domMode,codeRenderer:m.value,codeBlockStream:I.codeBlockStream,codeBlockDarkTheme:I.codeBlockDarkTheme,codeBlockLightTheme:I.codeBlockLightTheme,codeBlockMonacoOptions:I.codeBlockMonacoOptions,renderCodeBlocksAsPre:I.renderCodeBlocksAsPre,codeBlockMinWidth:I.codeBlockMinWidth,codeBlockMaxWidth:I.codeBlockMaxWidth,codeBlockProps:I.codeBlockProps,mermaidProps:I.mermaidProps,d2Props:I.d2Props,infographicProps:I.infographicProps,showTooltips:me.value,themes:I.themes,langs:I.langs,isDark:I.isDark,typewriter:f.value,smoothStreamingOptions:I.smoothStreamingOptions,parseCoalesceMs:I.parseCoalesceMs,fade:I.fade}));Gn("markstreamNestedRendererProps",ji);const Fr=D(()=>Zt.value),Oo=D(()=>Zt.value.length),pr=q(null),Zo=q(null),Po=q(null),fo=q(null),Ps=i.indexKey!=null&&String(i.indexKey).startsWith("list-item-"),$l=!Ps&&I.customId?yF(I.customId):null,mr=D(()=>$l?(S8.value,yF(I.customId)):null),Ue=D(()=>{var j;return!!(!Q.value&&I.customId&&!Ps&&((j=mr.value)!=null&&j.enabled))}),Ge=D(()=>!!(U&&Ue.value)),Ye=D(()=>{var j;return!!(!Q.value&&((j=i.virtualScroll)!=null&&j.enabled))}),fn=D(()=>Ye.value),xt=q(!1);gn(()=>{xt.value=!0});const hn=D(()=>!!(U&&Ye.value));Gn("markstreamHostScrollManaged",hn);const So=D(()=>!!(xt.value&&hn.value)),ei=D(()=>Ge.value||hn.value),Li=D(()=>Ge.value||So.value),Mt=D(()=>{var j;return ei.value&&((j=mr.value)==null?void 0:j.textEstimation)!==!1});function ht(){const j=te.value||Ve("getMeasuredContainerWidth.clientWidth",()=>{var oe;return((oe=F.value)==null?void 0:oe.clientWidth)||0});return Number.isFinite(j)&&j>0?j:0}const $t=D(()=>{const j=ht();return j>0?Math.max(1,Math.round(j)):640}),Vt=D(()=>{var j,oe;return!(Ne.value!==!0||Ye.value||c.value!=="chat"&&c.value!=="minimal"||a("maxLiveNodes")||a("liveNodeBuffer")||(j=i.nodes)!=null&&j.length||Rt.value||!(((oe=I.maxLiveNodes)!=null?oe:0)<=0))}),Un=D(()=>{var j;return Vt.value?50:Math.max(1,(j=I.maxLiveNodes)!=null?j:320)}),Ri=D(()=>{var j;return Vt.value?16:Math.max(0,(j=I.liveNodeBuffer)!=null?j:60)}),An=D(()=>{var j;return!Q.value&&I.nodeVirtual!==!1&&!(((j=I.maxLiveNodes)!=null?j:0)<=0&&!Vt.value)&&(I.nodeVirtual===!0?Zt.value.length>0:Zt.value.length>Un.value)}),Ga=D(()=>An.value||Ge.value||hn.value),va=D(()=>I.viewportPriority!==!1),Xf=D(()=>!!va.value&&!K.value);var Dr;Dr=D(()=>va.value),Gn(xq,Dr);const zl=D(()=>{var j;return!(Q.value||I.deferNodesUntilVisible===!1||((j=I.maxLiveNodes)!=null?j:0)<=0||An.value||Zt.value.length>900||I.viewportPriority===!1)}),gr=Q9e(j=>{var oe;return ge((oe=j??F.value)!=null?oe:null)},va),{requestFrame:Go,cancelFrame:Xi,hasIdleCallback:vr,isTestEnv:yr}=(function(j){const oe=j.isClient&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame.bind(window):null,ye=j.isClient&&typeof window.cancelAnimationFrame=="function"?window.cancelAnimationFrame.bind(window):null,we=j.isClient&&typeof window.requestIdleCallback=="function",Ee=(function(){var He;if(typeof globalThis>"u"||!("process"in globalThis))return;const Je=(He=Object.getOwnPropertyDescriptor(globalThis,"process"))==null?void 0:He.value;return Je?.env})();return{requestFrame:oe,cancelFrame:ye,hasIdleCallback:we,isTestEnv:Ee?.NODE_ENV==="test"}})({isClient:U}),Qa=D(()=>Ne.value===!0&&!Ye.value),{resolvedBatchSize:jl,resolvedInitialBatch:ol,batchingEnabled:Eu,incrementalRenderingActive:ya,renderedCount:Bs,previousRenderContext:Bo,adaptiveBatchSize:ks,previousBatchConfig:Hl}=(function(j,oe){var ye;const we=D(()=>{var gt;const Xe=Math.trunc((gt=j.renderBatchSize)!=null?gt:80);return Number.isFinite(Xe)?Math.max(0,Xe):0}),Ee=D(()=>{var gt;const Xe=Math.trunc((gt=j.initialRenderBatchSize)!=null?gt:we.value);return Number.isFinite(Xe)?Math.max(0,Xe):we.value}),He=D(()=>!oe.renderAsFragment.value&&j.batchRendering!==!1&&we.value>0&&oe.isClient&&!oe.isTestEnv),Je=q(0),nt=q({key:j.indexKey,total:0}),vt=q(Math.max(1,we.value||1)),it=D(()=>{var gt,Xe,at;return He.value&&!((gt=oe.continuousStreaming)!=null&>.value)&&!((Xe=oe.forceFullRenderFinalContent)!=null&&Xe.value)&&((at=j.maxLiveNodes)!=null?at:0)<=0}),lt=q({batchSize:we.value,initial:Ee.value,delay:(ye=j.renderBatchDelay)!=null?ye:16,enabled:it.value});return{resolvedBatchSize:we,resolvedInitialBatch:Ee,batchingEnabled:He,incrementalRenderingActive:it,renderedCount:Je,previousRenderContext:nt,adaptiveBatchSize:vt,previousBatchConfig:lt}})(I,{isClient:U,isTestEnv:yr,renderAsFragment:Q,forceFullRenderFinalContent:Qa,continuousStreaming:D(()=>pt.value&&Ne.value!==!0)}),bs=D(()=>{var j;return!Q.value&&I.batchRendering!==!1&&jl.value>0&&!yr&&((j=I.maxLiveNodes)!=null?j:0)<=0&&!Qa.value}),Ai=D(()=>bs.value),$o=D(()=>ei.value||Ai.value),Hi=D(()=>{var j;return $o.value&&((j=mr.value)==null?void 0:j.codeBlockEstimation)!==!1}),xi=new Map,Rr=new Map,Ya=new WeakMap;let zo=null;const Ja=new WeakMap,_o=new Map,sl=[];let Qo=[],vo=[],ai=-1;const ws=_u(sl),Xs=new Set,Or=q(0);let kr=0;const bc=q(0),wc=D(()=>(bc.value,Array.from(xi.entries()).sort((j,oe)=>j[0]-oe[0]))),Xa=q(null),jo=q(null);let Cs,Pr=null,br=0,Io=null;function ui(){Cs.markFallbackHeightPrefixDirty()}function Br(j){return Cs.getFallbackNodeHeight(j)}function $s(j,oe){return Cs.estimateHeightRange(j,oe)}function Wl(j){return Cs.estimateIndexForOffset(j)}const{activeRestoreAnchor:lo,getRelativeScrollTopWithinContainer:Lu,setRelativeScrollTopWithinContainer:ka,resolveAnchorOffset:md,clearRestoreReconcile:ql,scheduleRestoreReconcile:ba,captureRestoreAnchor:wr,restoreAnchor:wa,getAnchorDrift:As}=(function(j){const{isClient:oe,containerRef:ye,parsedNodeCount:we,requestFrame:Ee,cancelFrame:He,resolveScrollContainer:Je,getNormalizedScrollTop:nt,getOffsetTopWithinRoot:vt,isReverseFlexScrollRoot:it,estimateIndexForOffset:lt,estimateHeightRange:gt,getFallbackNodeHeight:Xe,clamp:at}=j,It=q(null);let At=null,Ut=[];function Dt(){const Cn=Je(),Wn=ye.value;if(!Cn||!Wn)return null;const Jn=Cn.ownerDocument||Wn.ownerDocument||document;if(Cn===Jn.documentElement||Cn===Jn.body||Cn===Jn.scrollingElement){const Oi=Wn.getBoundingClientRect();return Math.max(0,-Oi.top)}return Math.max(0,nt(Cn,Jn,!1)-vt(Wn,Cn))}function rn(Cn){var Wn;const Jn=Je(),Oi=ye.value;if(!Jn||!Oi)return;const er=Math.max(0,Cn),Us=Jn.ownerDocument||Oi.ownerDocument||document,nu=Us.defaultView||(typeof window<"u"?window:null);if(Jn===Us.documentElement||Jn===Us.body||Jn===Us.scrollingElement){const Ru=nt(Jn,Us,!0)+Oi.getBoundingClientRect().top;return void((Wn=nu?.scrollTo)==null||Wn.call(nu,0,Math.max(0,Ru+er)))}wF(Jn,Us,vt(Oi,Jn)+er,{isReverseFlexScrollRoot:Ru=>{var _g;return(_g=it?.(Ru))!=null&&_g},getNormalizedScrollTop:nt})}function cn(Cn){const Wn=we.value,Jn=at(Cn.nodeIndex,0,Math.max(0,Wn-1));return gt(0,Jn)+Math.max(0,Cn.offsetWithinNodePx)}function wn(){if(At!=null&&(He?.(At),At=null),oe)for(const Cn of Ut)window.clearTimeout(Cn);Ut=[]}function yn(Cn){const Wn=cn(Cn),Jn=Dt();Jn!=null&&Math.abs(Jn-Wn)<=.5||rn(Wn)}return{activeRestoreAnchor:It,getRelativeScrollTopWithinContainer:Dt,setRelativeScrollTopWithinContainer:rn,resolveAnchorOffset:cn,clearRestoreReconcile:wn,applyRestoreAnchor:yn,scheduleRestoreReconcile:function(){It.value&&oe&&At==null&&(At=Ee?Ee(()=>{At=null,It.value&&yn(It.value)}):null,At==null&&It.value&&yn(It.value))},captureRestoreAnchor:function(){const Cn=Dt(),Wn=we.value;if(Cn==null||Wn<=0)return null;const Jn=at(lt(Cn+1),0,Wn-1),Oi=gt(0,Jn),er=Xe(Jn);return{nodeIndex:Jn,offsetWithinNodePx:at(Cn-Oi,0,Math.max(0,er-1))}},restoreAnchor:function(Cn){const Wn=we.value;if(It.value={nodeIndex:at(Cn.nodeIndex,0,Math.max(0,Wn-1)),offsetWithinNodePx:Math.max(0,Cn.offsetWithinNodePx)},wn(),yn(It.value),oe)for(const Jn of[0,120,280,480])Ut.push(window.setTimeout(()=>{It.value&&yn(It.value)},Jn))},getAnchorDrift:function(Cn){const Wn=Dt();return Wn==null?null:Wn-cn(Cn)}}})({isClient:U,containerRef:F,parsedNodeCount:Oo,requestFrame:Go,cancelFrame:Xi,resolveScrollContainer:()=>Xa.value||ae(),getNormalizedScrollTop:ve,getOffsetTopWithinRoot:ce,isReverseFlexScrollRoot:Ce,estimateIndexForOffset:Wl,estimateHeightRange:$s,getFallbackNodeHeight:Br,clamp:Xo}),{nodeHeights:rl,heightStats:ao,heightTreeSize:eo,heightSumTree:Ul,heightKnownTree:gd,averageNodeHeight:Vl,resetHeightMeasurements:Kl,pruneHeightMeasurements:Zl,rebuildHeightTrees:ll,recordNodeHeight:vd,removeNodeHeights:Ca,exportHeightCache:eu,importHeightCache:Cc,fenwickRangeSum:zs}=(function(j={}){const oe=po({}),ye=po({total:0,count:0}),we=q(0),Ee=q([]),He=q([]);function Je(){for(const Xe of Object.keys(oe))delete oe[Number(Xe)];ye.total=0,ye.count=0,we.value=0,Ee.value=[],He.value=[]}function nt(Xe,at,It){for(let At=at+1;At0;At-=At&-At)It+=Xe[At];return It}function it(Xe){we.value=Xe;const at=new Array(Xe+1).fill(0),It=new Array(Xe+1).fill(0);for(const[At,Ut]of Object.entries(oe)){const Dt=Number(At),rn=Number(Ut);!Number.isFinite(Dt)||Dt<0||Dt>=Xe||!Number.isFinite(rn)||rn<=0||(nt(at,Dt,rn),nt(It,Dt,1))}Ee.value=at,He.value=It}function lt(Xe){if(!Number.isInteger(Xe)||Xe<0)return!1;const at=oe[Xe];if(!Number.isFinite(at)||at<=0)return!1;if(delete oe[Xe],ye.total=Math.max(0,ye.total-at),ye.count=Math.max(0,ye.count-1),we.value>Xe){const It=Ee.value,At=He.value;It.length&&At.length&&(nt(It,Xe,-at),nt(At,Xe,-1))}return!0}const gt=D(()=>ye.count>0?Math.max(12,ye.total/ye.count):32);return{nodeHeights:oe,heightStats:ye,heightTreeSize:we,heightSumTree:Ee,heightKnownTree:He,averageNodeHeight:gt,resetHeightMeasurements:Je,pruneHeightMeasurements:function(Xe){if(Xe<=0)return void Je();let at=0,It=0;for(const[At,Ut]of Object.entries(oe)){const Dt=Number(At),rn=Number(Ut);!Number.isFinite(Dt)||Dt<0||Dt>=Xe||!Number.isFinite(rn)||rn<=0?delete oe[Dt]:(at+=rn,It++)}ye.total=at,ye.count=It},rebuildHeightTrees:it,recordNodeHeight:function(Xe,at,It={}){(function(At,Ut,Dt={}){var rn;if(!Number.isFinite(Ut)||Ut<=0)return!1;const cn=oe[At];if(cn&&(Dt.allowShrink===!1&&UtAt){const wn=Ee.value,yn=He.value;if(wn.length&&yn.length)if(cn){const Cn=Ut-cn;Cn!==0&&nt(wn,At,Cn)}else nt(wn,At,Ut),nt(yn,At,1)}Dt.notify!==!1&&((rn=j.onHeightRecorded)==null||rn.call(j))})(Xe,at,Dn(Bt({},It),{notify:!0}))},removeNodeHeight:function(Xe,at={}){var It;const At=lt(Xe);return At&&at.notify!==!1&&((It=j.onHeightRecorded)==null||It.call(j)),At},removeNodeHeights:function(Xe,at={}){var It;let At=0;for(const Ut of Xe)lt(Number(Ut))&&At++;return At>0&&at.notify!==!1&&((It=j.onHeightRecorded)==null||It.call(j)),At},exportHeightCache:function(){return Object.entries(oe).map(([Xe,at])=>({index:Number(Xe),height:Number(at)})).filter(Xe=>Number.isFinite(Xe.index)&&Xe.index>=0&&Number.isFinite(Xe.height)&&Xe.height>0).sort((Xe,at)=>Xe.index-at.index)},importHeightCache:function(Xe,at={}){var It;if(!Array.isArray(Xe))return;const At=we.value;let Ut=!1;if(at.mode!=="merge"){const Dt=Object.keys(oe);if(Dt.length>0){for(const rn of Dt)delete oe[Number(rn)];Ut=!0}}for(const Dt of Xe){const rn=Number(Dt.index),cn=Number(Dt.height);if(!Number.isInteger(rn)||rn<0||At>0&&rn>=At||!Number.isFinite(cn)||cn<=0)continue;const wn=oe[rn];wn&&Math.abs(wn-cn)<=1||(oe[rn]=cn,Ut=!0)}Ut&&((function(){let Dt=0,rn=0;const cn=we.value;for(const[wn,yn]of Object.entries(oe)){const Cn=Number(wn),Wn=Number(yn);!Number.isFinite(Cn)||Cn<0||cn>0&&Cn>=cn||!Number.isFinite(Wn)||Wn<=0?delete oe[Cn]:(Dt+=Wn,rn++)}ye.total=Dt,ye.count=rn})(),At>0&&it(At),(It=j.onHeightRecorded)==null||It.call(j))},fenwickRangeSum:function(Xe,at,It){if(It<=at)return 0;const At=vt(Xe,It-1);return at<=0?At:At-vt(Xe,at-1)}}})({onHeightRecorded:()=>{ui(),hn.value&&bg(),lo.value&&ba(),jo.value&&Vp(),to("node-resize")}});function Yo(j){Number.isInteger(j)&&j>=0&&Xs.add(j)}function js(j){for(const oe of j)Yo(Number(oe))}function Hs(j){kr++;let oe=!0;try{const ye=j();return oe=ye!==!1,ye}finally{kr--,kr===0&&oe&&Or.value++}}function qe(){Qo=[],vo=[],ai=-1,Xs.clear(),ws.value=sl}function Re(){qe(),Hs(()=>Kl()),_o.clear()}function ct(j){!Number.isInteger(j)||j<0||j>=Zt.value.length||_o.set(j,ug(j))}function un(j,oe,ye={}){const we=rl[j];Yo(j),vd(j,oe,ye);const Ee=rl[j];return Object.is(we,Ee)?(Xs.delete(j),!1):(Ee&&Ee>0?ct(j):we&&_o.delete(j),!0)}function Rn(j,oe){const ye=Ve("getNodeLayoutHeight.slot.offsetHeight",()=>{var we,Ee;return(Ee=(we=xi.get(j))==null?void 0:we.offsetHeight)!=null?Ee:0});return ye>0?ye:Ve("getNodeLayoutHeight.content.offsetHeight",()=>oe.offsetHeight)}function In(j,oe={}){oe.mode!=="merge"?qe():js(j.map(ye=>ye.index)),Hs(()=>Cc(j,oe)),Hw()}const oi=D(()=>zl.value&&Xf.value),Si=D(()=>{var j;return!Q.value&&I.batchRendering!==!1&&jl.value>0&&((j=I.maxLiveNodes)!=null?j:0)<=0}),xs=D(()=>!Q.value&&Ze&&Ne.value===!0&&!An.value&&!Ye.value&&!Ue.value&&!oi.value&&!Si.value),al=D(()=>!!gr&&oi.value),ul=D(()=>An.value||hn.value),{focusIndex:Ho,liveRange:uo,updateLiveRange:tu}=(function(j,oe){const{parsedNodeCount:ye,virtualizationEnabled:we,maxLiveNodesResolved:Ee,liveNodeBufferResolved:He,clamp:Je}=oe,nt=He??D(()=>{var lt;return Math.max(0,(lt=j.liveNodeBuffer)!=null?lt:60)}),vt=q(0),it=po({start:0,end:0});return{liveNodeBufferResolved:nt,focusIndex:vt,liveRange:it,updateLiveRange:function(){const lt=ye.value;if(!we.value||lt===0)return it.start=0,void(it.end=lt);const gt=Math.min(Ee.value,lt),Xe=nt.value,at=Je(vt.value-Xe,0,Math.max(0,lt-gt));it.start=at,it.end=Math.min(lt,at+gt)}}})(I,{parsedNodeCount:Oo,virtualizationEnabled:An,maxLiveNodesResolved:Un,liveNodeBufferResolved:Ri,clamp:Xo}),$r=new Map,Aa=new Map,Gl=new Map,Nu=[],cl=new Map,zr=new Set,Fu=q(0);let yd=!1;const dl=D(()=>(Fu.value,zr.size)),Yn=new Map,Ss=new Map,Cr=q(0),fl=D(()=>{Cr.value;let j=0;for(const oe of Yn.values())j+=Math.max(0,oe);return j});let Ws=null;const Ac=D(()=>{if(!An.value)return Zt.value.length;const j=Ri.value,oe=Math.max(uo.end+j,ol.value),ye=Math.min(Zt.value.length,oe);return Math.max(Bs.value,ye)});function xc(){yd||(yd=!0,queueMicrotask(()=>{yd=!1,Fu.value+=1}))}function Ie(j,oe,ye="node-resize"){if(!U||typeof window>"u")return null;const we=window.setTimeout(()=>{zr.delete(we)&&xc();try{oe()}finally{to(ye)}},Math.max(0,j));return zr.add(we),xc(),we}function $e(j){U&&j!=null&&(zr.delete(j)&&xc(),window.clearTimeout(j))}function yt(){if(U&&typeof window<"u")for(const j of zr)window.clearTimeout(j);zr.size&&(zr.clear(),xc()),Nu.length=0,Gl.clear()}function Ht(j){P.value=j}function vn(j){z.value=j}function Bn(j){W.value=j}const{cancelScheduledFocusSync:Vn,scheduleFocusSync:ti}=(function(j){const{isClient:oe,containerRef:ye,virtualizationEnabled:we,requestFrame:Ee,cancelFrame:He,syncFocusToScroll:Je}=j;let nt=null;function vt(){var lt,gt,Xe;return(Xe=(gt=(lt=ye.value)==null?void 0:lt.ownerDocument)==null?void 0:gt.defaultView)!=null?Xe:typeof window<"u"?window:null}function it(){if(!nt)return;const lt=vt();nt.viaTimeout?lt?lt.clearTimeout(nt.id):clearTimeout(nt.id):He?.(nt.id),nt=null}return{cancelScheduledFocusSync:it,scheduleFocusSync:function(lt={}){if(!we.value)return;if(!oe)return void Je(!0);if(lt.immediate)return it(),void Je(!0);if(nt)return;const gt=()=>{nt=null,Je()};if(Ee)return void(nt={id:Ee(gt),viaTimeout:!1});const Xe=vt();nt={id:Xe?Xe.setTimeout(gt,16):setTimeout(gt,16),viaTimeout:!0}}}})({isClient:U,containerRef:F,virtualizationEnabled:An,requestFrame:Go,cancelFrame:Xi,syncFocusToScroll:function(j=!1){var oe;if(!An.value)return;const ye=Xa.value||ae();if(!ye)return;const we=ye.ownerDocument||((oe=F.value)==null?void 0:oe.ownerDocument)||document,Ee=we?.defaultView||(typeof window<"u"?window:null),He=ye===we?.documentElement||ye===we?.body,Je=Zt.value.length;if(Je<=0)return;if(!He&&Je>0&&Ce(ye)){const At=Ve("syncFocusToScroll.clientHeight",()=>ye.clientHeight||0),Ut=Ve("syncFocusToScroll.scrollTop",()=>ye.scrollTop),Dt=Ut<0?-Ut:Ut;return void kd(Xo((nt=Math.max(0,Dt)+.5*Math.max(0,At),Cs.estimateIndexForOffsetFromEnd(nt)),0,Math.max(0,Je-1)),j)}var nt;const vt=(function(At,Ut,Dt,rn){const cn=F.value;if(!cn)return null;const wn=rn?0:Ve("syncFocusToScroll.model.root.getBoundingClientRect",()=>At.getBoundingClientRect().top),yn=Ve("syncFocusToScroll.model.container.getBoundingClientRect",()=>cn.getBoundingClientRect().top),Cn=Math.max(0,wn-yn),Wn=rn?Ve("syncFocusToScroll.model.viewport.clientHeight",()=>{var Jn,Oi,er,Us;return(Us=(er=(Oi=Dt?.innerHeight)!=null?Oi:(Jn=Ut.documentElement)==null?void 0:Jn.clientHeight)!=null?er:At.clientHeight)!=null?Us:0}):Ve("syncFocusToScroll.model.root.clientHeight",()=>At.clientHeight);return Xo(Wl(Cn+.5*Math.max(0,Wn)),0,Math.max(0,Zt.value.length-1))})(ye,we,Ee,He);if(vt!=null)return void kd(vt,j);const it=He?null:Ve("syncFocusToScroll.root.getBoundingClientRect",()=>ye.getBoundingClientRect()),lt=He?0:it.top,gt=He?Ve("syncFocusToScroll.viewport.clientHeight",()=>{var At,Ut;return(Ut=(At=Ee?.innerHeight)!=null?At:ye.clientHeight)!=null?Ut:0}):it.bottom,Xe=wc.value;let at=null,It=null;for(const[At,Ut]of Xe){if(!Ut)continue;const Dt=Ve("syncFocusToScroll.slot.getBoundingClientRect",()=>Ut.getBoundingClientRect());Dt.bottom<=lt||Dt.top>=gt||(at==null&&(at=At),It=At)}if(at==null||It==null){const At=F.value;if(!At)return;const Ut=He?{top:0}:Ve("syncFocusToScroll.fallback.root.getBoundingClientRect",()=>ye.getBoundingClientRect()),Dt=Ve("syncFocusToScroll.fallback.scrollTop",()=>ve(ye,we,He)),rn=He?(()=>{const wn=Ve("syncFocusToScroll.fallback.container.getBoundingClientRect",()=>At.getBoundingClientRect()),yn=(He?0:Ut.top)-wn.top;return Math.max(0,yn)})():(()=>{const wn=ce(At,ye);return Math.max(0,Dt-wn)})(),cn=He?Ve("syncFocusToScroll.fallback.viewport.clientHeight",()=>{var wn,yn,Cn,Wn;return(Wn=(Cn=(yn=Ee?.innerHeight)!=null?yn:(wn=we?.documentElement)==null?void 0:wn.clientHeight)!=null?Cn:ye.clientHeight)!=null?Wn:0}):Ve("syncFocusToScroll.fallback.root.clientHeight",()=>ye.clientHeight);return void kd(Xo(Wl(rn+.5*Math.max(0,cn)),0,Math.max(0,Zt.value.length-1)),!0)}kd(Math.round((at+It)/2),j)}}),{visibleNodeIndices:Jo,nodeVisibilityHandles:hl,nodeVisibilityWatchStops:Ql,nodeVisibilityFallbackTimers:Pp,clearVisibilityFallback:Bp,markNodeVisible:Du,cleanupNodeVisibility:D2,destroyNodeVisibilityState:rg}=g4e({isClient:U,shouldTrackVisibleNodeIndices:()=>oi.value,shouldCleanupNodeVisibility:()=>An.value,onNodeMarkedVisible:j=>{An.value?ti():Ho.value=Xo(j,0,Math.max(0,Zt.value.length-1))},onNodeVisibilityCleaned:j=>{xi.delete(j)&&gI()}}),{cleanupScrollListener:R2,setupScrollListener:O2}=(function(j){const{isClient:oe,virtualizationEnabled:ye,listenerEnabled:we,scrollRootElement:Ee,resolveScrollContainer:He,scheduleFocusSync:Je,onScroll:nt}=j;let vt=null,it=null;function lt(){vt&&(vt(),vt=null),it=null,Ee.value=null}function gt(Xe){const at=j.getScrollTop?j.getScrollTop(Xe):Xe.scrollTop;return Math.max(0,Number.isFinite(at)?Math.abs(at):0)}return{cleanupScrollListener:lt,setupScrollListener:function(){if(!oe)return;if(!((Xe=we?.value)!=null?Xe:ye.value))return void lt();var Xe;const at=He();if(!at)return void lt();if(Ee.value===at&&vt)return;lt(),it=gt(at);const It=()=>{if(nt?.(),ye.value){const At=(function(Ut){const Dt=gt(Ut),rn=it;it=Dt;const cn=Math.max(480,.75*(Ut.clientHeight||0));return rn==null?Dt>cn?{immediate:!0}:void 0:Math.abs(Dt-rn)>cn?{immediate:!0}:void 0})(at);At?Je(At):Je()}};at.addEventListener("scroll",It,{passive:!0}),Ee.value=at,vt=()=>{at.removeEventListener("scroll",It)}}}})({isClient:U,virtualizationEnabled:An,listenerEnabled:ul,scrollRootElement:Xa,resolveScrollContainer:ae,scheduleFocusSync:ti,onScroll:function(){const j=jo.value;if(!j)return;const oe=ag();if(!oe||(function(we){if(pg()>=br)return Io=null,!1;const Ee=Io;if(Ee==null)return!0;const He=Math.abs(we.scrollTop-Ee)<=2;return He||(Io=null),He})(oe))return;const ye=oI(oe);ye!=null?(ye<-32||Math.abs(Math.max(0,ye)-Math.max(0,j.distanceFromBottomPx))>32)&&Up("restore"):Up("restore")},getScrollTop:j=>{var oe;const ye=j.ownerDocument||((oe=F.value)==null?void 0:oe.ownerDocument)||document,we=j===ye.documentElement||j===ye.body||j===ye.scrollingElement;return Ve("scrollListener.getScrollTop",()=>ve(j,ye,we))}});function kd(j,oe=!1){const ye=Xo(j,0,Math.max(0,Zt.value.length-1));!oe&&Math.abs(ye-Ho.value)<=1||(Ho.value=ye,tu())}function Xo(j,oe,ye){return Math.min(Math.max(j,oe),ye)}function $p(j=Zt.value.length){const oe=Ro();return!Number.isInteger(oe)||oe<0?j:Xo(oe,0,j)}function bd(j){return j?.firstElementChild}function P2(j,oe){var ye;return j?(ye=j.matches)!=null&&ye.call(j,oe)?j:j.querySelector(oe):null}function wd(j,oe){j<1||j>6||($[j]=oe)}function B2(){if(!ei.value)return void(te.value=0);const j=Ve("updateExperimentContainerWidth.clientWidth",()=>{var oe,ye;return(ye=(oe=F.value)==null?void 0:oe.clientWidth)!=null?ye:0});te.value=j>0?j:0}let Cd=null;function lg(){Cd?.disconnect(),Cd=null}const zp=d0("ViewportDeferredMarkdownCodeBlockNode",Xu({loader:()=>io(null,null,function*(){return(yield qo(()=>import("./index5-CI5HVqyi.js"),__vite__mapDeps([6,4,5]))).default}),loadingComponent:gb,delay:0,suspensible:!1}),gb);function Me(j){return j===zp}const st=D(()=>m.value==="pre"?bl:m.value==="shiki"?zp:k8);function et(){var j;return((j=I.codeBlockProps)==null?void 0:j.showHeader)!==!1}function _t(j,oe,ye){const we=rl[oe],Ee=typeof we=="number"&&we>0;if(Mt.value&&!Ee&&!(function(He){return!!Sn.value.paragraph&&(He.type==="paragraph"||He.type==="list_item"||He.type==="list")})(j)){const He=Eq(j,ye,le.value);if(He)return He}if(Hi.value&&j.type==="code_block"){const He=(function(Je){if(Je.type!=="code_block")return null;const nt=MI(Je,Z2(Je));return Me(nt)?"markdown":nt===bl?"pre":nt===st.value||nt===k8?"monaco":null})(j);if(He==="monaco"||He==="markdown"||He==="pre")return(function(Je,nt){var vt,it,lt;if(!Je||Je.type!=="code_block")return null;const gt=nt.rendererKind,Xe=gt!=="pre"&&nt.showHeader!==!1,at=!!Je.diff;let It=0,At=500;if(gt==="monaco"){const Dt=(vt=nt.monacoOptions)!=null?vt:{},rn=M8(Je,Dt,nt.width),cn=(function(yn){const Cn=typeof yn?.fontSize=="number"&&yn.fontSize>0?yn.fontSize:12;return typeof yn?.lineHeight=="number"&&yn.lineHeight>0?yn.lineHeight:Math.round(1.5*Cn)})(Dt),wn=(function(yn,Cn){var Wn,Jn;const Oi=typeof((Wn=yn?.padding)==null?void 0:Wn.top)=="number"?yn.padding.top:Cn?0:8,er=typeof((Jn=yn?.padding)==null?void 0:Jn.bottom)=="number"?yn.padding.bottom:Cn?0:8;return Math.max(0,Oi)+Math.max(0,er)})(Dt,at);At=typeof Dt.MAX_HEIGHT=="number"&&Dt.MAX_HEIGHT>0?Dt.MAX_HEIGHT:500,It=Math.round(rn*cn+wn)}else if(gt==="markdown"){const Dt=M8(Je);It=Math.round(21*Dt+32)}else{const Dt=M8(Je);It=Math.round(28*Dt),At=Number.POSITIVE_INFINITY}const Ut=Math.max(1,Math.min(It,At));return Bt({kind:"code-block",height:Math.round(Ut+(Xe?40:0)),contentHeight:Ut,rendererKind:gt},at&>==="monaco"?{diffInline:Wx((it=nt.monacoOptions)!=null?it:{},(lt=nt.width)!=null?lt:0)}:{})})(j,{rendererKind:He,monacoOptions:I.codeBlockMonacoOptions,showHeader:et(),width:ye})}return null}Y1(()=>{if(Or.value,kr>0)return;const j=Zt.value,oe=Js();if(!j.length||!$o.value)return Qo=[],vo=[],ai=-1,Xs.clear(),void(ws.value=sl);const ye=te.value||Ve("estimatedNodeHeights.clientWidth",()=>{var it;return((it=F.value)==null?void 0:it.clientWidth)||0});if(!Number.isFinite(ye)||ye<=0)return Qo=[],vo=[],ai=-1,Xs.clear(),void(ws.value=sl);const we=(function(it){return[Math.round(it),Mt.value,Hi.value,le.value,I.codeBlockMonacoOptions,et(),m.value,Sn.value,S8.value]})(ye),Ee=Qo.length<=j.length&&(Je=we,(He=vo).length===Je.length&&He.every((it,lt)=>Object.is(it,Je[lt])));var He,Je;const nt=Ee&&ai===oe?j.length:Ee?$p(j.length):0,vt=Ee?Array.from(Xs):[];Qo.length=j.length;for(let it=nt;it=0&&itws.value);Cs=(function(j){let oe=!0,ye=[0],we="";function Ee(lt){var gt;const Xe=j.nodeHeights[lt];if(Number.isFinite(Xe)&&Xe>0)return Xe;const at=j.parsedNodes.value[lt],It=at?.type,At=!!((gt=j.hasCustomParagraphComponent)!=null&>.call(j)),Ut=j.estimatedNodeHeights.value[lt],Dt=Ut?.height;if(!(function(cn,wn,yn){return!!(yn&&wn?.kind==="simple-text"&&(cn==="paragraph"||cn==="list_item"||cn==="list"))})(It,Ut,At)&&Number.isFinite(Dt)&&Dt>0)return Dt;const rn=o4e(at,j.getContainerWidth()||640);return It==="heading"||It==="paragraph"&&rn<=28&&(function(cn,wn){if(wn)return!1;const yn=cn.children;return!Array.isArray(yn)||!yn.length||yn.every(Nq)})(at,At)?rn:Math.max(j.averageNodeHeight.value,rn)}function He(){var lt;const gt=j.parsedNodes.value.length,Xe=j.getPrefixCacheKeyParts().join(":");if(!oe&&we===Xe)return ye;const at=new Array(gt+1);at[0]=0;for(let It=0;It=((gt=It[at])!=null?gt:0))return at-1;let At=0,Ut=at-1,Dt=at-1;for(;At<=Ut;){const rn=At+Ut>>1;((Xe=It[rn+1])!=null?Xe:0)>=lt?(Dt=rn,Ut=rn-1):At=rn+1}return Dt}function nt(lt,gt){var Xe,at;if(lt>=gt)return 0;if(j.heightEstimationActive.value)return(function(Ut,Dt){var rn,cn;const wn=j.parsedNodes.value.length,yn=xF(Math.trunc(Ut),0,wn),Cn=xF(Math.trunc(Dt),yn,wn);if(yn>=Cn)return 0;const Wn=He();return((rn=Wn[Cn])!=null?rn:0)-((cn=Wn[yn])!=null?cn:0)})(lt,gt);if(j.heightTreeSize.value!==j.parsedNodes.value.length){let Ut=0;for(let Dt=lt;Dtyn<=0?0:j.fenwickRangeSum(At,0,yn)+(yn-j.fenwickRangeSum(Ut,0,yn))*It;let rn=0,cn=Xe.length-1,wn=Xe.length-1;for(;rn<=cn;){const yn=rn+cn>>1;Dt(yn+1)>=lt?(wn=yn,cn=yn-1):rn=yn+1}return wn}let at=lt;for(let It=0;It0||lt++}return lt}return{markFallbackHeightPrefixDirty:function(){oe=!0},getFallbackNodeHeight:Ee,estimateHeightRange:nt,estimateIndexForOffset:vt,estimateIndexForOffsetFromEnd:function(lt){var gt,Xe;const at=j.parsedNodes.value;if(!at.length)return 0;if(lt<=0)return Math.max(0,at.length-1);if(j.heightEstimationActive.value){const At=(gt=He()[at.length])!=null?gt:0;return Je(Math.max(0,At-lt))}if(j.heightTreeSize.value===at.length){const At=nt(0,at.length);return vt(Math.max(0,At-lt))}let It=lt;for(let At=at.length-1;At>=0;At--){const Ut=(Xe=j.nodeHeights[At])!=null?Xe:j.averageNodeHeight.value;if(It<=Ut)return At;It-=Ut}return 0},getEstimatedNodeHeightCount:it,buildVirtualHeightSummary:function(lt){var gt;const Xe=j.parsedNodes.value.length;return{totalNodes:Xe,measuredCount:j.heightStats.count,estimatedCount:it(),averageNodeHeight:j.averageNodeHeight.value,topSpacerHeight:lt.topSpacerHeight,bottomSpacerHeight:lt.bottomSpacerHeight,estimatedTotalHeight:nt(0,Xe),width:(gt=lt.width)!=null?gt:j.getContainerWidth()}}}})({parsedNodes:Zt,nodeHeights:rl,heightStats:ao,heightTreeSize:eo,heightSumTree:Ul,heightKnownTree:gd,averageNodeHeight:Vl,heightEstimationActive:ei,estimatedNodeHeights:an,getContainerWidth:ht,hasCustomParagraphComponent:()=>!!Sn.value.paragraph,getPrefixCacheKeyParts:()=>{var j;const oe=zg(te.value||Ve("getFallbackHeightPrefix.clientWidth",()=>{var we;return((we=F.value)==null?void 0:we.clientWidth)||0})),ye=((j=i.virtualScroll)==null?void 0:j.measurementKey)==null?"":String(i.virtualScroll.measurementKey);return[Zt.value.length,ao.count,Math.round(ao.total),Math.round(100*Vl.value),ye,oe,ei.value?1:0,S8.value,G.value,Sn.value.paragraph?1:0]},fenwickRangeSum:zs}),ze(()=>Zt.value.length,j=>{var oe;ui(),j<=0?Re():(jZl(oe))),j!==eo.value&&ll(j))},{immediate:!0});const On=D(()=>{if(!An.value)return Zt.value.map((we,Ee)=>({node:we,index:Ee}));const j=Zt.value.length,oe=Xo(uo.start,0,j),ye=Xo(uo.end,oe,j);return Zt.value.slice(oe,ye).map((we,Ee)=>({node:we,index:oe+Ee}))}),xn=D(()=>An.value?$s(0,Math.min(uo.start,Zt.value.length)):0),En=D(()=>{if(!An.value)return 0;const j=Zt.value.length;return $s(Math.min(uo.end,j),j)});function Mn(){return Cs.buildVirtualHeightSummary({topSpacerHeight:xn.value,bottomSpacerHeight:En.value,width:th()})}function Wi(){const j=Zt.value,oe=Mn();return Dn(Bt({},oe),{probe:{paragraphReady:!!le.value.paragraph,listItemReady:!!le.value.listItem,listWrapperOverhead:le.value.listWrapperOverhead,headingReadyLevels:Object.entries(le.value.headings).filter(([,ye])=>!!ye).map(([ye])=>Number(ye))},nodes:j.map((ye,we)=>{var Ee,He,Je,nt,vt,it,lt,gt,Xe;return{index:we,type:ye.type,estimateKind:(He=(Ee=an.value[we])==null?void 0:Ee.kind)!=null?He:null,rendererKind:(nt=(Je=an.value[we])==null?void 0:Je.rendererKind)!=null?nt:null,estimatedHeight:(it=(vt=an.value[we])==null?void 0:vt.height)!=null?it:null,estimatedContentHeight:(gt=(lt=an.value[we])==null?void 0:lt.contentHeight)!=null?gt:null,measuredHeight:(Xe=rl[we])!=null?Xe:null}})})}function qs(){return i.indexKey!=null?String(i.indexKey):Ye.value?`virtual-${vi()}`:"markdown-renderer"}function Yl(j){const oe=String(j),ye=`${qs()}-`;if(!oe.startsWith(ye))return null;const we=oe.slice(ye.length).match(/^(\d+)(?:$|-)/);if(!we)return null;const Ee=Number(we[1]);return!Number.isInteger(Ee)||Ee<0||Ee>=Zt.value.length?null:Ee}function vi(){var j,oe,ye;const we=(j=i.virtualScroll)==null?void 0:j.sessionKey;return String(we!=null&&we!==""?we:(ye=(oe=i.indexKey)!=null?oe:I.customId)!=null?ye:kt)}function qi(){var j;const oe=(j=i.virtualScroll)==null?void 0:j.threadKey;return oe==null||oe===""?void 0:String(oe)}const eh=D(()=>{var j,oe,ye;return(ye=qi())!=null?ye:String((oe=(j=i.indexKey)!=null?j:I.customId)!=null?oe:kt)});function _w(j){var oe;return(j??"")===((oe=qi())!=null?oe:"")}function Sc(){var j,oe,ye;return oe=(j=i.virtualScroll)==null?void 0:j.measurementKey,ye=(function(){const we=m.value;return(function(Ee){var He,Je;const nt=Ee.renderer,vt=nt==="monaco"?Ee.codeBlockMonacoOptions:void 0,it=Ee.codeBlockProps,lt=nt==="shiki";return[Ee.isDark?"dark":"light",nt==="monaco"?"code-rich":nt==="pre"?"code-pre":"code-shiki",Ee.codeBlockStream===!1?"code-static":"code-stream",Vs(Ee.codeBlockMinWidth),Vs(Ee.codeBlockMaxWidth),...lt?[Gye((He=it?.themes)!=null?He:Ee.themes,(Je=it?.langs)!=null?Je:Ee.langs)]:[],Vs(vt?.fontSize),Vs(vt?.lineHeight),Vs(vt?.fontFamily),Vs(vt?.tabSize),Vs(vt?.MAX_HEIGHT),Vs(vt?.wordWrap),Vs(vt?.wrappingIndent),Vs(vt?.padding),Vs(it?.showHeader),Vs(it?.showCopyButton),Vs(it?.showExpandButton),Vs(it?.showPreviewButton),Vs(it?.showCollapseButton),Vs(it?.showFontSizeButtons)].join("\0")})({renderer:we,isDark:I.isDark,codeBlockStream:I.codeBlockStream,codeBlockMinWidth:I.codeBlockMinWidth,codeBlockMaxWidth:I.codeBlockMaxWidth,codeBlockMonacoOptions:we==="monaco"?I.codeBlockMonacoOptions:void 0,codeBlockProps:I.codeBlockProps,themes:we==="shiki"?I.themes:void 0,langs:we==="shiki"?I.langs:void 0})})(),[oe==null?"":String(oe),ye].join("\0")}function th(){return ht()}const $2=D(()=>zg(th())),Jl=D(()=>[Sc(),$2.value].join("\0")),fY=D(()=>{var j;return Ye.value?["virtual",(j=qi())!=null?j:"",vi(),Jl.value].join("\0"):i.indexKey});function jp(){Cr.value+=1}function Iw(j){return!(!j||!Number.isInteger(j.index)||j.index<0||j.index>=Zt.value.length||j.sessionKey!==vi()||j.threadKey!==qi()||j.layoutEpochKey!==Jl.value)}function X_(j){const oe=String(j),ye=Ss.get(oe);return ye?Iw(ye)?ye.index:null:Yl(oe)}function eI(j="async-node"){(Yn.size||Ss.size)&&(Yn.clear(),Ss.clear(),jp(),to(j))}const Hp=en(MA,null),Mw={reportHeight(j,oe){if(!hn.value)return;const ye=X_(j);if(ye==null)return;const we=$r.get(ye);if(!we)return;const Ee=Number(oe),He=Rn(ye,we);(function(Je,nt,vt={}){Hs(()=>un(Je,nt,vt))})(ye,Number.isFinite(Ee)&&Ee>0?Math.max(Ee,He||0):He)},markPending(j){if(!hn.value)return;const oe=Yl(j);oe!=null&&(function(ye,we){var Ee;const He=Ss.get(ye);if(He&&Iw(He))return Yn.set(ye,Math.max(0,(Ee=Yn.get(ye))!=null?Ee:0)+1),jp(),void to("async-node");Yn.set(ye,1),Ss.set(ye,(function(Je){return{index:Je,sessionKey:vi(),threadKey:qi(),layoutEpochKey:Jl.value}})(we)),jp(),to("async-node")})(String(j),oe)},markSettled(j){if(!hn.value)return;const oe=String(j),ye=X_(j);(ye!=null||(function(we){return Yn.has(String(we))})(oe))&&(function(we){var Ee;const He=(Ee=Yn.get(we))!=null?Ee:0;return!(He<=0||(He<=1?(Yn.delete(we),Ss.delete(we)):Yn.set(we,He-1),jp(),He===1&&to("async-node"),0))})(oe)&&ye!=null&&_c()}};function hY(){let j=0;for(const oe of $r.values())j+=Ve("getVisibleDomHeight.offsetHeight",()=>{var ye;return(ye=oe?.offsetHeight)!=null?ye:0});return Math.ceil(Math.max(0,j))}Gn(MA,{reportHeight(j,oe){Mw.reportHeight(j,oe),Hp?.reportHeight(j,oe)},markPending(j){Mw.markPending(j),Hp?.markPending(j)},markSettled(j){Mw.markSettled(j),Hp?.markSettled(j)}});let Tw,Ew=null,Wp=null;function z2(j){return j!==!1&&j!=null&&j!==""}function tI(){return An.value?(function(){if(!An.value)return!0;const j=Zt.value.length,oe=Xo(uo.start,0,j),ye=Xo(uo.end,oe,j);if(oe>=ye)return!0;for(let we=oe;we=Ac.value}function Lw(){return Ne.value===!0&&!rt.value&&fl.value===0&&zr.size===0&&cl.size===0&&Ws==null&&tI()}function nI(){var j,oe;if(((j=i.virtualScroll)==null?void 0:j.settleMode)!=="manual"||Ew===vi()&&Tw===qi())return!0;const ye=(oe=i.virtualScroll)==null?void 0:oe.settledToken;return!!z2(ye)&&Wp===wg(ye)}function Nw(){return Lw()&&nI()}function pY(j,oe){return oe.totalNodes<=0?j==="final"?"final":"estimate":oe.measuredCount>=oe.totalNodes?j==="final"?"final":"measured":oe.measuredCount>0||oe.estimatedCount>0?"mixed":"estimate"}function nh(j="manual",oe){const ye=Mn(),we=(function(Ee){return Ee||(Ne.value!==!0?Zt.value.length>0?"streaming":"estimating":!tI()||cl.size>0||Ws!=null?"measuring":Nw()?"settled":"settling")})(oe);return{sessionKey:vi(),threadKey:qi(),phase:we,nodeCount:ye.totalNodes,liveRange:{start:uo.start,end:uo.end},renderedCount:Bs.value,measuredCount:ye.measuredCount,estimatedCount:ye.estimatedCount,averageNodeHeight:ye.averageNodeHeight,topSpacerHeight:ye.topSpacerHeight,bottomSpacerHeight:ye.bottomSpacerHeight,visibleDomHeight:hY(),totalHeight:iI(),width:ye.width,final:Ne.value===!0,stable:Nw(),confidence:pY(we,ye),reason:j}}function ag(){const j=Xa.value||ae(),oe=F.value;if(!j||!oe)return null;const ye=j.ownerDocument||oe.ownerDocument||document,we=j===ye.documentElement||j===ye.body||j===ye.scrollingElement,Ee=Ve("getScrollBox.scrollTop",()=>ve(j,ye,we)),He=Ve("getScrollBox.scrollHeight",()=>{var nt,vt,it,lt,gt;return we?Math.max((vt=(nt=ye.documentElement)==null?void 0:nt.scrollHeight)!=null?vt:0,(lt=(it=ye.body)==null?void 0:it.scrollHeight)!=null?lt:0,(gt=j.scrollHeight)!=null?gt:0):j.scrollHeight}),Je=Ve("getScrollBox.clientHeight",()=>{var nt;return we?((nt=ye.documentElement)==null?void 0:nt.clientHeight)||j.clientHeight||0:j.clientHeight});return{root:j,doc:ye,isViewportRoot:we,scrollTop:Ee,scrollHeight:He,clientHeight:Je}}function iI(){const j=Zt.value.length,oe=Math.max(0,$s(0,j)),ye=Ve("getRendererLogicalHeight.offsetHeight",()=>{var Ee,He;return(He=(Ee=F.value)==null?void 0:Ee.offsetHeight)!=null?He:0}),we=Math.max(0,ye>0?ye:Ve("getRendererLogicalHeight.scrollHeight",()=>{var Ee,He;return(He=(Ee=F.value)==null?void 0:Ee.scrollHeight)!=null?He:0}));return j<=0?Math.ceil(ye):An.value?oe>0?Math.max(1,Math.ceil(oe),(function(){let Ee=xn.value+En.value;for(const He of xi.values())He&&(Ee+=Math.max(0,Ve("getVirtualizedDomLogicalHeight.offsetHeight",()=>He.offsetHeight||0)));return Math.ceil(Math.max(0,Ee))})(),(function(Ee,He){return Ee<=0||He<=0?0:He<=Ee+Math.max(512,.05*Ee)?Math.ceil(He):0})(oe,we)):Math.max(1,Math.ceil(we)):hn.value?oe>0||ao.count>0||Cs.getEstimatedNodeHeightCount()>0?(ya.value&&Bs.value,Math.max(1,Math.ceil(we),Math.ceil(oe))):Math.ceil(we):Math.max(1,Math.ceil(we),Math.ceil(oe))}function oI(j){const oe=F.value;if(!oe)return null;const ye=Ve("getRendererBottomDistanceFromViewport.getBoundingClientRect",()=>oe.getBoundingClientRect());return(function(Ee){return Ee.isViewportRoot?Ee.clientHeight:Ve("getViewportBottomInRoot.getBoundingClientRect",()=>Ee.root.getBoundingClientRect().bottom)})(j)-ye.bottom}function mY(j={}){const oe=j.requireViewport!==!1,ye=(function(He=64){const Je=ag(),nt=F.value;if(!Je||!nt)return!1;const vt=(function(lt){if(lt.isViewportRoot)return{top:0,bottom:lt.clientHeight};const gt=Ve("getVirtualViewportRect.getBoundingClientRect",()=>lt.root.getBoundingClientRect());return{top:gt.top,bottom:gt.bottom}})(Je),it=Ve("isRendererNearVirtualViewport.getBoundingClientRect",()=>nt.getBoundingClientRect());return it.bottom>=vt.top-He&&it.top<=vt.bottom+He})();if(oe&&!ye)return null;const we=(function(){const He=ag(),Je=F.value;if(!He||!Je||Math.max(0,He.scrollHeight-He.scrollTop-He.clientHeight)>64)return null;const nt=oI(He);return nt==null?null:nt>=-8&&nt<=160?{type:"bottom",distanceFromBottomPx:Math.max(0,nt)}:null})();if(we)return{anchor:we,captured:!0};const Ee=wr();if(Ee)return{anchor:{type:"node",nodeIndex:Ee.nodeIndex,offsetWithinNodePx:Ee.offsetWithinNodePx},captured:ye};if(j.allowFallback===!0){const He=(function(){const Je=Zt.value.length;return Je<=0?null:{type:"node",nodeIndex:Xo(Ho.value,0,Math.max(0,Je-1)),offsetWithinNodePx:0}})();return He?{anchor:He,captured:!1}:null}return null}function Fw(j){let oe=2166136261;for(let ye=0;ye>>0).toString(36)}function gY(j,oe){let ye=j;for(let we=0;we8192?`${we.slice(0,8192)}...${we.length}`:we;return`${we.length}:${Fw(Ee)}`})(j)}`;if(typeof j=="function")return"fn";if(typeof j!="object")return typeof j;if(oe.has(j))return"cycle";if(ye>=6)return"max-depth";oe.add(j);try{if(Array.isArray(j)){if(j.length<=160){const it=[];for(let lt=0;lt=nt&&Je.push(lt)}return[`a:${j.length}`,`h=${He.join(",")}`,`t=${Je.join(",")}`,`all=${(vt>>>0).toString(36)}`].join(":")}const we=j,Ee=Object.keys(we).filter(He=>{const Je=we[He];return He!=="parent"&&He!=="el"&&He!=="component"&&(Je==null||typeof Je=="string"||typeof Je=="number"||typeof Je=="boolean"||vY.has(He))}).sort();return`o:${Ee.length}:${Ee.map(He=>`${He}=${j2(we[He],oe,ye+1)}`).join(";")}`}finally{oe.delete(j)}}let Dw=-1,Rw="",ih=[2166136261];function ug(j){const oe=Zt.value[j];return oe?Fw(j2(oe)):""}function yY(j,oe){let ye=j;for(let we=0;we>>0}function Ow(){var j,oe;const ye=G.value;if(Dw===ye)return Rw;const we=Zt.value.length;let Ee=$p(we);(Dw!==ye-1||Ee>we||ih.length>>0).toString(36),Dw=ye,Rw}function qp(j,oe={}){var ye;const we=oe.includeHeightCache===!0,Ee=(ye=oe.includeContentHash)!=null?ye:we,He=we?(function(nt){const vt=(function(){var At,Ut;const Dt=Number((Ut=(At=i.virtualScroll)==null?void 0:At.heightCacheLimit)!=null?Ut:5e3);return!Number.isFinite(Dt)||Dt<=0?Number.POSITIVE_INFINITY:Math.max(1,Math.trunc(Dt))})();if(!Number.isFinite(vt)||nt.length<=vt)return nt;const it=new Map,lt=At=>{!At||it.size>=vt||it.set(At.index,At)},gt=Zt.value.length,Xe=Xo(uo.start-2*Ri.value,0,gt),at=Xo(uo.end+2*Ri.value,Xe,gt);for(const At of nt)At.index>=Xe&&At.index=0&&it.sizeAt.index-Ut.index).slice(0,vt)})(eu().map(nt=>{var vt;const it=Zt.value[nt.index];return it?Dn(Bt({},nt),{nodeType:String((vt=it.type)!=null?vt:""),signature:ug(nt.index)}):null}).filter(nt=>!!nt)):[],Je=mY({allowFallback:oe.allowAnchorFallback===!0,requireViewport:oe.requireViewport});return Je||He.length||oe.includeEmptyState===!0?Dn(Bt({sessionKey:j.sessionKey,threadKey:j.threadKey},Je?{anchor:Je.anchor,anchorCaptured:Je.captured}:{anchorCaptured:!1}),{metrics:j,width:j.width,contentHash:Ee?Ow():void 0,measurementKey:Sc()||void 0,heightCache:He.length?He:void 0}):null}function Pw(j){var oe,ye;const we=ag();if(!we)return;const Ee=(function(nt){const vt=F.value;if(!vt)return null;const it=ce(vt,nt.root),lt=Zt.value.length,gt=Ve("getRendererBottomOffsetWithinRoot.offsetHeight",()=>vt.offsetHeight||0),Xe=Math.max(0,gt>0?gt:lt>0?Ve("getRendererBottomOffsetWithinRoot.scrollHeight",()=>vt.scrollHeight||0):0),at=iI();return it+Math.max(Xe,at)})(we);if(Ee==null)return;const He=Math.max(0,j.distanceFromBottomPx),Je=Math.max(0,Ee-we.clientHeight-He);(function(nt){br=pg()+120,Io=nt})(Je),we.isViewportRoot?(ye=(oe=we.doc.defaultView)==null?void 0:oe.scrollTo)==null||ye.call(oe,0,Je):wF(we.root,we.doc,Je,{isReverseFlexScrollRoot:Ce,getNormalizedScrollTop:ve})}const Bw=[];function sI(){if(U)for(Pr!=null&&(Xi?.(Pr),Pr=null);Bw.length;){const j=Bw.pop();j!=null&&window.clearTimeout(j)}}function Up(j){const oe=!!jo.value;jo.value=null,br=0,Io=null,sI(),oe&&j&&to(j)}function Vp(){if(!jo.value||!U||Pr!=null)return;const j=()=>{Pr=null;const oe=jo.value;oe&&Pw(oe)};Pr=Go?Go(j):null,Pr==null&&j()}function rI(j,oe={}){const ye=Zt.value.length;return ye<=0?[]:j.filter(we=>!(!Number.isInteger(we.index)||we.index<0||we.index>=ye)&&!(!Number.isFinite(we.height)||we.height<=0)&&!(oe.requireSignature&&!we.signature)&&!(oe.requireCompatibilityMetadata&&!we.nodeType&&!we.signature)&&(function(Ee){var He;const Je=Zt.value[Ee.index];return!(!Je||Ee.nodeType&&Ee.nodeType!==String((He=Je.type)!=null?He:"")||Ee.signature&&Ee.signature!==ug(Ee.index))})(we))}function lI(j){const oe=zg(th()),ye=zg(j);return oe!==-1&&ye!==-1&&oe===ye}function $w(j){var oe;const ye=Number(j?.width);if(Number.isFinite(ye)&&ye>0)return ye;const we=Number((oe=j?.metrics)==null?void 0:oe.width);return Number.isFinite(we)&&we>0?we:null}function aI(j){var oe;return j.sessionKey===vi()&&!!_w(j.threadKey)&&((oe=j.measurementKey)!=null?oe:"")===Sc()&&!!lI($w(j))&&!!(function(ye){const we=ye.heightCache;return!!we?.length&&(uI(ye)?we.some(Ee=>!!(Ee.nodeType||Ee.signature)):we.some(Ee=>!!Ee.signature))})(j)}function uI(j){return!!(j.contentHash&&j.contentHash===Ow())}function kY(j){return!uI(j)}let oh=null,sh=null,H2=null,cg=null,dg=null;function zw(j){var oe;const ye=j.map(Ee=>{var He,Je;return[Ee.index,Math.round(10*Ee.height),(He=Ee.nodeType)!=null?He:"",(Je=Ee.signature)!=null?Je:""].join("")}).join(""),we=zg(th());return[(oe=qi())!=null?oe:"",vi(),Sc(),Zt.value.length,we,j.length,Fw(ye)].join(":")}function cI(j=(oe=>(oe=i.virtualScroll)==null?void 0:oe.heightCache)()){if(!hn.value||!j?.length||Zt.value.length<=0||!lI((oe=i.virtualScroll)==null?void 0:oe.heightCacheWidth))return!1;var oe;const ye=rI(j,{requireSignature:!0});if(!ye.length)return!1;const we=zw(ye);return we===oh?(sh="standalone",!0):(In(ye,{mode:"merge"}),ui(),oh=we,sh="standalone",gg(),to("restore"),!0)}function jw(j,oe={}){var ye,we,Ee;if(!hn.value||!j||j.sessionKey!==vi()||!_w(j.threadKey)||Zt.value.length<=0)return!1;const He=!!((ye=j.heightCache)!=null&&ye.length)&&!W2(),Je=!j.anchor||j.anchorCaptured===!1&&oe.allowUncapturedAnchor!==!0?null:j.anchor,nt=oe.restoreAnchor===!0&&!!Je&&!W2()&&Number($w(j))>0;let vt=!1;if((we=j.heightCache)!=null&&we.length&&aI(j)){const lt=rI(j.heightCache,{requireCompatibilityMetadata:!j.contentHash,requireSignature:kY(j)});lt.length&&(In(lt,{mode:"merge"}),ui(),oh=zw(lt),sh="restore",gg(),vt=!0)}if(He||nt)return!1;if(!oe.restoreAnchor||!Je)return vt&&to("restore"),!0;const it=(function(lt,gt){var Xe;const at=lt.anchor,It=at?at.type==="bottom"?`bottom:${Math.round(at.distanceFromBottomPx)}`:`node:${at.nodeIndex}:${Math.round(at.offsetWithinNodePx)}`:"none";return[(Xe=qi())!=null?Xe:"",vi(),Sc(),$2.value,gt,It].join(":")})(j,(Ee=oe.restoreToken)!=null?Ee:"imperative");return H2===it?(vt&&to("restore"),!0):(H2=it,(function(lt){const gt=()=>{if(lt.type==="node")return Up(),void wa({nodeIndex:lt.nodeIndex,offsetWithinNodePx:lt.offsetWithinNodePx});if(ql(),lo.value=null,jo.value=lt,sI(),Pw(lt),U)for(const Xe of[0,120,280,480])Bw.push(window.setTimeout(()=>{const at=jo.value;at&&Pw(at)},Xe))};(function(Xe){if(!An.value)return!1;const at=Zt.value.length;return!(at<=0||(Ho.value=Xe.type==="node"?Xo(Xe.nodeIndex,0,at-1):at-1,tu(),0))})(lt)?ft(gt):gt()})(Je),to("restore"),!0)}function W2(){const j=th();return Number.isFinite(j)&&j>0}function dI(j){var oe;return j.sessionKey===vi()&&!!_w(j.threadKey)&&(Zt.value.length<=0||!(!((oe=j.heightCache)!=null&&oe.length)||W2())||!(!(j.anchor&&Number($w(j))>0)||W2()))}function Hw(){_o.clear();for(const j of Object.keys(rl)){const oe=Number(j);Number.isInteger(oe)&&oe>=0&&oe{let oe=!1,ye=null;const we=()=>{oe||(oe=!0,ye!=null&&window.clearTimeout(ye),j())};if(Go)return Go(we),void(ye=window.setTimeout(we,50));ye=window.setTimeout(we,0)})}function Ww(j,oe=qi(),ye=Jl.value){return vi()===j&&qi()===oe&&Jl.value===ye}function qw(){return io(this,arguments,function*(j={}){var oe,ye,we,Ee,He;const Je=vi(),nt=qi(),vt=Jl.value,it=(oe=j.frames)!=null?oe:2,lt=(ye=j.timeoutMs)!=null?ye:120,gt=(we=j.reason)!=null?we:"manual",Xe=j.expectedSettledTokenKey,at=j.flushPendingTimers===!0,It=nh(gt),At=()=>Dn(Bt({},It),{phase:It.final?"settling":It.phase,stable:!1,confidence:It.confidence==="final"?"mixed":It.confidence,reason:gt}),Ut=()=>Ww(Je,nt,vt)&&(Xe==null||mg()===Xe);for(let wn=0;wnwindow.setTimeout(yn,wn))})(lt),!Ut()||(at&&yt(),_c(),fg(),!Ut()))return At();const Dt=Lw();Dt&&(Ew=Je,Tw=nt,((Ee=i.virtualScroll)==null?void 0:Ee.settleMode)==="manual"&&Xe!=null&&z2((He=i.virtualScroll)==null?void 0:He.settledToken)&&mg()===Xe&&(Wp=wg(i.virtualScroll.settledToken)));const rn=Ut()&&Dt&&nI(),cn=nh(gt,rn?"final":void 0);return Gw(cn,!0),cn})}let Uw="content",rh=null,lh=null,Vw=0,hg=null,Kp=null,Kw=null,Zw=null;function pg(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function hI(j){var oe,ye;const we=hg;if(!we)return!0;const Ee=(ye=(oe=i.virtualScroll)==null?void 0:oe.heightDiffThresholdPx)!=null?ye:1;return Math.abs(j.totalHeight-we.totalHeight)>Ee||j.sessionKey!==we.sessionKey||j.phase!==we.phase||j.stable!==we.stable||j.final!==we.final||j.threadKey!==we.threadKey||j.nodeCount!==we.nodeCount||j.measuredCount!==we.measuredCount||j.width!==we.width}function mg(j=(oe=>(oe=i.virtualScroll)==null?void 0:oe.settledToken)()){return Vs(j)}function pI(j,oe){var ye,we;return[j,oe.sessionKey,(ye=oe.threadKey)!=null?ye:"",Sc(),Ow(),Vs((we=i.virtualScroll)==null?void 0:we.settledToken),Math.round(oe.totalHeight),Math.round(oe.width)].join("\0")}function gg(){Kw=null,Zw=null,Kp=null}function bY(j){const oe=j.heightCache;return oe?.length?zw(oe):""}function vg(j){var oe,ye,we;const Ee=j.metrics,He=j.anchor?(Je=j.anchor).type==="bottom"?`bottom:${Math.round(Je.distanceFromBottomPx)}`:`node:${Je.nodeIndex}:${Math.round(Je.offsetWithinNodePx)}`:"none";var Je;return[j.sessionKey,(oe=j.threadKey)!=null?oe:"",(ye=j.measurementKey)!=null?ye:Sc(),(we=j.contentHash)!=null?we:"",bY(j),He,j.anchorCaptured?1:0,Ee.liveRange.start,Ee.liveRange.end,Ee.renderedCount,Ee.nodeCount,Math.round(Ee.totalHeight),Math.round(Ee.width),Ee.phase,Ee.stable?1:0].join("\0")}function Gw(j,oe=!1){if(!hn.value||(function(Je=!1){return!Je&&Ye.value&&!So.value})(oe))return;const ye=oe||hI(j),we=(function(Je,nt=!1){return nt||Je.stable||Je.phase==="final"?{state:qp(Je,{includeHeightCache:!0})}:{state:qp(Je)}})(j,oe),Ee=we.state,He=!!(Ee&&(ye||(function(Je,nt=!1){return!!nt||vg(Je)!==Kp})(Ee,oe)));if(ye&&(O(j),hg=j,Vw=pg()),Ee&&He&&(H(Ee),Ee.anchor&&R(Ee.anchor),Kp=vg(Ee)),j.stable){const Je=pI("settled",j);if(Je!==Kw){Kw=Je;const nt=qp(j,{includeHeightCache:!0});nt&&(H(nt),Kp=vg(nt)),(function(vt){o("render-settled",vt)})(j)}}if(j.phase==="final"){const Je=pI("final",j);if(Je!==Zw){Zw=Je;const nt=qp(j,{includeHeightCache:!0});nt&&(H(nt),Kp=vg(nt)),(function(vt){o("render-final",vt)})(j)}}}function Qw(){rh!=null&&(Xi?.(rh),rh=null),lh!=null&&U&&(window.clearTimeout(lh),lh=null)}function mI(){rh=null,lh=null,(function(j){if(cl.size>0||Ws!=null)return!0;switch(j){case"node-resize":case"async-node":case"resize":case"restore":case"final":case"manual":return!0;default:return!1}})(Uw)&&(_c(),fg()),Gw(nh(Uw))}function to(j){var oe,ye;if(!hn.value||(Uw=j,rh!=null||lh!=null))return;const we=Math.max(0,(ye=(oe=i.virtualScroll)==null?void 0:oe.emitIntervalMs)!=null?ye:32),Ee=Math.max(0,we-(pg()-Vw)),He=()=>{lh=null,rh=Go?Go(mI):null,rh==null&&mI()};U&&Ee>0?lh=window.setTimeout(He,Ee):He()}function gI(){bc.value+=1}function q2(j){if(ya.value&&j>=Bs.value){const oe=Zt.value[j],ye=Ae.value===!0&&Ne.value!==!0&&j>=Zt.value.length-2,we=oe?.type==="code_block"||oe?.type==="image"||oe?.type==="mermaid"||oe?.type==="infographic";if(!ye||we)return!1}return!oi.value||j=he.value&&(K.value||(K.value=!0,rg()),!al.value||!gr))return Zp(j),void(oe&&Du(j,!0));if(j{if(Pp.delete(He),!oi.value||Jo.value.has(He))return;const vt=xi.get(He);if(!vt)return;const it=ae(vt),lt=vt.ownerDocument||document,gt=lt.defaultView||window,Xe=!it||it===lt.documentElement||it===lt.body,at=!Xe&&it?Ve("nodeVisibilityFallback.root.getBoundingClientRect",()=>it.getBoundingClientRect()):null,It=Xe?0:at.top,At=Xe?Ve("nodeVisibilityFallback.clientHeight",()=>{var Dt,rn;return(rn=(Dt=gt.innerHeight)!=null?Dt:it?.clientHeight)!=null?rn:0}):at.bottom,Ut=Ve("nodeVisibilityFallback.node.getBoundingClientRect",()=>vt.getBoundingClientRect());Ut.bottom>=It-500&&Ut.top<=At+500&&Du(He,!0)},1800+Je);Pp.set(He,nt)})(j);let Ee=null;Ee=ze(()=>we.isVisible.value,He=>{if(He){Bp(j),Du(j,!0),Ee?.(),Ql.delete(j),hl.get(j)===we&&hl.delete(j);try{we.destroy()}catch{}}},{immediate:!0}),Ql.set(j,Ee),An.value&&ti()}function Yw(){Ws=null,Hs(()=>{let j=!1;for(const[oe,ye]of cl)cl.delete(oe),$r.get(oe)===ye.el&&Aa.get(oe)===ye.version&&(j=un(oe,ye.height,{allowShrink:ye.allowShrink})||j);return j})}function Gp(){Ws!=null&&(Xi?.(Ws),Ws=null),cl.clear()}function V2(j,oe){(function(ye,we,Ee){var He;if(!Number.isFinite(Ee)||Ee<=0||$r.get(ye)!==we)return;const Je=Aa.get(ye);if(Je==null)return;const nt=Zt.value[ye],vt=rt.value&&Ne.value!==!0&&!((He=i.nodes)!=null&&He.length)&&ye>=Zt.value.length-2,it=!(nt?.loading===!0||vt),lt=cl.get(ye),gt=lt?lt.allowShrink&&it:it,Xe=lt&&!gt?Math.max(lt.height,Ee):Ee;cl.set(ye,{height:Xe,allowShrink:gt,version:Je,el:we}),Ws==null&&(Ws=Go?Go(Yw):null,Ws==null&&Yw())})(j,oe,Rn(j,oe))}function _c(){for(const[j,oe]of $r)oe&&V2(j,oe)}function vI(){zo?.disconnect(),zo=null,Rr.clear()}function Jw(){for(;Nu.length;)$e(Nu.pop())}ze(So,j=>{j&&to("content")},{flush:"post"}),t({getVirtualMetrics:nh,captureVirtualState:function(j={}){var oe;return qp(nh("manual"),{includeHeightCache:!0,includeContentHash:!0,allowAnchorFallback:j.allowFallbackAnchor===!0,requireViewport:j.requireViewport===!0,includeEmptyState:(oe=j.includeEmptyState)==null||oe})},restoreVirtualState:function(j,oe={}){const ye=oe.restoreAnchor===!0,we=oe.restoreToken==null?"imperative":String(oe.restoreToken);cg=j,dg={restoreAnchor:ye,restoreToken:we,allowUncapturedAnchor:oe.allowUncapturedAnchor===!0},!jw(j,{restoreAnchor:ye,restoreToken:we,allowUncapturedAnchor:oe.allowUncapturedAnchor===!0})&&dI(j)||(cg=null,dg=null)},forceMeasure:function(j="manual"){return io(this,null,function*(){yield ft(),yield fI(),_c(),fg(),yield ft();const oe=nh(j);return Gw(oe,!0),oe})},settle:qw,scrollToNode:function(j,oe="start"){Up(),ql();const ye=Zt.value.length;if(ye<=0)return;const we=Xo(j,0,ye-1),Ee=()=>{var He;const Je=md({nodeIndex:we,offsetWithinNodePx:0}),nt=Br(we),vt=ag(),it=(He=vt?.clientHeight)!=null?He:0,lt=Lu();let gt=Je;if(oe==="center")gt=Je-it/2+nt/2;else if(oe==="end")gt=Je-it+nt;else if(oe==="nearest"&<!=null){if(Je>=lt&&Je+nt<=lt+it)return;gt=JeGa.value,j=>{if(!j){vI();for(const oe of Gl.values())for(const ye of oe)$e(ye);Gl.clear(),Aa.clear(),Jw(),Gp()}},{immediate:!0}),ze(Ne,j=>{j&&(function(){if(U&&Ne.value&&$r.size){Jw();for(const oe of[80,240,640]){const ye=Ie(oe,()=>{for(const[we,Ee]of $r)Ee&&V2(we,Ee)},"final");ye!=null&&Nu.push(ye)}}})(),to(j?"final":"content")});const wY=CF(()=>to("content"),16),CY=CF(()=>to("batch"),16);ze([()=>Zt.value.length,()=>Bs.value],()=>{jo.value&&Vp(),wY()},{flush:"post",immediate:!0}),ze([()=>uo.start,()=>uo.end],()=>{CY()},{flush:"post"});const{cleanupBatchScheduler:AY}=(function(j){const{props:oe,isClient:ye,isTestEnv:we,parsedNodesIdentity:Ee,parsedNodeCount:He,desiredRenderedCount:Je,datasetKey:nt,batchingEnabled:vt,incrementalRenderingActive:it,resolvedBatchSize:lt,resolvedInitialBatch:gt,renderedCount:Xe,adaptiveBatchSize:at,previousRenderContext:It,previousBatchConfig:At,requestFrame:Ut,cancelFrame:Dt,hasIdleCallback:rn,cleanupNodeVisibility:cn,onDatasetKeyChanged:wn,onDatasetChanged:yn}=j;let Cn=null,Wn="raf",Jn=null,Oi=0,er=!1,Us=!1;const nu=new Set,Ru=new Set;function _g(){if(ye){Cn!=null&&(Wn==="raf"&&Dt?Dt(Cn):Wn==="idle"&&typeof window.cancelIdleCallback=="function"?window.cancelIdleCallback(Cn):Wn==="timeout"&&window.clearTimeout(Cn),Cn=null),Oi+=1;for(const Ar of nu)Dt&&Dt(Ar);for(const Ar of Ru)window.clearTimeout(Ar);nu.clear(),Ru.clear(),Jn=null,er=!1,Us=!1}}function ty(){return typeof performance<"u"?performance.now():Date.now()}function RI(Ar){(function(Ic){var xd;if(!it.value)return;const Mc=Math.max(2,(xd=oe.renderBatchBudgetMs)!=null?xd:6),Tc=Math.max(1,lt.value||1),iu=Math.max(1,Math.floor(Tc/4));Ic>1.5*Mc?at.value=Math.max(iu,Math.floor(.8*at.value)):Ic<.6*Mc&&at.value=Mc)return;const Tc=Math.max(1,Ar),iu=()=>{const Jp=ty();Cn=null;const Ig=Jn??Tc;Jn=null;const Xp=ty();Xe.value=Math.min(Mc,Xe.value+Ig),cn(Xe.value),(function(s3,ny){if(!ye)return void RI(ny);er=!0;const $I=++Oi;ft().then(()=>{var zI;if($I!==Oi)return;const qY=ty(),UY=Math.max(ny,qY-s3),jI=()=>{$I===Oi&&RI(UY)};if(Ut){let uh=null,e1=null,WI=!1;const qI=()=>{WI||(WI=!0,uh!==null&&(nu.delete(uh),uh=null),e1!==null&&(Ru.delete(e1),window.clearTimeout(e1),e1=null),jI())};return uh=Ut(()=>{qI()}),nu.add(uh),e1=window.setTimeout(()=>{uh!==null&&Dt&&Dt(uh),qI()},Math.max(32,(zI=oe.renderBatchIdleTimeoutMs)!=null?zI:120)),void Ru.add(e1)}const HI=window.setTimeout(()=>{Ru.delete(HI),jI()},0);Ru.add(HI)})})(Jp,ty()-Xp)};if(!ye||ml.immediate)return void iu();const Sd=Math.max(0,(Ic=oe.renderBatchDelay)!=null?Ic:16);if(Jn=Jn!=null?Math.max(Jn,Tc):Tc,Cn==null){if(!we&&rn&&window.requestIdleCallback){const Jp=Math.max(0,(xd=oe.renderBatchIdleTimeoutMs)!=null?xd:120);return Wn="idle",void(Cn=window.requestIdleCallback(()=>iu(),{timeout:Jp}))}if(Ut&&!we)return Wn="raf",void(Cn=Ut(()=>{Sd===0?iu():(Wn="timeout",Cn=window.setTimeout(()=>iu(),Sd))}));Wn="timeout",Cn=window.setTimeout(()=>iu(),Sd)}}function PI(Ar,ml={}){er?Us=!0:Ar==null?BI():OI(Ar,ml)}function BI(){it.value&&OI(vt.value?Math.max(1,Math.round(at.value)):Math.max(1,lt.value))}return ze([Ee,He,nt,it,lt,gt,()=>oe.renderBatchDelay],()=>{var Ar;const ml=He.value,Ic=It.value,xd=nt.value,Mc=!Object.is(xd,Ic.key),Tc=ml!==Ic.total,iu=Mc||Tc;It.value={key:xd,total:ml};const Sd=At.value,Jp=(Ar=oe.renderBatchDelay)!=null?Ar:16,Ig=Sd.batchSize!==lt.value||Sd.initial!==gt.value||Sd.delay!==Jp||Sd.enabled!==it.value;At.value={batchSize:lt.value,initial:gt.value,delay:Jp,enabled:it.value},Mc&&wn(ml),(iu||Ig||!it.value)&&_g(),(iu||Ig)&&(at.value=Math.max(1,lt.value||1)),iu&&yn();const Xp=Je.value;if(!ml)return Xe.value=0,void cn(0);if(!it.value)return Xe.value=Xp,void cn(Xe.value);const s3=Mc||Ic.total===0;Xe.value=s3||Ig?Math.min(Xp,gt.value):Math.min(Xe.value,Xp);const ny=Math.max(1,gt.value||lt.value||ml);Xe.value{it.value&&(typeof ml=="number"&&Ar<=ml||Ar>Xe.value&&PI())}),{cleanupBatchScheduler:_g}})({props:I,isClient:U,isTestEnv:yr,parsedNodesIdentity:Fr,parsedNodeCount:Oo,desiredRenderedCount:Ac,datasetKey:fY,batchingEnabled:Eu,incrementalRenderingActive:ya,resolvedBatchSize:jl,resolvedInitialBatch:ol,renderedCount:Bs,adaptiveBatchSize:ks,previousRenderContext:Bo,previousBatchConfig:Hl,requestFrame:Go,cancelFrame:Xi,hasIdleCallback:vr,cleanupNodeVisibility:D2,onDatasetKeyChanged:j=>{Gp(),Re(),ui(),gg(),j>0&&ll(j)},onDatasetChanged:()=>{An.value&&ti({immediate:!0})}});ze([ul,An,()=>F.value,()=>Y()],([j,oe])=>{if(!j)return R2(),void Vn();O2(),oe?ti({immediate:!0}):Vn()},{flush:"post",immediate:!0}),ze([()=>Zt.value.length,()=>An.value],j=>io(null,[j],function*([oe,ye]){ye&&oe&&U&&(yield ft(),ti({immediate:!0}))}),{flush:"post"}),ze(ei,j=>{j&&(function(){var oe;if(pr.value&&Zo.value&&Po.value&&((oe=fo.value)!=null&&oe[1]))return;const ye=Lt({type:"paragraph",children:[{type:"text",content:"Probe paragraph text",raw:"Probe paragraph text"}],raw:"Probe paragraph text"}),we=Lt({type:"list_item",children:[ye],raw:"- Probe paragraph text"}),Ee=Lt({type:"list",ordered:!1,items:[we],raw:"- Probe paragraph text"});pr.value=ye,Zo.value=we,Po.value=Ee;const He={1:null,2:null,3:null,4:null,5:null,6:null};for(let Je=1;Je<=6;Je++)He[Je]=Lt({type:"heading",level:Je,text:"Probe heading",children:[{type:"text",content:"Probe heading",raw:"Probe heading"}],raw:`${"#".repeat(Je)} Probe heading`});fo.value=He})()},{immediate:!0}),ze([()=>F.value,ei],()=>{if(!ei.value)return lg(),void(te.value=0);B2(),lg(),ei.value&&F.value&&typeof ResizeObserver<"u"&&(Cd=new ResizeObserver(()=>{B2(),lo.value&&ba(),jo.value&&Vp(),to("resize")}),Cd.observe(F.value))},{immediate:!0}),ze([ei,$t,Jl],()=>io(null,null,function*(){if(!ei.value)return le.value={paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}},void ui();yield ft(),(function(){if(!ei.value||typeof window>"u")return le.value={paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}},void ui();const j={paragraph:null,listItem:null,listWrapperOverhead:0,headings:{1:null,2:null,3:null,4:null,5:null,6:null}},oe=P2(bd(P.value),".paragraph-node");j.paragraph=T8(P.value,oe,"pre-wrap");const ye=bd(z.value),we=ye?.querySelector(".paragraph-node");j.listItem=T8(z.value,we,"pre-wrap");const Ee=Ve("readSimpleTextProbeProfile.list.offsetHeight",()=>{var Je,nt;return(nt=(Je=W.value)==null?void 0:Je.offsetHeight)!=null?nt:0}),He=Ve("readSimpleTextProbeProfile.listItem.offsetHeight",()=>{var Je,nt;return(nt=(Je=z.value)==null?void 0:Je.offsetHeight)!=null?nt:0});j.listWrapperOverhead=Math.max(0,Ee-He);for(let Je=1;Je<=6;Je++){const nt=P2(bd($[Je]),`h${Je}`);j.headings[Je]=T8($[Je],nt,"pre-wrap")}le.value=j,ui()})()}),{flush:"post",immediate:!0}),ze(()=>Zt.value.length,()=>{An.value&&ti({immediate:!0})}),ze([ei,te],()=>{ui(),An.value&&ti({immediate:!0}),lo.value&&ba(),jo.value&&Vp(),to("resize")},{immediate:!1}),ze(()=>oi.value,j=>{if(j)for(const[oe,ye]of xi)U2(oe,ye);else if(rg(),An.value)ti({immediate:!0});else for(const[oe,ye]of xi)ye&&Du(oe,!0)},{immediate:!1}),ze([se,he,()=>Y()],()=>{var j;(j=gr.refresh)==null||j.call(gr);for(const[oe,ye]of xi)U2(oe,ye)},{immediate:!1}),ze([()=>I.viewportPriority,()=>Zt.value.length,he],([j,oe,ye])=>{if(j!==!1){if(K.value&&(oe<=200||oe<=ye)){K.value=!1;for(const[we,Ee]of xi)U2(we,Ee)}}else K.value=!1}),ze(()=>Bs.value,()=>{An.value&&ti({immediate:!0})}),ze([Ho,Un,Ri,()=>Zt.value.length,An],()=>{tu()},{immediate:!0});let yg=null,kg=!1,Qp=null;function bg(){yg=null,Ew=null,Tw=void 0,Wp=null,gg()}function Xw(){Gp(),Re(),ui(),_o.clear();const j=Zt.value.length;j>0&&ll(j),Hw()}function e3(){Qw(),yt(),hg=null,oh=null,sh=null,H2=null,cg=null,dg=null,kg=!1,bg(),eI("restore"),ql(),Up()}function wg(j){var oe;return[(oe=qi())!=null?oe:"",vi(),Sc(),$2.value,mg(j),Zt.value.length,Math.round($s(0,Zt.value.length)),Math.round(th()),ao.count,Math.round(ao.total)].join(":")}function yI(){return io(this,null,function*(){var j,oe,ye,we;const Ee=(j=i.virtualScroll)==null?void 0:j.settledToken,He=mg(Ee),Je=vi(),nt=qi(),vt=Jl.value;if(hn.value&&((oe=i.virtualScroll)==null?void 0:oe.settleMode)==="manual"&&z2(Ee))if(Lw()){if(wg(Ee)!==Wp&&!kg){kg=!0;try{const it=yield qw({reason:"manual",expectedSettledTokenKey:He}),lt=mg()===He;Ww(Je,nt,vt)&&it.sessionKey===Je&&it.threadKey===nt&<&&it.stable&&it.phase==="final"&&(Wp=wg((ye=i.virtualScroll)==null?void 0:ye.settledToken))}finally{kg=!1,yield ft();const it=(we=i.virtualScroll)==null?void 0:we.settledToken,lt=z2(it)?wg(it):"";Ww(Je,nt,vt)&<&&Wp!==lt&&yI()}}}else to("manual")})}ze(hn,(j,oe)=>{if(j!==oe){if(!j)return e3(),void Qw();e3(),Xw(),Qp=Jl.value,to("content")}},{flush:"post"}),ze([hn,Jl],([j,oe])=>{j?Qp!=null?Qp!==oe&&(Qp=oe,(function(ye="resize"){Gp(),Re(),ui(),_o.clear();const we=Zt.value.length;we>0&&ll(we),Hw(),oh=null,sh=null,H2=null,hg=null,kg=!1,bg(),cI(),ft(()=>{_c(),lo.value&&ba(),jo.value&&Vp(),to(ye)})})("resize")):Qp=oe:Qp=null},{flush:"post",immediate:!0}),ze([hn,()=>vi(),()=>qi()],([j])=>{j&&(e3(),Xw(),eI("content"),to("content"))}),ze([hn,()=>vi(),()=>qi(),Jl,()=>Zt.value.length],([j])=>{j&&(function(oe="async-node"){let ye=!1;for(const[we,Ee]of Array.from(Ss.entries()))Iw(Ee)||(Ss.delete(we),Yn.delete(we),ye=!0);ye&&(jp(),to(oe))})("async-node")},{flush:"post"}),ze([hn,()=>{var j;return(j=i.virtualScroll)==null?void 0:j.sessionKey},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.measurementKey},()=>i.indexKey,()=>G.value],([j])=>{j&&(gg(),(function(oe="content"){if(!hn.value)return;const ye=[],we=Zt.value.length,Ee=$p(we);for(const He of Array.from(_o.keys())){if(He>=we){ye.push(He);continue}if(He=we&&_o.delete(He);ye.length&&((function(He,Je={}){const nt=Array.from(He,Number);js(nt);let vt=0;if(Hs(()=>(vt=Ca(nt,Je),vt>0)),vt>0)(function(it){for(const lt of it)_o.delete(lt)})(nt);else for(const it of nt)Xs.delete(it)})(ye,{notify:!1}),ui(),bg(),lo.value&&ba(),jo.value&&Vp(),to(oe))})("content"))},{flush:"post",immediate:!0}),ze([hn,()=>Zt.value.length,()=>vi(),()=>qi()],([j,oe,ye,we],[Ee,He,Je,nt])=>{j&&Ee&&ye===Je&&we===nt&&oe!==He&&bg()},{flush:"post"}),ze([hn,()=>{var j;return(j=i.virtualScroll)==null?void 0:j.heightCache},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.heightCacheWidth},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.restoreState},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.measurementKey},()=>Zt.value.length,()=>vi(),te],()=>{cI()},{flush:"post",immediate:!0}),ze([hn,()=>{var j;return(j=i.virtualScroll)==null?void 0:j.restoreState},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.restoreAnchor},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.measurementKey},()=>Zt.value.length,()=>vi(),te],j=>io(null,[j],function*([oe,ye]){if(!oe||!ye)return;yield ft();const we=(function(){var Ee;const He=(Ee=i.virtualScroll)==null?void 0:Ee.restoreAnchor;return He==null||He===!1?null:He===!0?"true":String(He)})();jw(ye,{restoreAnchor:we!=null,restoreToken:we??void 0})}),{flush:"post",immediate:!0}),ze([hn,te,()=>{var j;return(j=i.virtualScroll)==null?void 0:j.restoreState},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.measurementKey}],([j])=>{var oe;if(!j)return;const ye=(oe=i.virtualScroll)==null?void 0:oe.restoreState;ye&&oh&&sh==="restore"&&(aI(ye)||(Xw(),oh=null,sh=null,to("resize")))},{flush:"post"}),ze([hn,()=>Zt.value.length,()=>vi(),te],j=>io(null,[j],function*([oe]){var ye;const we=cg,Ee=dg;oe&&we&&(yield ft(),!jw(we,{restoreAnchor:Ee?.restoreAnchor===!0,restoreToken:(ye=Ee?.restoreToken)!=null?ye:"imperative",allowUncapturedAnchor:Ee?.allowUncapturedAnchor===!0})&&dI(we)||(cg=null,dg=null))}),{flush:"post",immediate:!0}),ze([hn,Ne,()=>{var j;return(j=i.virtualScroll)==null?void 0:j.settleMode},()=>vi(),()=>qi(),Jl,fl,dl,()=>Bs.value,Ac,()=>ao.count,()=>ao.total],([j,oe,ye])=>{if(!j||oe!==!0||ye==="manual"||!Nw())return;const we=(function(){var Ee;const He=Zt.value.length;return[(Ee=qi())!=null?Ee:"",vi(),Sc(),$2.value,He,Math.round($s(0,He)),Math.round(th()),ao.count,Math.round(ao.total)].join(":")})();yg!==we&&(yg=we,qw({reason:"final"}).then(Ee=>{Ee.stable||yg!==we||(yg=null)}))},{flush:"post",immediate:!0}),ze([hn,Ne,()=>{var j;return(j=i.virtualScroll)==null?void 0:j.settleMode},()=>{var j;return(j=i.virtualScroll)==null?void 0:j.settledToken},()=>vi(),()=>qi(),Jl,fl,dl,()=>Bs.value,Ac,()=>Zt.value.length,()=>ao.count,()=>ao.total],()=>{yI()},{flush:"post",immediate:!0}),ze([()=>Zt.value.length,An,Un,Ri,()=>uo.start,()=>uo.end],([j,oe,ye,we,Ee,He])=>{ue.value&&Ke("virtualization",{nodes:j,virtualization:oe,maxLiveNodes:ye,buffer:we,focusIndex:Ho.value,scroll:oe?(()=>{const Je=Xa.value||ae();return Je?{reverse:Ce(Je),scrollTop:Math.round(Je.scrollTop),scrollTopAbs:Math.round(Math.abs(Je.scrollTop)),scrollHeight:Math.round(Je.scrollHeight),clientHeight:Math.round(Je.clientHeight)}:null})():null,liveRange:{start:Ee,end:He},rendered:Bs.value})}),ze([()=>I.customId],([j],oe,ye)=>{if(!j||Ps)return;const we=(function(Ee,He){return Ee?(_s.controllers[Ee]=He,()=>{_s.controllers[Ee]===He&&delete _s.controllers[Ee]}):()=>{}})(j,{captureRestoreAnchor:wr,restoreAnchor:wa,getAnchorDrift:As,getReport:Wi});ye(()=>{we()})},{immediate:!0}),ii(()=>{(function(){if(hn.value)try{_c(),fg();const j=nh("manual");hI(j)&&(O(j),hg=j,Vw=pg());const oe=qp(j,{includeHeightCache:!0,includeContentHash:!0,allowAnchorFallback:!1,requireViewport:!0,includeEmptyState:!0});oe&&(H(oe),oe.anchor&&R(oe.anchor),Kp=vg(oe))}catch{}})(),AY(),rg(),be(),vI();for(const j of Gl.values())for(const oe of j)$e(oe);Gl.clear(),Aa.clear(),_o.clear(),Jw(),Gp(),lg(),ql(),Up(),Qw(),R2(),Vn()});const xY=d0("ViewportDeferredMermaidBlockNode",Xu({loader:()=>io(null,null,function*(){try{return(yield qo(()=>import("./index11-oTpPg1Iy.js"),__vite__mapDeps([7,5]))).default}catch(j){return console.warn('[markstream-vue] Optional peer dependencies for MermaidBlockNode are missing. Falling back to preformatted code rendering. To enable Mermaid rendering, please install "mermaid".',j),bl}}),loadingComponent:OF,delay:0}),OF),SY=d0("ViewportDeferredInfographicBlockNode",Xu({loader:()=>io(null,null,function*(){try{return(yield qo(()=>import("./index10-DPt9V4bc.js"),[])).default}catch(j){return console.warn('[markstream-vue] Failed to load InfographicBlockNode. Falling back to preformatted code rendering. To enable Infographic rendering, install "@antv/infographic" and configure setInfographicLoader with a dynamic loader.',j),bl}}),loadingComponent:RF,delay:0}),RF),_Y=d0("ViewportDeferredD2BlockNode",Xu(()=>io(null,null,function*(){try{return(yield qo(()=>import("./index8-MiLy1Wbt.js"),[])).default}catch(j){return console.warn('[markstream-vue] Optional peer dependencies for D2BlockNode are missing. Falling back to preformatted code rendering. To enable D2 rendering, please install "@terrastruct/d2".',j),bl}})),bl),kI={text:Fo,paragraph:rp,heading:Z4,code_block:k8,list:um,list_item:am,blockquote:j9,table:G0,definition_list:H9,footnote:W9,footnote_reference:la,footnote_anchor:K0,admonition:K9,vmr_container:U9,hardbreak:ff,link:Xr,image:df,thematic_break:q9,math_inline:Iu,math_block:_q,strong:Yr,emphasis:el,strikethrough:Jr,highlight:ua,insert:El,subscript:Tl,superscript:Ml,emoji:Il,checkbox:ra,checkbox_input:ra,inline_code:Er,html_inline:aa,reference:Qr,html_block:Z0},IY=D(()=>qs()),bI=D(()=>bF(I.codeBlockProps)),MY=D(()=>bF(I.codeBlockProps,{omit:["langs"]})),wI=D(()=>Bt(Bt({stream:I.codeBlockStream,darkTheme:I.codeBlockDarkTheme,lightTheme:I.codeBlockLightTheme,monacoOptions:I.codeBlockMonacoOptions,themes:I.themes,langs:m.value==="shiki"?I.langs:void 0,minWidth:I.codeBlockMinWidth,maxWidth:I.codeBlockMaxWidth},typeof me.value=="boolean"?{showTooltips:me.value}:{}),MY.value)),CI=D(()=>Bt(Dn(Bt({},wI.value),{langs:I.langs}),bI.value));function AI(j){return typeof j=="boolean"?j:void 0}const TY=D(()=>{const j=I.codeBlockProps||{},oe={},ye=AI(j.showLineNumbers);ye!==void 0&&(oe.showLineNumbers=ye);const we=AI(j.diffInline);we!==void 0&&(oe.diffInline=we);const Ee=(function(He){const Je=Number(He);return Number.isFinite(Je)&&Je>0?Je:void 0})(j.reservedHeightPx);return Ee!==void 0&&(oe.reservedHeightPx=Ee),oe}),EY=D(()=>Bt(Bt({stream:I.codeBlockStream,darkTheme:I.codeBlockDarkTheme,lightTheme:I.codeBlockLightTheme,themes:I.themes,langs:I.langs,minWidth:I.codeBlockMinWidth,maxWidth:I.codeBlockMaxWidth},typeof me.value=="boolean"?{showTooltips:me.value}:{}),bI.value)),LY=D(()=>Bt({},I.mermaidProps||{})),xI=D(()=>Bt({},I.d2Props||{})),NY=D(()=>Bt({},I.infographicProps||{})),Cg=D(()=>({typewriter:f.value,fade:I.fade,customHtmlTags:Ji.value.customHtmlTags})),FY=D(()=>Bt(Bt({},Cg.value),typeof me.value=="boolean"?{showTooltip:me.value}:{})),DY=D(()=>Bt(Bt({},Cg.value),typeof me.value=="boolean"?{showTooltips:me.value}:{})),RY=D(()=>Bt(Bt({},Cg.value),typeof me.value=="boolean"?{showTooltips:me.value}:{})),OY=D(()=>Bt(Bt({},Cg.value),typeof me.value=="boolean"?{showTooltips:me.value}:{}));function PY(j){return Array.isArray(j.children)&&j.children.length>0}const K2=D(()=>On.value.map(j=>{var oe,ye,we,Ee,He,Je,nt,vt;let it=(function(Dt){var rn,cn,wn,yn,Cn,Wn,Jn;if(Dt.type!=="code_block")return Dt;const Oi=Dt,er=[String((rn=Oi.language)!=null?rn:""),String((cn=Oi.loading)!=null?cn:""),String((wn=Oi.diff)!=null?wn:""),String((yn=Oi.code)!=null?yn:""),String((Cn=Oi.originalCode)!=null?Cn:""),String((Wn=Oi.updatedCode)!=null?Wn:""),String((Jn=Oi.raw)!=null?Jn:"")].join("\0"),Us=Ja.get(Oi);if(Us&&Us.signature===er)return Us.node;const nu=Bt({},Oi);return Ja.set(Oi,{signature:er,node:nu}),nu})(j.node);const lt=Z2(it);let gt=MI(it,lt);if((it.type==="html_block"||it.type==="html_inline")&>===kI[it.type]){const Dt=it,rn=String((oe=Dt.tag)!=null?oe:"").trim().toLowerCase()||YH(Dt.content);if(rn){const cn=Sn.value[rn];if(Yi.value.has(rn)&&cn)gt=cn,it=Dn(Bt({},Dt),{type:rn,tag:rn,content:gme(Dt.content,rn)});else if(JH((ye=Dt.content)!=null?ye:Dt.raw,rn)){const wn=String((Ee=(we=Dt.content)!=null?we:Dt.raw)!=null?Ee:"");it.type==="html_inline"?(gt=Fo,it={type:"text",content:wn,raw:wn}):(gt=rp,it={type:"paragraph",children:[{type:"text",content:wn,raw:wn}],raw:wn})}}}const Xe=it.type==="code_block"&&m.value==="pre"&>===bl&&!t3(Sn.value,lt);let at=Bt({},(function(Dt,rn,cn){const wn=rn??Z2(Dt);if(Dt.type==="code_block"){const yn=wn?t3(Sn.value,wn):void 0;if(cn&&m.value==="pre"&&!yn&&cn===bl)return TY.value;if(cn&&wn&&cn===yn)return wn==="mermaid"?_I(Dt):wn==="infographic"?II(Dt):wn==="d2"||wn==="d2lang"?xI.value:CI.value;if(cn&&cn===Sn.value.code_block)return CI.value;if(Me(cn))return EY.value}return wn==="mermaid"?_I(Dt):wn==="infographic"?II(Dt):wn==="d2"||wn==="d2lang"?xI.value:Dt.type==="link"?FY.value:Dt.type==="list"?DY.value:Dt.type==="blockquote"?RY.value:Dt.type==="table"?OY.value:Dt.type==="code_block"?wI.value:Cg.value})(it,lt,gt));const It=ei.value?an.value[j.index]:null;it.type==="code_block"&&It?.kind==="code-block"&&(at=Dn(Bt({},at),Xe?{reservedHeightPx:(He=It.height)!=null?He:It.contentHeight}:{estimatedHeightPx:It.height,estimatedContentHeightPx:It.contentHeight,estimatedDiffInline:It.diffInline})),Xe||it.type!=="code_block"||lt!=="mermaid"||O1(at.estimatedPreviewHeightPx)!=null||(at=Dn(Bt({},at),{estimatedPreviewHeightPx:fb(cb(String((Je=it.code)!=null?Je:"")))})),Xe||it.type!=="code_block"||lt!=="infographic"||O1(at.estimatedPreviewHeightPx)!=null||(at=Dn(Bt({},at),{estimatedPreviewHeightPx:hb(db(String((nt=it.code)!=null?nt:"")))})),it.type==="math_block"&&(at=Dn(Bt({},at),{cacheScope:Nn}));const At=(function(Dt,rn){const cn=String(Dt.type);return!v2(cn)&&Sn.value[cn]===rn})(it,gt),Ut=At?$x(it,pe.value):void 0;return Dn(Bt({},j),{node:it,component:gt,bindings:at,customBindings:Bt(Bt({},Ut??{}),at),rendersCustomNode:At,hasSlotChildren:PY(it),slotContent:String((vt=it.content)!=null?vt:""),isCodeBlock:it.type==="code_block",indexKey:`${IY.value}-${j.index}`,vnodeKey:`${eh.value}\0${j.index}\0${it.type}`})}));function Z2(j){var oe;return j?.type==="code_block"?String((oe=j.language)!=null?oe:"").trim().toLowerCase():""}function t3(j,oe){const ye=oe.trim().toLowerCase();if(ye)for(const we of[ye,U4(ye),aq(ye)]){const Ee=we&&j[we];if(Ee)return Ee}}function SI(j,oe,ye,we){var Ee,He;const Je=Bt({},j.value);return O1(Je.estimatedPreviewHeightPx)==null&&(Je.estimatedPreviewHeightPx=we(ye(String((Ee=oe?.code)!=null?Ee:"")),void 0,Je.maxHeight==="none"?null:(He=O1(Je.maxHeight))!=null?He:void 0)),Je}function _I(j){return SI(LY,j,cb,fb)}function II(j){return SI(NY,j,db,hb)}function MI(j,oe){if(!j)return zA;const ye=Sn.value,we=ye[String(j.type)];if(j.type==="code_block"){const Ee=oe??Z2(j),He=Ee?t3(ye,Ee):void 0;return He||(m.value==="pre"?ye.code_block||bl:Ee==="mermaid"?ye.mermaid||xY:Ee==="infographic"?ye.infographic||SY:Ee==="d2"||Ee==="d2lang"?ye.d2||_Y:we||ye.code_block||st.value)}return we||kI[String(j.type)]||zA}function n3(j){o("click",j)}function BY(j){var oe;(oe=j.target)!=null&&oe.closest("[data-node-index]")&&o("mouseover",j)}function $Y(j){var oe;(oe=j.target)!=null&&oe.closest("[data-node-index]")&&o("mouseout",j)}function TI(j){o("mouseover",j)}function EI(j){o("mouseout",j)}const ah=q(null),pl=q(!1),Ag=q(null),zY=D(()=>!(I.domMode!=="minimal"||Q.value||I.fade!==!1||f.value||pl.value||bs.value||An.value||fn.value||Ue.value||zl.value||Object.keys(Sn.value).length!==0));let xg,Yp=null,i3=0,G2=0,Q2=0;const LI=["code_block","admonition","table","math_block","html_block","image","thematic_break"],jY=new Set(LI),NI=[".typewriter-cursor",".height-estimation-probes",...LI.map(j=>`[data-node-type="${j}"]`),"script","style"].join(",");function FI(j){if(!j||typeof j!="object")return!1;const oe=j.type;return typeof oe=="string"&&jY.has(oe)}function Y2(j){var oe,ye;if(!j||typeof j!="object")return 0;const we=j,Ee=(ye=(oe=we.raw)!=null?oe:we.content)!=null?ye:we.code;if(typeof Ee=="string")return Ee.length;const He=we.children;if(Array.isArray(He))return He.reduce((nt,vt)=>nt+Y2(vt),0);const Je=we.items;return Array.isArray(Je)?Je.reduce((nt,vt)=>nt+Y2(vt),0):0}function J2(){xg&&(clearTimeout(xg),xg=void 0)}function o3(){i3+=1,Yp!=null&&(Xi?.(Yp),Yp=null)}function Sg(){o3(),Ad(),ah.value&&(ah.value.style.visibility="hidden")}function HY(j){var oe;if(j.nodeType!==Node.TEXT_NODE||!((oe=j.textContent)!=null?oe:"").trim())return!1;const ye=j.parentElement;return!!ye&&!ye.closest(NI)}function WY(j){let oe=j.lastChild;for(;oe;){if(HY(oe))return oe;if(oe.nodeType===Node.ELEMENT_NODE){const ye=oe;if(!ye.matches(NI)&&ye.lastChild){oe=ye.lastChild;continue}}for(;oe&&oe!==j&&!oe.previousSibling;)oe=oe.parentNode;if(!oe||oe===j)break;oe=oe.previousSibling}return null}function DI(){const j=K2.value;for(let oe=j.length-1;oe>=0;oe--){const ye=j[oe];if(!ye||FI(ye.node)||!q2(ye.index))continue;const we=xi.get(ye.index);if(!we)continue;const Ee=WY(we);if(Ee)return Ee}return null}function Ad(){Ag.value&&(Ag.value.classList.remove(PF),Ag.value=null)}function X2(){if(d.value!=="simple"||!U||!pl.value||!F.value)return void Ad();const j=DI(),oe=j?(function(ye){var we;const Ee=(we=ye.parentElement)==null?void 0:we.closest(".text-node");return Ee instanceof HTMLElement?Ee:ye.parentElement})(j):null;oe!==Ag.value&&(Ad(),oe&&(oe.classList.add(PF),Ag.value=oe))}function ey(){if(d.value!=="precise"||!U||!pl.value||Yp!=null)return;const j=i3,oe=()=>{Yp=null,j===i3&&(function(){var ye,we;if(d.value!=="precise"||!(U&&pl.value&&F.value&&ah.value))return;const Ee=F.value,He=ah.value;He.style.visibility="hidden";const Je=DI();if(!Je)return;let nt=0,vt=0,it=20,lt=!1;if(Je?.textContent){const gt=Je.textContent.length,Xe=document.createRange();Xe.setStart(Je,Math.max(0,gt-1)),Xe.setEnd(Je,gt);const at=typeof Xe.getClientRects=="function"?Xe.getClientRects():void 0,It=(we=at?.[at.length-1])!=null?we:(ye=Je.parentElement)==null?void 0:ye.getBoundingClientRect();if(It){const At=Ve("typewriterCursor.root.getBoundingClientRect",()=>Ee.getBoundingClientRect());nt=It.right-At.left+Ee.scrollLeft,vt=It.top-At.top+Ee.scrollTop,it=It.height||it,lt=!0}Xe.detach()}lt&&(He.style.transform=`translate(${Math.max(0,nt)}px, ${Math.max(0,vt)}px)`,He.style.height=`${it}px`,He.style.visibility="visible")})()};Go?Yp=Go(oe):oe()}return ze([ke,()=>i.content,()=>i.nodes,()=>I.typewriter,Ne],()=>io(null,null,function*(){var j,oe;if(!U||Q.value||!re.value)return;if(Ne.value)return pl.value=!1,J2(),void Sg();if((j=i.nodes)!=null&&j.length)return pl.value=!1,J2(),Sg(),G2=((oe=i.content)!=null?oe:"").length,void(Q2=ke.value.length);const ye=(function(){var nt,vt;return(nt=i.nodes)!=null&&nt.length?i.nodes.reduce((it,lt)=>it+Y2(lt),0):((vt=i.content)!=null?vt:"").length})(),we=(function(){var nt;return(nt=i.nodes)!=null&&nt.length?i.nodes.reduce((vt,it)=>vt+Y2(it),0):ke.value.length})(),Ee=!FI(Zt.value[Zt.value.length-1]),He=ye>G2,Je=we>Q2;if(!f.value||!Ee||!He&&!Je)return f.value&&Ee||(pl.value=!1,Sg()),G2=ye,void(Q2=we);G2=ye,Q2=we,pl.value=!0,d.value==="precise"&&ah.value&&(ah.value.style.visibility="hidden"),J2(),yield ft(),d.value==="simple"?X2():(Ad(),ey()),xg=setTimeout(()=>{xg=void 0,pl.value=!1},3e3)}),{flush:"post",immediate:!0}),ze(pl,j=>io(null,null,function*(){j?(yield ft(),d.value!=="simple"?(Ad(),d.value==="precise"&&ey()):X2()):Sg()}),{flush:"post"}),ze(d,()=>io(null,null,function*(){if(U&&!Q.value&&re.value&&pl.value){if(yield ft(),d.value==="simple")return o3(),void X2();Ad(),d.value!=="precise"?Sg():ey()}}),{flush:"post"}),ze([()=>Bs.value,()=>uo.start,()=>uo.end],()=>io(null,null,function*(){U&&!Q.value&&re.value&&pl.value&&(yield ft(),d.value!=="simple"?(Ad(),d.value==="precise"&&ey()):X2())}),{flush:"post"}),ii(()=>{J2(),o3(),Ad(),Wt.clear()}),(j,oe)=>{const ye=QB("NodeRenderer",!0);return p(Q)?(b(!0),N(Le,{key:0},Ct(K2.value,we=>(b(),N(Le,{key:we.vnodeKey},[we.rendersCustomNode?(b(),fe(To(we.component),ci({key:0,ref_for:!0},we.customBindings,{node:we.node,loading:we.node.loading,"index-key":we.indexKey,"custom-id":I.customId,"is-dark":I.isDark,onClick:n3,onMouseover:TI,onMouseout:EI,onCopy:oe[0]||(oe[0]=Ee=>s(Ee)),onHandleArtifactClick:oe[1]||(oe[1]=Ee=>o("handleArtifactClick",Ee))}),{default:de(()=>[we.hasSlotChildren?(b(),fe(ye,ci({key:0,ref_for:!0},ji.value,{nodes:we.node.children,"index-key":we.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):we.slotContent?(b(),fe(ye,ci({key:1,ref_for:!0},ji.value,{content:we.slotContent,final:!we.node.loading,"index-key":`${we.indexKey}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):X("",!0)]),_:2},1040,["node","loading","index-key","custom-id","is-dark"])):(b(),fe(To(we.component),ci({key:1,node:we.node,loading:we.node.loading,"index-key":we.indexKey},{ref_for:!0},we.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onClick:n3,onMouseover:TI,onMouseout:EI,onCopy:oe[2]||(oe[2]=Ee=>s(Ee)),onHandleArtifactClick:oe[3]||(oe[3]=Ee=>o("handleArtifactClick",Ee))}),null,16,["node","loading","index-key","custom-id","is-dark"]))],64))),128)):(b(),N("div",{key:1,ref_key:"containerRef",ref:F,class:De(["markstream-vue markdown-renderer",[{dark:I.isDark},{virtualized:An.value},{"virtual-scroll-coordinated":So.value},{"stable-layout":xs.value},{"typewriter-simple-cursor":pl.value&&d.value==="simple"}]]),"data-custom-id":I.customId,onClick:n3,onMouseover:BY,onMouseout:$Y},[Li.value||An.value?(b(),N(Le,{key:0},[Li.value?(b(),fe(A4e,{key:0,width:$t.value,"flow-root":An.value||So.value,"paragraph-node":pr.value,"list-item-node":Zo.value,"list-node":Po.value,"heading-nodes":fo.value,"set-paragraph-wrapper":Ht,"set-list-item-wrapper":vn,"set-list-wrapper":Bn,"set-heading-wrapper":wd},null,8,["width","flow-root","paragraph-node","list-item-node","list-node","heading-nodes"])):X("",!0),An.value?(b(),N("div",{key:1,class:"node-spacer",style:on({height:`${xn.value}px`}),"aria-hidden":"true"},null,4)):X("",!0)],64)):X("",!0),zY.value?(b(!0),N(Le,{key:1},Ct(K2.value,we=>(b(),N(Le,{key:we.vnodeKey},[q2(we.index)?(b(),fe(To(we.component),ci({key:0,node:we.node,loading:we.node.loading,"index-key":we.indexKey},{ref_for:!0},we.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onMouseover:oe[4]||(oe[4]=Ee=>o("mouseover",Ee)),onMouseout:oe[5]||(oe[5]=Ee=>o("mouseout",Ee)),onCopy:oe[6]||(oe[6]=Ee=>s(Ee)),onHandleArtifactClick:oe[7]||(oe[7]=Ee=>o("handleArtifactClick",Ee))}),null,16,["node","loading","index-key","custom-id","is-dark"])):X("",!0)],64))),128)):(b(!0),N(Le,{key:2},Ct(K2.value,we=>(b(),N("div",{key:we.vnodeKey,ref_for:!0,ref:Ee=>U2(we.index,Ee),class:"node-slot","data-node-index":we.index,"data-node-type":we.node.type},[q2(we.index)?(b(),N("div",{key:0,ref_for:!0,ref:Ee=>(function(He,Je){var nt;Je||(function(gt){const Xe=`${qs()}-${gt}`;let at=!1;for(const It of Array.from(Yn.keys())){const At=Ss.get(It);(At?.index===gt||It===Xe||It.startsWith(`${Xe}-`))&&(Yn.delete(It),Ss.delete(It),at=!0)}at&&(jp(),to("async-node"))})(He),cl.delete(He),(function(gt){var Xe;const at=((Xe=Aa.get(gt))!=null?Xe:0)+1;Aa.set(gt,at)})(He);const vt=Gl.get(He);if(vt){for(const gt of vt)$e(gt);Gl.delete(He)}if((function(gt){const Xe=Rr.get(gt);Xe&&(zo?.unobserve(Xe),Ya.delete(Xe),Rr.delete(gt))})(He),!Je||!Ga.value)return $r.delete(He),void Aa.delete(He);$r.set(He,Je);const it=()=>{V2(He,Je)};queueMicrotask(it);const lt=(zo||typeof ResizeObserver>"u"||(zo=new ResizeObserver(gt=>{if(gt.length)for(const Xe of gt){const at=Ya.get(Xe.target),It=Rr.get(at??-1);at!=null&&It&&V2(at,It)}else _c()})),zo);if(lt&&(Rr.set(He,Je),Ya.set(Je,He),lt.observe(Je)),typeof window<"u"){const gt=((nt=Zt.value[He])==null?void 0:nt.type)==="code_block"?[16,80,240,800]:Ne.value?[80]:[];if(gt.length){const Xe=gt.map(at=>Ie(at,it,"node-resize")).filter(at=>at!=null);Xe.length&&Gl.set(He,Xe)}}})(we.index,Ee),class:"node-content"},[we.isCodeBlock?we.rendersCustomNode?(b(),fe(To(we.component),ci({key:1,ref_for:!0},we.customBindings,{node:we.node,loading:we.node.loading,"index-key":we.indexKey,"custom-id":I.customId,"is-dark":I.isDark,onCopy:oe[12]||(oe[12]=Ee=>s(Ee)),onHandleArtifactClick:oe[13]||(oe[13]=Ee=>o("handleArtifactClick",Ee))}),{default:de(()=>[we.hasSlotChildren?(b(),fe(ye,ci({key:0,ref_for:!0},ji.value,{nodes:we.node.children,"index-key":we.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):we.slotContent?(b(),fe(ye,ci({key:1,ref_for:!0},ji.value,{content:we.slotContent,final:!we.node.loading,"index-key":`${we.indexKey}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):X("",!0)]),_:2},1040,["node","loading","index-key","custom-id","is-dark"])):(b(),fe(To(we.component),ci({key:2,node:we.node,loading:we.node.loading,"index-key":we.indexKey},{ref_for:!0},we.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onCopy:oe[14]||(oe[14]=Ee=>s(Ee)),onHandleArtifactClick:oe[15]||(oe[15]=Ee=>o("handleArtifactClick",Ee))}),null,16,["node","loading","index-key","custom-id","is-dark"])):(b(),fe(mo,{key:0,name:"fade",css:I.fade!==!1,appear:I.fade!==!1},{default:de(()=>[we.rendersCustomNode?(b(),fe(To(we.component),ci({key:0,ref_for:!0},we.customBindings,{node:we.node,loading:we.node.loading,"index-key":we.indexKey,"custom-id":I.customId,"is-dark":I.isDark,onCopy:oe[8]||(oe[8]=Ee=>s(Ee)),onHandleArtifactClick:oe[9]||(oe[9]=Ee=>o("handleArtifactClick",Ee))}),{default:de(()=>[we.hasSlotChildren?(b(),fe(ye,ci({key:0,ref_for:!0},ji.value,{nodes:we.node.children,"index-key":we.indexKey,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["nodes","index-key"])):we.slotContent?(b(),fe(ye,ci({key:1,ref_for:!0},ji.value,{content:we.slotContent,final:!we.node.loading,"index-key":`${we.indexKey}-content`,"smooth-streaming":!1,"batch-rendering":!1,"defer-nodes-until-visible":!1,"render-as-fragment":!0}),null,16,["content","final","index-key"])):X("",!0)]),_:2},1040,["node","loading","index-key","custom-id","is-dark"])):(b(),fe(To(we.component),ci({key:1,node:we.node,loading:we.node.loading,"index-key":we.indexKey},{ref_for:!0},we.bindings,{"custom-id":I.customId,"is-dark":I.isDark,onCopy:oe[10]||(oe[10]=Ee=>s(Ee)),onHandleArtifactClick:oe[11]||(oe[11]=Ee=>o("handleArtifactClick",Ee))}),null,16,["node","loading","index-key","custom-id","is-dark"]))]),_:2},1032,["css","appear"]))],512)):(b(),N("div",{key:1,class:"node-placeholder",style:on({height:`${Br(we.index)}px`})},null,4))],8,_4e))),128)),pl.value&&d.value==="precise"?(b(),N("span",{key:3,ref_key:"typewriterCursorRef",ref:ah,class:"typewriter-cursor","aria-hidden":"true"},null,512)):X("",!0),An.value?(b(),N("div",{key:4,class:"node-spacer",style:on({height:`${En.value}px`}),"aria-hidden":"true"},null,4)):X("",!0)],42,S4e))}}})),[["__scopeId","data-v-a9489508"]]),Ll=zq;Ll.install=e=>{const t=new Set(["MarkdownRender","NodeRenderer",Ll.__name,Ll.name].filter(n=>!!n));for(const n of t)e.component(n,zq)};const Xx=Object.freeze(Object.defineProperty({__proto__:null,default:Ll},Symbol.toStringTag,{value:"Module"})),I4e={key:0,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},M4e={key:1,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},T4e={key:2,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},E4e={key:3,xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"admonition-icon"},L4e={class:"admonition-title"},N4e=["aria-expanded","aria-controls"],F4e=["id"],K9=Ei(ot({__name:"AdmonitionNode",props:{node:{},indexKey:{},isDark:{type:Boolean},typewriter:{type:Boolean},fade:{type:Boolean},customId:{}},emits:["copy"],setup(e,{emit:t}){var n;const i=e,o=t,s=D(()=>{if(i.node.title&&i.node.title.trim().length)return i.node.title;const u=i.node.kind||"note";return u.charAt(0).toUpperCase()+u.slice(1)}),r=q(!!i.node.collapsible&&!((n=i.node.open)==null||n));function l(){i.node.collapsible&&(r.value=!r.value)}const a=`admonition-${Math.random().toString(36).slice(2,9)}`;return(u,c)=>(b(),N("div",{class:De(["admonition",[`admonition-${i.node.kind}`]])},[_("div",{id:a,class:"admonition-legend"},[i.node.kind==="note"||i.node.kind==="info"?(b(),N("svg",I4e,[...c[1]||(c[1]=[_("circle",{cx:"12",cy:"12",r:"10"},null,-1),_("path",{d:"M12 16v-4"},null,-1),_("path",{d:"M12 8h.01"},null,-1)])])):i.node.kind==="tip"?(b(),N("svg",M4e,[...c[2]||(c[2]=[_("path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"},null,-1),_("path",{d:"M9 18h6"},null,-1),_("path",{d:"M10 22h4"},null,-1)])])):i.node.kind==="warning"||i.node.kind==="caution"?(b(),N("svg",T4e,[...c[3]||(c[3]=[_("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"},null,-1),_("path",{d:"M12 9v4"},null,-1),_("path",{d:"M12 17h.01"},null,-1)])])):i.node.kind==="danger"||i.node.kind==="error"?(b(),N("svg",E4e,[...c[4]||(c[4]=[_("polygon",{points:"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2"},null,-1),_("path",{d:"M12 8v4"},null,-1),_("path",{d:"M12 16h.01"},null,-1)])])):X("",!0),_("span",L4e,B(s.value),1),i.node.collapsible?(b(),N("button",{key:4,class:"admonition-toggle","aria-expanded":!r.value,"aria-controls":`${a}-content`,onClick:l},[(b(),N("svg",{style:on({rotate:r.value?"0deg":"90deg"}),xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[...c[5]||(c[5]=[_("path",{d:"m9 18 6-6-6-6"},null,-1)])],4))],8,N4e)):X("",!0)]),si(_("div",{id:`${a}-content`,class:"admonition-content","aria-labelledby":a},[V(p(Ll),{"index-key":`admonition-${e.indexKey}`,nodes:i.node.children,"custom-id":i.customId,typewriter:i.typewriter,fade:i.fade,onCopy:c[0]||(c[0]=d=>o("copy",d))},null,8,["index-key","nodes","custom-id","typewriter","fade"])],8,F4e),[[Eo,!r.value]])],2))}}),[["__scopeId","data-v-a83480e1"]]);K9.install=e=>{e.component(K9.__name,K9)};const UA=()=>qo(()=>import("./d2_markstream-vue-yoD6TSFD.js"),[]);let Py=null,By=UA,$y=null,BF=!1,$F=!1;function V8t(){return io(this,null,function*(){if(Py)return Py;const e=By;return e?e===UA&&BF?null:$y||($y=io(null,null,function*(){let t;try{t=yield e()}catch(n){if(e===UA)return e===By&&(BF=!0,(function(i){$F||($F=!0,console.warn('[markstream-vue] Optional dependency "@terrastruct/d2" is not installed. D2 blocks will render as source.',i))})(n)),null;throw n}finally{e===By&&($y=null)}return e!==By?null:t?(Py=(function(n){var i;if(!n)return n;if(n.D2&&typeof n.D2=="function")return n.D2;if(n.default&&n.default.D2&&typeof n.default.D2=="function")return n.default.D2;const o=(i=n.default)!=null?i:n;return typeof o=="function"?o:o?.D2&&typeof o.D2=="function"?o.D2:o})(t),Py):null}),$y):null})}let zy=null,jq=null,jy=null;function K8t(){return typeof jq=="function"}function Z8t(){return io(this,null,function*(){if(zy)return zy;const e=jq;return e?jy||(jy=io(null,null,function*(){const t=yield e(),n=(function(i){var o,s,r;if(!i)return null;const l=(o=i.default)!=null?o:i,a=typeof l=="function"&&typeof((s=l.prototype)==null?void 0:s.render)=="function"?l:(r=i.Infographic)!=null?r:l?.Infographic;return typeof a=="function"?a:null})(t);return n?(zy=n,zy):null}).finally(()=>{jy=null}),jy):null})}const G8t=Symbol("markstreamLanguageIconResolver");function D4e(e){return new Worker("/assets/katexRenderer.worker-CO_gEm4q.js",{type:"module",name:e?.name})}function R4e(e){return new Worker("/assets/mermaidParser.worker-BFSlSHEW.js",{type:"module",name:e?.name})}let zF=!1;function Hq(){zF||typeof Worker>"u"||(zF=!0,f9e(new D4e),S9e(new R4e))}Hq();function Jd(e,t,n="/api/v1"){return`${e}${n}${t.startsWith("/")?t:`/${t}`}`}function jF(e,t){const n=new URL(`${e}/api/v1/ws`);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.searchParams.set("client_id",t),n.toString()}const eS={},Cb=Symbol("resolveImage"),Dc=3e4,Hy=5*6e4,HF=5*6e4,Wq="0123456789ABCDEFGHJKMNPQRSTVWXYZ",VA=500,qq=40101;function WF(e,t){for(const[n,i]of Object.entries(t))if(i!==void 0)if(Array.isArray(i))for(const o of i)o!==void 0&&e.append(n,String(o));else e.set(n,String(i))}function f0(e=Dc){try{return AbortSignal.timeout(e)}catch{return}}function O4e(e,t){const n=f0(e);if(n===void 0)return t;try{return AbortSignal.any([n,t])}catch{return t}}function P4e(e,t){let n="",i=e;for(let o=0;oWq[n%32]).join("")}function jg(){return`${P4e(Date.now(),10)}${B4e(16)}`}function qF(e){try{const t=[];return e.forEach((n,i)=>{typeof n=="string"?t.push({field:i,value:n}):t.push({field:i,file:n.name,size:n.size,type:n.type})}),{formData:t}}catch{return"[FormData]"}}async function E8(e){try{const t=await e.text();return t?t.length>VA?`${t.slice(0,VA)}...`:t:void 0}catch{return}}class UF{constructor(t){this.opts=t,this.tracer=t.tracer??eS}tracer;async get(t,n){return this.request("GET",t,void 0,n)}async getBlob(t,n,i){let o=Jd(this.opts.origin,t,this.opts.restBasePath);if(n){const c=new URLSearchParams;WF(c,n);const d=c.toString();d&&(o=`${o}?${d}`)}const s=jg(),r={"X-Request-Id":s};this.addClientHeaders(r);const l=Date.now();this.tracer.restRequest?.({method:"GET",path:t,url:o,requestId:s});let a;try{a=await fetch(o,{method:"GET",headers:r,signal:f0()})}catch(c){throw this.tracer.restFailure?.({method:"GET",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:c}),new Xl({message:`Network error calling GET ${t}`,cause:c,method:"GET",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Dc,timestamp:Date.now(),durationMs:Date.now()-l})}if(a.ok){this.tracer.restResponse?.({method:"GET",path:t,requestId:s,status:a.status,durationMs:Date.now()-l,code:0,msg:""});const c=Number(a.headers.get("content-length")??0);if(i?.maxBytes!==void 0&&c>i.maxBytes)throw a.body?.cancel(),new z7({size:c,limit:i.maxBytes});return a.blob()}let u;try{u=await a.clone().json()}catch{}throw this.checkAuthRequired(a,u?.code??0),this.tracer.restResponse?.({method:"GET",path:t,requestId:s,status:a.status,durationMs:Date.now()-l,code:u?.code??a.status,msg:u?.msg??a.statusText,envelopeRequestId:u?.request_id}),new Zu({code:u?.code??a.status,msg:u?.msg??a.statusText,requestId:u?.request_id??s,details:u?.details,timestamp:Date.now(),durationMs:Date.now()-l})}async post(t,n,i){return this.request("POST",t,n,void 0,i)}async postZip(t,n,i){const o="POST",s=Jd(this.opts.origin,t,this.opts.restBasePath),r=jg(),l={"X-Request-Id":r,"Content-Type":"application/json; charset=utf-8"};this.addClientHeaders(l);const a=Date.now();this.tracer.restRequest?.({method:o,path:t,url:s,requestId:r,body:i});let u;try{u=await fetch(s,{method:o,headers:l,body:JSON.stringify(n),signal:f0(Hy)})}catch(h){throw this.tracer.restFailure?.({method:o,path:t,requestId:r,phase:"fetch",durationMs:Date.now()-a,error:h}),new Xl({message:`Network error calling ${o} ${t}`,cause:h,method:o,path:t,url:s,requestId:r,phase:"fetch",timeoutMs:Hy,timestamp:Date.now(),durationMs:Date.now()-a})}const c=u.headers.get("content-type")??void 0,d=c?.split(";",1)[0]?.trim().toLowerCase();if(!u.ok||d!=="application/zip"){let h;try{h=await u.clone().json()}catch{}if(this.checkAuthRequired(u,h?.code??0),!u.ok||h!==void 0&&h.code!==0){const y=h?.code??u.status,k=h?.msg??u.statusText;throw this.tracer.restResponse?.({method:o,path:t,requestId:r,status:u.status,durationMs:Date.now()-a,code:y,msg:k,envelopeRequestId:h?.request_id}),new Zu({code:y,msg:k,requestId:h?.request_id??r,details:h?.details,timestamp:Date.now(),durationMs:Date.now()-a})}const m=u.clone(),g=new TypeError(`Expected application/zip, received ${c??"no content type"}`);throw this.tracer.restFailure?.({method:o,path:t,requestId:r,phase:"parse",durationMs:Date.now()-a,status:u.status,error:g}),new Xl({message:`Invalid ZIP response from ${o} ${t}`,cause:g,method:o,path:t,url:s,requestId:r,phase:"parse",timeoutMs:Hy,status:u.status,statusText:u.statusText,contentType:c,bodyPreview:await E8(m),timestamp:Date.now(),durationMs:Date.now()-a})}let f;try{f=await u.blob()}catch(h){throw this.tracer.restFailure?.({method:o,path:t,requestId:r,phase:"parse",durationMs:Date.now()-a,status:u.status,error:h}),new Xl({message:`Failed to read ZIP response from ${o} ${t}`,cause:h,method:o,path:t,url:s,requestId:r,phase:"parse",timeoutMs:Hy,status:u.status,statusText:u.statusText,contentType:c,timestamp:Date.now(),durationMs:Date.now()-a})}return this.tracer.restResponse?.({method:o,path:t,requestId:r,status:u.status,durationMs:Date.now()-a,code:0,msg:""}),{blob:f,contentDisposition:u.headers.get("content-disposition")??void 0}}async postForm(t,n,i){if(i?.onUploadProgress!==void 0)return this.postFormXhr(t,n,i.onUploadProgress);const o=Jd(this.opts.origin,t,this.opts.restBasePath),s=jg(),r={"X-Request-Id":s};this.addClientHeaders(r);const l=Date.now();this.tracer.restRequest?.({method:"POST",path:t,url:o,requestId:s,body:qF(n)});let a;try{a=await fetch(o,{method:"POST",headers:r,body:n,signal:f0()})}catch(d){throw this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:d}),new Xl({message:`Network error calling POST ${t}`,cause:d,method:"POST",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Dc,timestamp:Date.now(),durationMs:Date.now()-l})}let u;const c=a.clone();try{u=await a.json()}catch(d){throw this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"parse",durationMs:Date.now()-l,status:a.status,error:d}),new Xl({message:`Failed to parse JSON response from POST ${t}`,cause:d,method:"POST",path:t,url:o,requestId:s,phase:"parse",timeoutMs:Dc,status:a.status,statusText:a.statusText,contentType:a.headers.get("content-type")??void 0,bodyPreview:await E8(c),timestamp:Date.now(),durationMs:Date.now()-l})}if(this.tracer.restResponse?.({method:"POST",path:t,requestId:s,status:a.status,durationMs:Date.now()-l,code:u.code,msg:u.msg,envelopeRequestId:u.request_id,data:u.data}),this.checkAuthRequired(a,u.code),u.code!==0){const d=u.code??a.status;throw new Zu({code:d,msg:u.msg??a.statusText,requestId:u.request_id??s,details:u.details,timestamp:Date.now(),durationMs:Date.now()-l})}return u.data}postFormXhr(t,n,i){const o=Jd(this.opts.origin,t,this.opts.restBasePath),s=jg(),r={"X-Request-Id":s};this.addClientHeaders(r);const l=Date.now();return this.tracer.restRequest?.({method:"POST",path:t,url:o,requestId:s,body:qF(n)}),new Promise((a,u)=>{const c=new XMLHttpRequest;c.open("POST",o),c.timeout=Dc;for(const[d,f]of Object.entries(r))c.setRequestHeader(d,f);c.upload.onprogress=d=>{d.lengthComputable&&i(d.loaded,d.total)},c.onerror=()=>{this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:c.statusText||"network error"}),u(new Xl({message:`Network error calling POST ${t}`,cause:null,method:"POST",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Dc,timestamp:Date.now(),durationMs:Date.now()-l}))},c.ontimeout=()=>{this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"fetch",durationMs:Date.now()-l,error:"timeout"}),u(new Xl({message:`Timeout calling POST ${t}`,cause:null,method:"POST",path:t,url:o,requestId:s,phase:"fetch",timeoutMs:Dc,timestamp:Date.now(),durationMs:Date.now()-l}))},c.onload=()=>{let d;try{d=JSON.parse(c.responseText)}catch(f){this.tracer.restFailure?.({method:"POST",path:t,requestId:s,phase:"parse",durationMs:Date.now()-l,status:c.status,error:f}),u(new Xl({message:`Failed to parse JSON response from POST ${t}`,cause:f,method:"POST",path:t,url:o,requestId:s,phase:"parse",timeoutMs:Dc,status:c.status,statusText:c.statusText,bodyPreview:c.responseText.slice(0,VA),timestamp:Date.now(),durationMs:Date.now()-l}));return}if(this.tracer.restResponse?.({method:"POST",path:t,requestId:s,status:c.status,durationMs:Date.now()-l,code:d.code,msg:d.msg,envelopeRequestId:d.request_id,data:d.data}),this.checkAuthStatus(c.status,d.code),d.code!==0){const f=d.code??c.status;u(new Zu({code:f,msg:d.msg??c.statusText,requestId:d.request_id??s,details:d.details,timestamp:Date.now(),durationMs:Date.now()-l}));return}a(d.data)},c.send(n)})}async patch(t,n){return this.request("PATCH",t,n)}async put(t,n){return this.request("PUT",t,n)}async delete(t){return this.request("DELETE",t)}async request(t,n,i,o,s={}){const r=s.allowCodes??[],l=s.timeoutMs??Dc,a=s.signal;let u=Jd(this.opts.origin,n,this.opts.restBasePath);if(o){const y=new URLSearchParams;WF(y,o);const k=y.toString();k&&(u=`${u}?${k}`)}const c=jg(),d={"X-Request-Id":c};this.addClientHeaders(d),i!==void 0&&(d["Content-Type"]="application/json; charset=utf-8");const f=Date.now();this.tracer.restRequest?.({method:t,path:n,url:u,requestId:c,body:i});let h;try{h=await fetch(u,{method:t,headers:d,body:i!==void 0?JSON.stringify(i):void 0,signal:a!==void 0?O4e(l,a):f0(l)})}catch(y){throw a?.aborted&&y instanceof Error&&y.name==="AbortError"?y:(this.tracer.restFailure?.({method:t,path:n,requestId:c,phase:"fetch",durationMs:Date.now()-f,error:y}),new Xl({message:`Network error calling ${t} ${n}`,cause:y,method:t,path:n,url:u,requestId:c,phase:"fetch",timeoutMs:l,timestamp:Date.now(),durationMs:Date.now()-f}))}let m;const g=h.clone();try{const y=await h.text();m=h.status===204&&y===""?{code:0,msg:"",data:null,request_id:c}:JSON.parse(y)}catch(y){throw a?.aborted&&y instanceof Error&&y.name==="AbortError"?y:(this.tracer.restFailure?.({method:t,path:n,requestId:c,phase:"parse",durationMs:Date.now()-f,status:h.status,error:y}),new Xl({message:`Failed to parse JSON response from ${t} ${n}`,cause:y,method:t,path:n,url:u,requestId:c,phase:"parse",timeoutMs:l,status:h.status,statusText:h.statusText,contentType:h.headers.get("content-type")??void 0,bodyPreview:await E8(g),timestamp:Date.now(),durationMs:Date.now()-f}))}if(this.tracer.restResponse?.({method:t,path:n,requestId:c,status:h.status,durationMs:Date.now()-f,code:m.code,msg:m.msg,envelopeRequestId:m.request_id,data:m.data}),this.checkAuthRequired(h,m.code),m.code!==0&&!r.includes(m.code))throw new Zu({code:typeof m.code=="number"?m.code:h.status,msg:typeof m.msg=="string"&&m.msg.length>0?m.msg:`HTTP ${h.status}${h.statusText?` ${h.statusText}`:""}`,requestId:m.request_id??c,details:m.details,timestamp:Date.now(),durationMs:Date.now()-f});return m.data}addClientHeaders(t){const n=this.opts.credentialStore?.getToken();n!==void 0&&(t.Authorization=`Bearer ${n}`);const i=this.opts.identity;i!==void 0&&(t["X-Kimi-Client-Id"]=i.clientId,t["X-Kimi-Client-Name"]=i.clientName,t["X-Kimi-Client-Version"]=i.clientVersion,t["X-Kimi-Client-Ui-Mode"]=i.clientUiMode)}checkAuthRequired(t,n){this.checkAuthStatus(t.status,n)}checkAuthStatus(t,n){(t===401||n===qq)&&this.opts.credentialStore?.markAuthRequired?.()}}function Uq(e){return{inputTokens:e.input_tokens,outputTokens:e.output_tokens,cacheReadTokens:e.cache_read_tokens,cacheCreationTokens:e.cache_creation_tokens,totalCostUsd:e.total_cost_usd,contextTokens:e.context_tokens,contextLimit:e.context_limit,turnCount:e.turn_count}}function VF(e){return e.contextTokens===0&&e.contextLimit===0&&e.inputTokens===0&&e.outputTokens===0&&e.turnCount===0}function Wu(e){return{id:e.id,title:e.title,createdAt:e.created_at,updatedAt:e.updated_at,busy:e.busy,mainTurnActive:e.main_turn_active,pendingInteraction:e.pending_interaction,lastTurnReason:e.last_turn_reason,archived:e.archived??!1,archivedAt:e.archived_at,currentPromptId:e.current_prompt_id,lastPrompt:e.last_prompt,cwd:e.metadata.cwd,model:e.agent_config.model,usage:Uq(e.usage),messageCount:e.message_count,lastSeq:e.last_seq,workspaceId:e.workspace_id,parentSessionId:typeof e.metadata.parent_session_id=="string"?e.metadata.parent_session_id:void 0}}function Wy(e){const t=e.activity.status;return{id:e.id,title:e.meta.title??e.meta.last_prompt??e.id.slice(0,12),createdAt:new Date(e.meta.created_at).toISOString(),updatedAt:new Date(e.meta.updated_at).toISOString(),busy:t==="running",pendingInteraction:t==="approval"?"approval":t==="question"?"question":void 0,lastTurnReason:t==="failed"?"failed":void 0,archived:e.meta.archived,archivedAt:e.meta.archived_at==null?void 0:new Date(e.meta.archived_at).toISOString(),lastPrompt:e.meta.last_prompt??void 0,cwd:e.workspace.cwd??"",model:e.activity.model??"",pullRequest:e.git===void 0?void 0:e.git.pull_request,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalCostUsd:0,contextTokens:0,contextLimit:0,turnCount:0},messageCount:0,lastSeq:0,workspaceId:e.workspace.id.length>0?e.workspace.id:void 0}}function Y0(e){return{id:e.id,root:e.root,name:e.name,lastOpenedAt:e.last_opened_at,sessionCount:e.session_count}}function KF(e){return e.kind==="base64"?{kind:"base64",mediaType:e.media_type,data:e.data}:e.kind==="file"?{kind:"file",fileId:e.file_id}:e.kind==="session_media"?{kind:"sessionMedia",fileId:e.file_id}:{kind:"url",url:e.url}}function Q4(e){switch(e.type){case"text":return{type:"text",text:e.text};case"tool_use":return{type:"toolUse",toolCallId:e.tool_call_id,toolName:e.tool_name,input:e.input};case"tool_result":return{type:"toolResult",toolCallId:e.tool_call_id,output:e.output,isError:e.is_error};case"image":return{type:"image",source:KF(e.source)};case"video":return{type:"video",source:KF(e.source)};case"file":return{type:"file",fileId:e.file_id,name:e.name,mediaType:e.media_type,size:e.size};case"thinking":return{type:"thinking",thinking:e.thinking,signature:e.signature};default:return{type:"unknown",raw:e}}}function Vq(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content.map(Q4),createdAt:e.created_at,promptId:e.prompt_id,parentMessageId:e.parent_message_id,metadata:e.metadata}}function Kq(e){switch(e.type){case"text":return{type:"text",text:e.text};case"toolUse":return{type:"tool_use",tool_call_id:e.toolCallId,tool_name:e.toolName,input:e.input};case"toolResult":return{type:"tool_result",tool_call_id:e.toolCallId,output:e.output,is_error:e.isError};case"image":case"video":{const t=e.source;let n;return t.kind==="base64"?n={kind:"base64",media_type:t.mediaType,data:t.data}:t.kind==="file"?n={kind:"file",file_id:t.fileId}:t.kind==="sessionMedia"?n={kind:"session_media",file_id:t.fileId}:n={kind:"url",url:t.url},{type:e.type,source:n}}case"file":return{type:"file",file_id:e.fileId,name:e.name,media_type:e.mediaType,size:e.size};case"thinking":return{type:"thinking",thinking:e.thinking,signature:e.signature};case"unknown":return e.raw}}function $4e(e){return{content:e.content.map(Kq),metadata:e.metadata,agent_id:e.agentId,model:e.model,thinking:e.thinking,permission_mode:e.permissionMode,plan_mode:e.planMode,swarm_mode:e.swarmMode,goal_objective:e.goalObjective,goal_control:e.goalControl,skills:e.skills}}function z4e(e){return{decision:e.decision,scope:e.scope,feedback:e.feedback,selected_label:e.selectedLabel}}function j4e(e){return{approvalId:e.approval_id,sessionId:e.session_id,turnId:e.turn_id,toolCallId:e.tool_call_id,toolName:e.tool_name,action:e.action,display:e.tool_input_display??e.display,expiresAt:e.expires_at,createdAt:e.created_at}}function H4e(e){return{id:e.id,label:e.label,description:e.description,recommended:e.recommended===!0||e.is_recommended===!0}}function W4e(e){return{id:e.id,question:e.question,header:e.header,body:e.body,options:e.options.map(H4e),multiSelect:e.multi_select,allowOther:e.allow_other,otherLabel:e.other_label,otherDescription:e.other_description}}function q4e(e){return{questionId:e.question_id,sessionId:e.session_id,turnId:e.turn_id,toolCallId:e.tool_call_id,questions:e.questions.map(W4e),createdAt:e.created_at}}function U4e(e){switch(e.kind){case"single":return{kind:"single",option_id:e.optionId};case"multi":return{kind:"multi",option_ids:e.optionIds};case"other":return{kind:"other",text:e.text};case"multiWithOther":return{kind:"multi_with_other",option_ids:e.optionIds,other_text:e.otherText};case"skipped":return{kind:"skipped"}}}function V4e(e){const t={};for(const[n,i]of Object.entries(e.answers))t[n]=U4e(i);return{answers:t,method:e.method,note:e.note}}function KA(e,t){if(typeof e.run_in_background!="boolean")throw new Error(`task wire missing required run_in_background (id ${e.id})`);return{id:e.id,agentId:e.agent_id??t,sessionId:e.session_id,kind:e.kind,description:e.description,status:e.status,command:e.command,createdAt:e.created_at,startedAt:e.started_at,completedAt:e.completed_at,outputPreview:e.output_preview,outputBytes:e.output_bytes,subagentPhase:e.subagent_phase,subagentType:e.subagent_type,model:e.model,thinkingEffort:e.thinking_effort,parentToolCallId:e.parent_tool_call_id,suspendedReason:e.suspended_reason,swarmIndex:e.swarm_index,runInBackground:e.run_in_background}}function ZF(e){return{path:e.path,name:e.name,kind:e.kind,size:e.size,modifiedAt:e.modified_at,etag:e.etag,mime:e.mime,languageId:e.language_id,isBinary:e.is_binary,isSymlinkTo:e.is_symlink_to,gitStatus:e.git_status,childCount:e.child_count}}function Fd(e,t){const n=e[t];return typeof n=="string"?n:void 0}function d1(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Sa(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function Zq(e){if(!e||typeof e!="object")return null;const t=e,n=Fd(t,"status");if(n!=="active"&&n!=="paused"&&n!=="blocked"&&n!=="complete")return null;const i=t.budget,o=i&&typeof i=="object"?i:{};return{goalId:Fd(t,"goalId")??Fd(t,"goal_id")??"goal",objective:Fd(t,"objective")??"",completionCriterion:Fd(t,"completionCriterion")??Fd(t,"completion_criterion"),status:n,turnsUsed:d1(t,"turnsUsed")??d1(t,"turns_used")??0,tokensUsed:d1(t,"tokensUsed")??d1(t,"tokens_used")??0,wallClockMs:d1(t,"wallClockMs")??d1(t,"wall_clock_ms")??0,terminalReason:Fd(t,"terminalReason")??Fd(t,"terminal_reason"),budget:{tokenBudget:Sa(o,"tokenBudget")??Sa(o,"token_budget"),remainingTokens:Sa(o,"remainingTokens")??Sa(o,"remaining_tokens"),turnBudget:Sa(o,"turnBudget")??Sa(o,"turn_budget"),remainingTurns:Sa(o,"remainingTurns")??Sa(o,"remaining_turns"),wallClockBudgetMs:Sa(o,"wallClockBudgetMs")??Sa(o,"wall_clock_budget_ms"),remainingWallClockMs:Sa(o,"remainingWallClockMs")??Sa(o,"remaining_wall_clock_ms"),overBudget:o.overBudget===!0||o.over_budget===!0}}}function K4e(e){const t=e;switch(e.type){case"event.session.created":return{type:"sessionCreated",session:Wu(t.payload.session)};case"event.session.updated":return{type:"sessionUpdated",session:Wu(t.payload.session),changedFields:t.payload.changed_fields};case"event.session.deleted":return{type:"sessionDeleted",sessionId:t.session_id};case"event.session.archived":{const n=t.payload?.sessionId??t.payload?.session_id;if(typeof n!="string"||n.length===0)return{type:"unknown",raw:{_noop:!0,_wireType:t.type}};const i=t.payload?.workspace_id;return{type:"sessionArchived",sessionId:n,workspaceId:typeof i=="string"&&i.length>0?i:void 0}}case"event.workspace.created":return{type:"workspaceCreated",workspace:Y0(t.payload.workspace)};case"event.workspace.updated":return{type:"workspaceUpdated",workspace:Y0(t.payload.workspace)};case"event.workspace.deleted":return{type:"workspaceDeleted",workspaceId:t.payload.workspace_id,root:t.payload.root};case"event.session.work_changed":return{type:"sessionWorkChanged",sessionId:t.session_id,busy:t.payload.busy,mainTurnActive:t.payload.main_turn_active,pendingInteraction:t.payload.pending_interaction,lastTurnReason:t.payload.last_turn_reason};case"event.session.status_changed":return{type:"sessionWorkChanged",sessionId:t.session_id,busy:t.payload.status!=="idle"&&t.payload.status!=="aborted",mainTurnActive:t.payload.status!=="idle"&&t.payload.status!=="aborted",pendingInteraction:t.payload.status==="awaiting_approval"?"approval":t.payload.status==="awaiting_question"?"question":"none",lastTurnReason:t.payload.status==="aborted"?"cancelled":void 0};case"event.session.usage_updated":return{type:"sessionUsageUpdated",sessionId:t.session_id,usage:Uq(t.payload.usage)};case"event.session.history_compacted":return{type:"historyCompacted",sessionId:t.session_id,beforeSeq:t.payload.before_seq,reason:t.payload.reason,summaryMessageId:t.payload.summary_message_id};case"event.goal.updated":{const n=Zq(t.payload.snapshot??null);return{type:"goalUpdated",sessionId:t.session_id,goal:n?.status==="complete"?null:n}}case"event.message.created":return{type:"messageCreated",message:Vq(t.payload.message)};case"event.message.updated":return{type:"messageUpdated",sessionId:t.session_id,messageId:t.payload.message_id,content:t.payload.content.map(Q4),status:t.payload.status};case"event.assistant.delta":return{type:"assistantDelta",sessionId:t.session_id,messageId:t.payload.message_id,contentIndex:t.payload.content_index,delta:t.payload.delta};case"event.assistant.tool_use_started":case"event.assistant.tool_use_delta":case"event.assistant.tool_use_completed":case"event.assistant.completed":case"event.tool.started":return{type:"unknown",raw:{_noop:!0,_wireType:t.type}};case"event.tool.output":return{type:"toolOutput",sessionId:t.session_id,toolCallId:t.payload.tool_call_id,outputChunk:t.payload.chunk,stream:t.payload.stream};case"event.tool.progress":return typeof t.payload.message=="string"&&t.payload.message.length>0?{type:"toolOutput",sessionId:t.session_id,toolCallId:t.payload.tool_call_id,outputChunk:t.payload.message,stream:"stdout"}:{type:"unknown",raw:{_noop:!0,_wireType:t.type}};case"event.tool.completed":return{type:"unknown",raw:{_noop:!0,_wireType:t.type}};case"event.approval.requested":return{type:"approvalRequested",sessionId:t.session_id,approval:j4e(t.payload)};case"event.approval.resolved":return{type:"approvalResolved",sessionId:t.session_id,approvalId:t.payload.approval_id,decision:t.payload.decision,resolvedAt:t.payload.resolved_at,feedback:t.payload.feedback,selectedLabel:t.payload.selected_label};case"event.approval.expired":return{type:"approvalExpired",sessionId:t.session_id,approvalId:t.payload.approval_id};case"event.question.requested":return{type:"questionRequested",sessionId:t.session_id,question:q4e(t.payload)};case"event.question.answered":return{type:"questionAnswered",sessionId:t.session_id,questionId:t.payload.question_id,resolvedAt:t.payload.resolved_at};case"event.question.dismissed":return{type:"questionDismissed",sessionId:t.session_id,questionId:t.payload.question_id,dismissedAt:t.payload.dismissed_at};case"event.task.created":return{type:"taskCreated",sessionId:t.session_id,task:KA(t.payload.task)};case"event.task.progress":return{type:"taskProgress",sessionId:t.session_id,taskId:t.payload.task_id,outputChunk:t.payload.output_chunk,stream:t.payload.stream};case"event.task.completed":return{type:"taskCompleted",sessionId:t.session_id,taskId:t.payload.task_id,status:t.payload.status,outputPreview:t.payload.output_preview,outputBytes:t.payload.output_bytes};case"event.plugin.changed":return{type:"pluginsChanged"};case"event.capability.changed":return{type:"capabilityChanged",capabilityId:t.payload.capability_id,install:t.payload.install};case"event.config.changed":return{type:"configChanged",changedFields:t.payload.changed_fields,config:ZA(t.payload.config)};case"event.model_catalog.changed":return{type:"modelCatalogChanged",changed:t.payload.changed.map(n=>({providerId:n.provider_id,providerName:n.provider_name,added:n.added,removed:n.removed})),unchanged:t.payload.unchanged,failed:t.payload.failed};default:return{type:"unknown",raw:e}}}function Z4e(e){return{id:e.model,provider:e.provider,model:e.model,displayName:e.display_name,maxContextSize:e.max_context_size,capabilities:e.capabilities,supportEfforts:e.support_efforts,defaultEffort:e.default_effort}}function f1(e){return{id:e.id,type:e.type,baseUrl:e.base_url,defaultModel:e.default_model,hasApiKey:e.has_api_key,status:e.status,models:e.models}}function GF(e){return{id:e.id,name:e.name,wireType:e.wire_type,guessed:e.guessed,needsBaseUrl:e.needs_base_url,rejected:e.rejected,rejectReason:e.reject_reason,envKey:e.env_key,models:e.models.map(t=>({id:t.id,name:t.name,maxContextSize:t.max_context_size,capabilities:t.capabilities,reasoning:t.reasoning}))}}function ZA(e){const t={};for(const[n,i]of Object.entries(e.providers))t[n]={type:i.type,baseUrl:i.base_url,defaultModel:i.default_model,hasApiKey:i.has_api_key};return{providers:t,defaultProvider:e.default_provider,defaultModel:e.default_model,secondaryModel:e.secondary_model,models:e.models,thinking:e.thinking,planMode:e.plan_mode,yolo:e.yolo,defaultPermissionMode:e.default_permission_mode,defaultPlanMode:e.default_plan_mode,permission:e.permission,hooks:e.hooks,services:e.services,mergeAllAvailableSkills:e.merge_all_available_skills,extraSkillDirs:e.extra_skill_dirs,loopControl:e.loop_control,background:e.background,experimental:e.experimental,telemetry:e.telemetry,raw:e.raw}}function G4e(e){return e.session_id}function Q4e(e){return e.seq}function Y4e(e){const t=Number(e.slice(1));return Number.isFinite(t)?t:0}function QF(e){switch(e.kind){case"turn":return e.turnId;case"marker":return e.markerId;case"taskref":return e.refId}}const J4e={items:[],tasks:new Map,interactions:new Map,attachments:new Map,todos:new Map,prompts:new Map,meta:{},pendingInteractions:new Set,hasMoreOlder:!1};function X4e(e,t){switch(t.op){case"reset":return ewe(e,t);case"turn.upsert":return nwe(e,t.turn);case"step.upsert":return owe(e,t.turnId,t.step);case"frame.upsert":return rwe(e,t);case"append":return awe(e,t);case"marker.upsert":return JF(e,t.item,t.item.markerId,t.beforeTurn);case"taskref.upsert":return JF(e,t.item,t.item.refId,t.beforeTurn);case"task.upsert":return dwe(e,t.task);case"interaction.upsert":return fwe(e,t.interaction);case"attachment.upsert":return pwe(e,t.attachment);case"todo.upsert":return gwe(e,t.todo);case"prompt.upsert":return ywe(e,t.prompt);case"meta.merge":return wwe(e,t.meta);case"items.remove":return cwe(e,t.ids)}}function ewe(e,t){const n=new Set;for(const i of t.snapshot.interactions)i.state==="pending"&&n.add(i.interactionId);return{state:{items:t.snapshot.items,tasks:new Map(t.snapshot.tasks.map(i=>[i.taskId,i])),interactions:new Map(t.snapshot.interactions.map(i=>[i.interactionId,i])),attachments:new Map(t.snapshot.attachments.map(i=>[i.attachmentId,i])),todos:new Map(t.snapshot.todos.map(i=>[i.todoId,i])),prompts:new Map(t.snapshot.prompts.map(i=>[i.promptId,i])),meta:t.snapshot.meta,pendingInteractions:n,hasMoreOlder:t.snapshot.hasMoreOlder??!1},changed:!0}}function YF(e,t){return{...e,kind:"turn",steps:[...t]}}function Gq(e){return{kind:"turn",turnId:e,ordinal:Y4e(e),state:"running",origin:{kind:"other"},steps:[]}}function twe(e,t){const n=Number(e.slice(t.length+1))||0;return{kind:"step",stepId:e,turnId:t,ordinal:n,state:"running",frames:[]}}function Am(e,t){const n=e.items.find(i=>i.kind==="turn"&&i.turnId===t);return n?.kind==="turn"?n:void 0}function tS(e,t){const n=[...e];let i=n.length;for(let o=0;ot.ordinal){i=o;break}}return n.splice(i,0,t),n}function Y4(e,t,n){return e.map(i=>i.kind==="turn"&&i.turnId===t?n(i):i)}function nwe(e,t){const n=Am(e,t.turnId);return n?iwe(n,t)?{state:e,changed:!1}:{state:{...e,items:Y4(e.items,t.turnId,i=>YF(t,i.steps))},changed:!0}:{state:{...e,items:tS(e.items,YF(t,[]))},changed:!0}}function iwe(e,t){return e.ordinal===t.ordinal&&e.triggerPromptId===t.triggerPromptId&&e.state===t.state&&e.prompt===t.prompt&&e.attachmentIds===t.attachmentIds&&e.startedAt===t.startedAt&&e.endedAt===t.endedAt&&e.origin.kind===t.origin.kind&&e.origin.payload===t.origin.payload&&e.usage===t.usage&&e.durationMs===t.durationMs&&e.error===t.error}function owe(e,t,n){const i=Am(e,t)??Gq(t),o=i.steps.findIndex(u=>u.stepId===n.stepId);let s,r=!0;if(o>=0){const u=i.steps[o];u&&swe(u,n)?(r=!1,s=i.steps):s=i.steps.map(c=>c.stepId===n.stepId?{...n,kind:"step",frames:c.frames}:c)}else s=[...i.steps,{...n,kind:"step",frames:[]}].toSorted((u,c)=>u.ordinal-c.ordinal);if(!r)return{state:e,changed:!1};const l={...i,steps:[...s]},a=Am(e,t)?Y4(e.items,t,()=>l):tS(e.items,l);return{state:{...e,items:a},changed:!0}}function swe(e,t){return e.ordinal===t.ordinal&&e.state===t.state&&e.startedAt===t.startedAt&&e.endedAt===t.endedAt&&e.usage===t.usage&&e.finishReason===t.finishReason&&e.timing===t.timing&&e.retry===t.retry&&e.endReason===t.endReason&&e.endMessage===t.endMessage}function rwe(e,t){const n=Am(e,t.turnId)??Gq(t.turnId),i=n.steps.find(c=>c.stepId===t.stepId)??twe(t.stepId,t.turnId),o=i.frames.findIndex(c=>c.frameId===t.frame.frameId);let s;if(o>=0){const c=i.frames[o];if(c!==void 0&&lwe(c,t.frame))return{state:e,changed:!1};s=i.frames.map(d=>d.frameId===t.frame.frameId?t.frame:d)}else s=[...i.frames,t.frame];const r={...i,frames:[...s]},l=n.steps.some(c=>c.stepId===t.stepId)?n.steps.map(c=>c.stepId===t.stepId?r:c):[...n.steps,r].toSorted((c,d)=>c.ordinal-d.ordinal),a={...n,steps:l},u=Am(e,t.turnId)?Y4(e.items,t.turnId,()=>a):tS(e.items,a);return{state:{...e,items:u},changed:!0}}function lwe(e,t){return e.kind!==t.kind?!1:e.kind==="text"&&t.kind==="text"?e.text===t.text&&e.role===t.role&&e.attachmentIds===t.attachmentIds&&e.taskId===t.taskId:e.kind==="thinking"&&t.kind==="thinking"?e.text===t.text:e.kind==="tool"&&t.kind==="tool"?e.state===t.state&&e.toolCallId===t.toolCallId&&e.name===t.name&&e.view===t.view&&e.input===t.input&&e.output===t.output&&e.display===t.display&&e.error===t.error&&e.inputText===t.inputText&&e.progress===t.progress&&e.taskId===t.taskId&&e.approvalId===t.approvalId&&e.todoId===t.todoId&&e.agentRefs===t.agentRefs:e.kind==="notice"&&t.kind==="notice"?e.message===t.message&&e.level===t.level&&e.detail===t.detail:!1}function awe(e,t){if(t.target.type==="task")return uwe(e,t);const{turnId:n,stepId:i,frameId:o}=t.target,s=Am(e,n),r=s?.steps.find(f=>f.stepId===i),l=r?.frames.find(f=>f.frameId===o);if(!s||!r||!l||l.kind!=="text"&&l.kind!=="thinking")return{state:e,changed:!1,gap:{expected:0,got:t.offset}};const a=Qq(l.text,t.offset,t.text);if(a.gap)return{state:e,changed:!1,gap:a.gap};if(!a.changed)return{state:e,changed:!1};const u={...l,text:a.text},c={...r,frames:r.frames.map(f=>f.frameId===o?u:f)},d={...s,steps:s.steps.map(f=>f.stepId===i?c:f)};return{state:{...e,items:Y4(e.items,n,()=>d)},changed:!0}}function uwe(e,t){if(t.target.type!=="task")throw new Error("unreachable");const n=t.target.taskId,i=e.tasks.get(n),o=i?.outputTail??"",s=Qq(o,t.offset,t.text);if(s.gap)return{state:e,changed:!1,gap:s.gap};if(!s.changed)return{state:e,changed:!1};const r=i?{...i,outputTail:s.text}:{taskId:n,kind:"other",state:"running",detached:!1,outputTail:s.text},l=new Map(e.tasks);return l.set(n,r),{state:{...e,tasks:l},changed:!0}}function Qq(e,t,n){if(t>e.length)return{text:e,changed:!1,gap:{expected:e.length,got:t}};if(e.slice(t,t+n.length)===n)return{text:e,changed:!1};const i=e.length-t;return e.slice(t)!==n.slice(0,i)?{text:e,changed:!1,gap:{expected:e.length,got:t}}:(i>0?n.slice(i):n).length===0?{text:e,changed:!1}:{text:e.slice(0,t)+n,changed:!0}}function JF(e,t,n,i){if(e.items.some(s=>GA(s)===n)){let s=!1;const r=e.items.map(l=>GA(l)!==n||l===t?l:(s=!0,t));return s?{state:{...e,items:r},changed:!0}:{state:e,changed:!1}}if(i!==void 0){const s=[...e.items];let r=s.length;for(let l=0;l=i){r=l;break}}return s.splice(r,0,t),{state:{...e,items:s},changed:!0}}return{state:{...e,items:[...e.items,t]},changed:!0}}function GA(e){switch(e.kind){case"turn":return e.turnId;case"marker":return e.markerId;case"taskref":return e.refId}}function cwe(e,t){const n=new Set(t),i=e.items.filter(l=>l.kind==="turn"&&n.has(l.turnId)),o=e.items.filter(l=>!n.has(GA(l)));if(o.length===e.items.length)return{state:e,changed:!1};let s=e.pendingInteractions,r=e.interactions;if(i.length>0){const l=new Set,a=new Set(s),u=new Set;for(const c of i)for(const d of c.steps)for(const f of d.frames)f.kind==="tool"&&l.add(f.toolCallId);for(const c of r.values())c.toolCallId!==void 0&&l.has(c.toolCallId)&&(u.add(c.interactionId),a.delete(c.interactionId));if(u.size>0){const c=new Map(r);for(const d of u)c.delete(d);r=c}s=a}return{state:{...e,items:o,interactions:r,pendingInteractions:s},changed:!0}}function dwe(e,t){const n=e.tasks.get(t.taskId);if(n&&bwe(n,t))return{state:e,changed:!1};const i=new Map(e.tasks);return i.set(t.taskId,t),{state:{...e,tasks:i},changed:!0}}function fwe(e,t){const n=e.interactions.get(t.interactionId);if(n&&hwe(n,t))return{state:e,changed:!1};const i=new Map(e.interactions);i.set(t.interactionId,t);let o=e.pendingInteractions;if(t.state==="pending"){if(!o.has(t.interactionId)){const s=new Set(o);s.add(t.interactionId),o=s}}else if(o.has(t.interactionId)){const s=new Set(o);s.delete(t.interactionId),o=s}return{state:{...e,interactions:i,pendingInteractions:o},changed:!0}}function hwe(e,t){return e.interactionKind===t.interactionKind&&e.toolCallId===t.toolCallId&&e.state===t.state&&e.request===t.request&&e.response===t.response}function pwe(e,t){const n=e.attachments.get(t.attachmentId);if(n&&mwe(n,t))return{state:e,changed:!1};const i=new Map(e.attachments);return i.set(t.attachmentId,t),{state:{...e,attachments:i},changed:!0}}function mwe(e,t){return e.mediaType===t.mediaType&&e.name===t.name&&e.size===t.size&&e.source===t.source&&e.placeholder===t.placeholder}function gwe(e,t){const n=e.todos.get(t.todoId);if(n&&vwe(n,t))return{state:e,changed:!1};const i=new Map(e.todos);return i.set(t.todoId,t),{state:{...e,todos:i},changed:!0}}function vwe(e,t){return e.items===t.items&&e.updatedAt===t.updatedAt}function ywe(e,t){const n=e.prompts.get(t.promptId);if(n&&kwe(n,t))return{state:e,changed:!1};const i=new Map(e.prompts);return i.set(t.promptId,t),{state:{...e,prompts:i},changed:!0}}function kwe(e,t){return e.status===t.status&&e.userMessageId===t.userMessageId&&e.content===t.content&&e.createdAt===t.createdAt&&e.finishedAt===t.finishedAt&&e.steeredAt===t.steeredAt}function bwe(e,t){return e.kind===t.kind&&e.state===t.state&&e.detached===t.detached&&e.description===t.description&&e.agentId===t.agentId&&e.outputTail===t.outputTail&&e.startedAt===t.startedAt&&e.endedAt===t.endedAt&&e.resultSummary===t.resultSummary&&e.error===t.error&&e.stateReason===t.stateReason&&e.usage===t.usage}function wwe(e,t){const n=t.modes!==void 0?{plan:t.modes.plan===null?void 0:t.modes.plan??e.meta.modes?.plan,swarm:t.modes.swarm===null?void 0:t.modes.swarm??e.meta.modes?.swarm,tower:t.modes.tower===null?void 0:t.modes.tower??e.meta.modes?.tower}:e.meta.modes,i=t.agent!==void 0?{...e.meta.agent,...t.agent}:e.meta.agent,o={goal:t.goal===null?void 0:t.goal??e.meta.goal,activity:t.activity??e.meta.activity,modes:n!==void 0&&n.plan===void 0&&n.swarm===void 0&&n.tower===void 0?void 0:n,agent:i};return o.goal===e.meta.goal&&o.activity===e.meta.activity&&o.modes===e.meta.modes&&o.agent===e.meta.agent?{state:e,changed:!1}:{state:{...e,meta:o},changed:!0}}class Cwe{constructor(t){this.agentId=t}#e=J4e;#t=new Set;receive(t){return this.apply(t)}apply(t){const n=[];let i,o=this.#e;for(const s of t){const r=X4e(o,s);if(r.gap){i={target:s.target,...r.gap};continue}r.changed&&(o=r.state,n.push(s))}if(this.#e=o,n.length>0){const s={agentId:this.agentId,ops:n};for(const r of this.#t)r(s)}return{accepted:n,gap:i}}onChange(t){return this.#t.add(t),{dispose:()=>void this.#t.delete(t)}}getItems(){return this.#e.items}getTurn(t){const n=this.#e.items.find(i=>i.kind==="turn"&&i.turnId===t);return n?.kind==="turn"?n:void 0}getTasks(){return this.#e.tasks}getTask(t){return this.#e.tasks.get(t)}getInteractions(){return this.#e.interactions}getInteraction(t){return this.#e.interactions.get(t)}getAttachments(){return this.#e.attachments}getAttachment(t){return this.#e.attachments.get(t)}getTodos(){return this.#e.todos}getTodo(t){return this.#e.todos.get(t)}getPrompts(){return this.#e.prompts}getPrompt(t){return this.#e.prompts.get(t)}getMeta(){return this.#e.meta}listPendingInteractions(){return[...this.#e.pendingInteractions]}get hasMoreOlder(){return this.#e.hasMoreOlder}snapshot(t){let n=this.#e.items,i=this.#e.hasMoreOlder;if(t!==void 0){const o=n.reduce((s,r)=>r.kind==="turn"?s+1:s,0);if(o>t.tailTurns){const s=o-t.tailTurns,r=[];let l=0;for(const a of n)if(a.kind==="turn"){if(l+=1,l<=s)continue;r.push(a)}else l>s&&r.push(a);n=r,i=!0}}return{items:n,tasks:[...this.#e.tasks.values()],interactions:[...this.#e.interactions.values()],attachments:[...this.#e.attachments.values()],todos:[...this.#e.todos.values()],prompts:[...this.#e.prompts.values()],meta:this.#e.meta,hasMoreOlder:i}}}function Ft(e,t,n){function i(l,a){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:a,constr:r,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,a);const u=r.prototype,c=Object.keys(u);for(let d=0;dn?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(r,"name",{value:e}),r}class cm extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Yq extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Jq={};function Ef(e){return Jq}function Xq(e){const t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,o])=>t.indexOf(+i)===-1).map(([i,o])=>o)}function QA(e,t){return typeof t=="bigint"?t.toString():t}function J4(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nS(e){return e==null}function iS(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Awe(e,t){const n=(e.toString().split(".")[1]||"").length,i=t.toString();let o=(i.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(i)){const a=i.match(/\d?e-(\d?)/);a?.[1]&&(o=Number.parseInt(a[1]))}const s=n>o?n:o,r=Number.parseInt(e.toFixed(s).replace(".","")),l=Number.parseInt(t.toFixed(s).replace(".",""));return r%l/10**s}const XF=Symbol("evaluating");function Di(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==XF)return i===void 0&&(i=XF,i=n()),i},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Fp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Uf(...e){const t={};for(const n of e){const i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function eD(e){return JSON.stringify(e)}function xwe(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const eU="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Bv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Swe=J4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function xm(e){if(Bv(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Bv(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function tU(e){return xm(e)?{...e}:Array.isArray(e)?[...e]:e}const _we=new Set(["string","number","symbol"]);function Sm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vf(e,t,n){const i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function _n(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Iwe(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Mwe={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Twe(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=Uf(e._zod.def,{get shape(){const r={};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(r[l]=n.shape[l])}return Fp(this,"shape",r),r},checks:[]});return Vf(e,s)}function Ewe(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=Uf(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&delete r[l]}return Fp(this,"shape",r),r},checks:[]});return Vf(e,s)}function Lwe(e,t){if(!xm(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const s=e._zod.def.shape;for(const r in t)if(Object.getOwnPropertyDescriptor(s,r)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=Uf(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return Fp(this,"shape",s),s}});return Vf(e,o)}function Nwe(e,t){if(!xm(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Uf(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Fp(this,"shape",i),i}});return Vf(e,n)}function Fwe(e,t){const n=Uf(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t._zod.def.shape};return Fp(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return Vf(e,n)}function Dwe(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const r=Uf(t._zod.def,{get shape(){const l=t._zod.def.shape,a={...l};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(a[u]=e?new e({type:"optional",innerType:l[u]}):l[u])}else for(const u in l)a[u]=e?new e({type:"optional",innerType:l[u]}):l[u];return Fp(this,"shape",a),a},checks:[]});return Vf(t,r)}function Rwe(e,t,n){const i=Uf(t._zod.def,{get shape(){const o=t._zod.def.shape,s={...o};if(n)for(const r in n){if(!(r in s))throw new Error(`Unrecognized key: "${r}"`);n[r]&&(s[r]=new e({type:"nonoptional",innerType:o[r]}))}else for(const r in o)s[r]=new e({type:"nonoptional",innerType:o[r]});return Fp(this,"shape",s),s}});return Vf(t,i)}function B1(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function qy(e){return typeof e=="string"?e:e?.message}function Lf(e,t,n){const i={...e,path:e.path??[]};if(!e.message){const o=qy(e.inst?._zod.def?.error?.(e))??qy(t?.error?.(e))??qy(n.customError?.(e))??qy(n.localeError?.(e))??"Invalid input";i.message=o}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function oS(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function $v(...e){const[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}const nU=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,QA,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},iU=Ft("$ZodError",nU),oU=Ft("$ZodError",nU,{Parent:Error});function Owe(e,t=n=>n.message){const n={},i=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):i.push(t(o));return{formErrors:i,fieldErrors:n}}function Pwe(e,t=n=>n.message){const n={_errors:[]},i=o=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(r=>i({issues:r}));else if(s.code==="invalid_key")i({issues:s.issues});else if(s.code==="invalid_element")i({issues:s.issues});else if(s.path.length===0)n._errors.push(t(s));else{let r=n,l=0;for(;l(t,n,i,o)=>{const s=i?Object.assign(i,{async:!1}):{async:!1},r=t._zod.run({value:n,issues:[]},s);if(r instanceof Promise)throw new cm;if(r.issues.length){const l=new(o?.Err??e)(r.issues.map(a=>Lf(a,s,Ef())));throw eU(l,o?.callee),l}return r.value},rS=e=>async(t,n,i,o)=>{const s=i?Object.assign(i,{async:!0}):{async:!0};let r=t._zod.run({value:n,issues:[]},s);if(r instanceof Promise&&(r=await r),r.issues.length){const l=new(o?.Err??e)(r.issues.map(a=>Lf(a,s,Ef())));throw eU(l,o?.callee),l}return r.value},X4=e=>(t,n,i)=>{const o=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new cm;return s.issues.length?{success:!1,error:new(e??iU)(s.issues.map(r=>Lf(r,o,Ef())))}:{success:!0,data:s.value}},Bwe=X4(oU),ew=e=>async(t,n,i)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(r=>Lf(r,o,Ef())))}:{success:!0,data:s.value}},$we=ew(oU),zwe=e=>(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return sS(e)(t,n,o)},jwe=e=>(t,n,i)=>sS(e)(t,n,i),Hwe=e=>async(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return rS(e)(t,n,o)},Wwe=e=>async(t,n,i)=>rS(e)(t,n,i),qwe=e=>(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return X4(e)(t,n,o)},Uwe=e=>(t,n,i)=>X4(e)(t,n,i),Vwe=e=>async(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return ew(e)(t,n,o)},Kwe=e=>async(t,n,i)=>ew(e)(t,n,i),Zwe=/^[cC][^\s-]{8,}$/,Gwe=/^[0-9a-z]+$/,Qwe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ywe=/^[0-9a-vA-V]{20}$/,Jwe=/^[A-Za-z0-9]{27}$/,Xwe=/^[a-zA-Z0-9_-]{21}$/,e3e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,t3e=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,tD=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,n3e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,i3e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function o3e(){return new RegExp(i3e,"u")}const s3e=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,r3e=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,l3e=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,a3e=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,u3e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,sU=/^[A-Za-z0-9_-]*$/,c3e=/^\+[1-9]\d{6,14}$/,rU="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",d3e=new RegExp(`^${rU}$`);function lU(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function f3e(e){return new RegExp(`^${lU(e)}$`)}function h3e(e){const t=lU({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${rU}T(?:${i})$`)}const p3e=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},m3e=/^-?\d+$/,aU=/^-?\d+(?:\.\d+)?$/,g3e=/^(?:true|false)$/i,v3e=/^[^A-Z]*$/,y3e=/^[^a-z]*$/,Pl=Ft("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),uU={number:"number",bigint:"bigint",object:"date"},cU=Ft("$ZodCheckLessThan",(e,t)=>{Pl.init(e,t);const n=uU[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?i.value<=t.value:i.value{Pl.init(e,t);const n=uU[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),k3e=Ft("$ZodCheckMultipleOf",(e,t)=>{Pl.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Awe(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),b3e=Ft("$ZodCheckNumberFormat",(e,t)=>{Pl.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[o,s]=Mwe[t.format];e._zod.onattach.push(r=>{const l=r._zod.bag;l.format=t.format,l.minimum=o,l.maximum=s,n&&(l.pattern=m3e)}),e._zod.check=r=>{const l=r.value;if(n){if(!Number.isInteger(l)){r.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?r.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort}):r.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}ls&&r.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),w3e=Ft("$ZodCheckMaxLength",(e,t)=>{var n;Pl.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!nS(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const o=i.value;if(o.length<=t.maximum)return;const r=oS(o);i.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),C3e=Ft("$ZodCheckMinLength",(e,t)=>{var n;Pl.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!nS(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const o=i.value;if(o.length>=t.minimum)return;const r=oS(o);i.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),A3e=Ft("$ZodCheckLengthEquals",(e,t)=>{var n;Pl.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!nS(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=i=>{const o=i.value,s=o.length;if(s===t.length)return;const r=oS(o),l=s>t.length;i.issues.push({origin:r,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),tw=Ft("$ZodCheckStringFormat",(e,t)=>{var n,i;Pl.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),x3e=Ft("$ZodCheckRegex",(e,t)=>{tw.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),S3e=Ft("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=v3e),tw.init(e,t)}),_3e=Ft("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=y3e),tw.init(e,t)}),I3e=Ft("$ZodCheckIncludes",(e,t)=>{Pl.init(e,t);const n=Sm(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(i)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),M3e=Ft("$ZodCheckStartsWith",(e,t)=>{Pl.init(e,t);const n=new RegExp(`^${Sm(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),T3e=Ft("$ZodCheckEndsWith",(e,t)=>{Pl.init(e,t);const n=new RegExp(`.*${Sm(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}}),E3e=Ft("$ZodCheckOverwrite",(e,t)=>{Pl.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class L3e{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const i=t.split(` +`).filter(r=>r),o=Math.min(...i.map(r=>r.length-r.trimStart().length)),s=i.map(r=>r.slice(o)).map(r=>" ".repeat(this.indent*2)+r);for(const r of s)this.content.push(r)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(` +`))}}const N3e={major:4,minor:3,patch:6},Co=Ft("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=N3e;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const o of i)for(const s of o._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(r,l,a)=>{let u=B1(r),c;for(const d of l){if(d._zod.def.when){if(!d._zod.def.when(r))continue}else if(u)continue;const f=r.issues.length,h=d._zod.check(r);if(h instanceof Promise&&a?.async===!1)throw new cm;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,r.issues.length!==f&&(u||(u=B1(r,f)))});else{if(r.issues.length===f)continue;u||(u=B1(r,f))}}return c?c.then(()=>r):r},s=(r,l,a)=>{if(B1(r))return r.aborted=!0,r;const u=o(l,i,a);if(u instanceof Promise){if(a.async===!1)throw new cm;return u.then(c=>e._zod.parse(c,a))}return e._zod.parse(u,a)};e._zod.run=(r,l)=>{if(l.skipChecks)return e._zod.parse(r,l);if(l.direction==="backward"){const u=e._zod.parse({value:r.value,issues:[]},{...l,skipChecks:!0});return u instanceof Promise?u.then(c=>s(c,r,l)):s(u,r,l)}const a=e._zod.parse(r,l);if(a instanceof Promise){if(l.async===!1)throw new cm;return a.then(u=>o(u,i,l))}return o(a,i,l)}}Di(e,"~standard",()=>({validate:o=>{try{const s=Bwe(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return $we(e,o).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}))}),lS=Ft("$ZodString",(e,t)=>{Co.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??p3e(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),go=Ft("$ZodStringFormat",(e,t)=>{tw.init(e,t),lS.init(e,t)}),F3e=Ft("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=t3e),go.init(e,t)}),D3e=Ft("$ZodUUID",(e,t)=>{if(t.version){const i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=tD(i))}else t.pattern??(t.pattern=tD());go.init(e,t)}),R3e=Ft("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=n3e),go.init(e,t)}),O3e=Ft("$ZodURL",(e,t)=>{go.init(e,t),e._zod.check=n=>{try{const i=n.value.trim(),o=new URL(i);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),P3e=Ft("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=o3e()),go.init(e,t)}),B3e=Ft("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Xwe),go.init(e,t)}),$3e=Ft("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Zwe),go.init(e,t)}),z3e=Ft("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Gwe),go.init(e,t)}),j3e=Ft("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qwe),go.init(e,t)}),H3e=Ft("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ywe),go.init(e,t)}),W3e=Ft("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jwe),go.init(e,t)}),q3e=Ft("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=h3e(t)),go.init(e,t)}),U3e=Ft("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=d3e),go.init(e,t)}),V3e=Ft("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=f3e(t)),go.init(e,t)}),K3e=Ft("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=e3e),go.init(e,t)}),Z3e=Ft("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=s3e),go.init(e,t),e._zod.bag.format="ipv4"}),G3e=Ft("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=r3e),go.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Q3e=Ft("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=l3e),go.init(e,t)}),Y3e=Ft("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=a3e),go.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(i.length!==2)throw new Error;const[o,s]=i;if(!s)throw new Error;const r=Number(s);if(`${r}`!==s)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function fU(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const J3e=Ft("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=u3e),go.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{fU(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function X3e(e){if(!sU.test(e))return!1;const t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return fU(n)}const e8e=Ft("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=sU),go.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{X3e(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),t8e=Ft("$ZodE164",(e,t)=>{t.pattern??(t.pattern=c3e),go.init(e,t)});function n8e(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[i]=n;if(!i)return!1;const o=JSON.parse(atob(i));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const i8e=Ft("$ZodJWT",(e,t)=>{go.init(e,t),e._zod.check=n=>{n8e(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),hU=Ft("$ZodNumber",(e,t)=>{Co.init(e,t),e._zod.pattern=e._zod.bag.pattern??aU,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),o8e=Ft("$ZodNumberFormat",(e,t)=>{b3e.init(e,t),hU.init(e,t)}),s8e=Ft("$ZodBoolean",(e,t)=>{Co.init(e,t),e._zod.pattern=g3e,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),r8e=Ft("$ZodUnknown",(e,t)=>{Co.init(e,t),e._zod.parse=n=>n}),l8e=Ft("$ZodNever",(e,t)=>{Co.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function nD(e,t,n){e.issues.length&&t.issues.push(...$1(n,e.issues)),t.value[n]=e.value}const a8e=Ft("$ZodArray",(e,t)=>{Co.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let r=0;rnD(u,n,r))):nD(a,n,r)}return s.length?Promise.all(s).then(()=>n):n}});function Ab(e,t,n,i,o){if(e.issues.length){if(o&&!(n in i))return;t.issues.push(...$1(n,e.issues))}e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function pU(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=Iwe(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function mU(e,t,n,i,o,s){const r=[],l=o.keySet,a=o.catchall._zod,u=a.def.type,c=a.optout==="optional";for(const d in t){if(l.has(d))continue;if(u==="never"){r.push(d);continue}const f=a.run({value:t[d],issues:[]},i);f instanceof Promise?e.push(f.then(h=>Ab(h,n,d,t,c))):Ab(f,n,d,t,c)}return r.length&&n.issues.push({code:"unrecognized_keys",keys:r,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}const u8e=Ft("$ZodObject",(e,t)=>{if(Co.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const a={...l};return Object.defineProperty(t,"shape",{value:a}),a}})}const i=J4(()=>pU(t));Di(e._zod,"propValues",()=>{const l=t.shape,a={};for(const u in l){const c=l[u]._zod;if(c.values){a[u]??(a[u]=new Set);for(const d of c.values)a[u].add(d)}}return a});const o=Bv,s=t.catchall;let r;e._zod.parse=(l,a)=>{r??(r=i.value);const u=l.value;if(!o(u))return l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l;l.value={};const c=[],d=r.shape;for(const f of r.keys){const h=d[f],m=h._zod.optout==="optional",g=h._zod.run({value:u[f],issues:[]},a);g instanceof Promise?c.push(g.then(y=>Ab(y,l,f,u,m))):Ab(g,l,f,u,m)}return s?mU(c,u,l,a,i.value,e):c.length?Promise.all(c).then(()=>l):l}}),c8e=Ft("$ZodObjectJIT",(e,t)=>{u8e.init(e,t);const n=e._zod.parse,i=J4(()=>pU(t)),o=f=>{const h=new L3e(["shape","payload","ctx"]),m=i.value,g=C=>{const w=eD(C);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};h.write("const input = payload.value;");const y=Object.create(null);let k=0;for(const C of m.keys)y[C]=`key_${k++}`;h.write("const newResult = {};");for(const C of m.keys){const w=y[C],M=eD(C),E=f[C]?._zod?.optout==="optional";h.write(`const ${w} = ${g(C)};`),E?h.write(` + if (${w}.issues.length) { + if (${M} in input) { + payload.issues = payload.issues.concat(${w}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${M}, ...iss.path] : [${M}] + }))); + } + } + + if (${w}.value === undefined) { + if (${M} in input) { + newResult[${M}] = undefined; + } + } else { + newResult[${M}] = ${w}.value; + } + + `):h.write(` + if (${w}.issues.length) { + payload.issues = payload.issues.concat(${w}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${M}, ...iss.path] : [${M}] + }))); + } + + if (${w}.value === undefined) { + if (${M} in input) { + newResult[${M}] = undefined; + } + } else { + newResult[${M}] = ${w}.value; + } + + `)}h.write("payload.value = newResult;"),h.write("return payload;");const v=h.compile();return(C,w)=>v(f,C,w)};let s;const r=Bv,l=!Jq.jitless,u=l&&Swe.value,c=t.catchall;let d;e._zod.parse=(f,h)=>{d??(d=i.value);const m=f.value;return r(m)?l&&u&&h?.async===!1&&h.jitless!==!0?(s||(s=o(t.shape)),f=s(f,h),c?mU([],m,f,h,d,e):f):n(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f)}});function iD(e,t,n,i){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const o=e.filter(s=>!B1(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(r=>Lf(r,i,Ef())))}),t)}const gU=Ft("$ZodUnion",(e,t)=>{Co.init(e,t),Di(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Di(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Di(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Di(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>iS(s.source)).join("|")})$`)}});const n=t.options.length===1,i=t.options[0]._zod.run;e._zod.parse=(o,s)=>{if(n)return i(o,s);let r=!1;const l=[];for(const a of t.options){const u=a._zod.run({value:o.value,issues:[]},s);if(u instanceof Promise)l.push(u),r=!0;else{if(u.issues.length===0)return u;l.push(u)}}return r?Promise.all(l).then(a=>iD(a,o,e,s)):iD(l,o,e,s)}}),d8e=Ft("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,gU.init(e,t);const n=e._zod.parse;Di(e._zod,"propValues",()=>{const o={};for(const s of t.options){const r=s._zod.propValues;if(!r||Object.keys(r).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[l,a]of Object.entries(r)){o[l]||(o[l]=new Set);for(const u of a)o[l].add(u)}}return o});const i=J4(()=>{const o=t.options,s=new Map;for(const r of o){const l=r._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const a of l){if(s.has(a))throw new Error(`Duplicate discriminator value "${String(a)}"`);s.set(a,r)}}return s});e._zod.parse=(o,s)=>{const r=o.value;if(!Bv(r))return o.issues.push({code:"invalid_type",expected:"object",input:r,inst:e}),o;const l=i.value.get(r?.[t.discriminator]);return l?l._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:r,path:[t.discriminator],inst:e}),o)}}),f8e=Ft("$ZodIntersection",(e,t)=>{Co.init(e,t),e._zod.parse=(n,i)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},i),r=t.right._zod.run({value:o,issues:[]},i);return s instanceof Promise||r instanceof Promise?Promise.all([s,r]).then(([a,u])=>oD(n,a,u)):oD(n,s,r)}});function YA(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(xm(e)&&xm(t)){const n=Object.keys(t),i=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of i){const r=YA(e[s],t[s]);if(!r.valid)return{valid:!1,mergeErrorPath:[s,...r.mergeErrorPath]};o[s]=r.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;il.l&&l.r).map(([l])=>l);if(s.length&&o&&e.issues.push({...o,keys:s}),B1(e))return e;const r=YA(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const h8e=Ft("$ZodRecord",(e,t)=>{Co.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!xm(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[],r=t.keyType._zod.values;if(r){n.value={};const l=new Set;for(const u of r)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){l.add(typeof u=="number"?u.toString():u);const c=t.valueType._zod.run({value:o[u],issues:[]},i);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...$1(u,d.issues)),n.value[u]=d.value})):(c.issues.length&&n.issues.push(...$1(u,c.issues)),n.value[u]=c.value)}let a;for(const u in o)l.has(u)||(a=a??[],a.push(u));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.value={};for(const l of Reflect.ownKeys(o)){if(l==="__proto__")continue;let a=t.keyType._zod.run({value:l,issues:[]},i);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&aU.test(l)&&a.issues.length){const d=t.keyType._zod.run({value:Number(l),issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(a=d)}if(a.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(d=>Lf(d,i,Ef())),input:l,path:[l],inst:e});continue}const c=t.valueType._zod.run({value:o[l],issues:[]},i);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...$1(l,d.issues)),n.value[a.value]=d.value})):(c.issues.length&&n.issues.push(...$1(l,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),p8e=Ft("$ZodEnum",(e,t)=>{Co.init(e,t);const n=Xq(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(o=>_we.has(typeof o)).map(o=>typeof o=="string"?Sm(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{const r=o.value;return i.has(r)||o.issues.push({code:"invalid_value",values:n,input:r,inst:e}),o}}),m8e=Ft("$ZodLiteral",(e,t)=>{if(Co.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(i=>typeof i=="string"?Sm(i):i?Sm(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,o)=>{const s=i.value;return n.has(s)||i.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),i}}),g8e=Ft("$ZodTransform",(e,t)=>{Co.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Yq(e.constructor.name);const o=t.transform(n.value,n);if(i.async)return(o instanceof Promise?o:Promise.resolve(o)).then(r=>(n.value=r,n));if(o instanceof Promise)throw new cm;return n.value=o,n}});function sD(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const vU=Ft("$ZodOptional",(e,t)=>{Co.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Di(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Di(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${iS(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>sD(s,n.value)):sD(o,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,i)}}),v8e=Ft("$ZodExactOptional",(e,t)=>{vU.init(e,t),Di(e._zod,"values",()=>t.innerType._zod.values),Di(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),y8e=Ft("$ZodNullable",(e,t)=>{Co.init(e,t),Di(e._zod,"optin",()=>t.innerType._zod.optin),Di(e._zod,"optout",()=>t.innerType._zod.optout),Di(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${iS(n.source)}|null)$`):void 0}),Di(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>n.value===null?n:t.innerType._zod.run(n,i)}),k8e=Ft("$ZodDefault",(e,t)=>{Co.init(e,t),e._zod.optin="optional",Di(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>rD(s,t)):rD(o,t)}});function rD(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const b8e=Ft("$ZodPrefault",(e,t)=>{Co.init(e,t),e._zod.optin="optional",Di(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>(i.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,i))}),w8e=Ft("$ZodNonOptional",(e,t)=>{Co.init(e,t),Di(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>lD(s,e)):lD(o,e)}});function lD(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const C8e=Ft("$ZodCatch",(e,t)=>{Co.init(e,t),Di(e._zod,"optin",()=>t.innerType._zod.optin),Di(e._zod,"optout",()=>t.innerType._zod.optout),Di(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(r=>Lf(r,i,Ef()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Lf(s,i,Ef()))},input:n.value}),n.issues=[]),n)}}),A8e=Ft("$ZodPipe",(e,t)=>{Co.init(e,t),Di(e._zod,"values",()=>t.in._zod.values),Di(e._zod,"optin",()=>t.in._zod.optin),Di(e._zod,"optout",()=>t.out._zod.optout),Di(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){const s=t.out._zod.run(n,i);return s instanceof Promise?s.then(r=>Uy(r,t.in,i)):Uy(s,t.in,i)}const o=t.in._zod.run(n,i);return o instanceof Promise?o.then(s=>Uy(s,t.out,i)):Uy(o,t.out,i)}});function Uy(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const x8e=Ft("$ZodReadonly",(e,t)=>{Co.init(e,t),Di(e._zod,"propValues",()=>t.innerType._zod.propValues),Di(e._zod,"values",()=>t.innerType._zod.values),Di(e._zod,"optin",()=>t.innerType?._zod?.optin),Di(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(aD):aD(o)}});function aD(e){return e.value=Object.freeze(e.value),e}const S8e=Ft("$ZodCustom",(e,t)=>{Pl.init(e,t),Co.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=n=>{const i=n.value,o=t.fn(i);if(o instanceof Promise)return o.then(s=>uD(s,n,i,e));uD(o,n,i,e)}});function uD(e,t,n,i){if(!e){const o={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(o.params=i._zod.def.params),t.issues.push($v(o))}}var cD;class _8e{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const i=n[0];return this._map.set(t,i),i&&typeof i=="object"&&"id"in i&&this._idmap.set(i.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const i={...this.get(n)??{}};delete i.id;const o={...i,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function I8e(){return new _8e}(cD=globalThis).__zod_globalRegistry??(cD.__zod_globalRegistry=I8e());const h0=globalThis.__zod_globalRegistry;function M8e(e,t){return new e({type:"string",..._n(t)})}function T8e(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,..._n(t)})}function dD(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,..._n(t)})}function E8e(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,..._n(t)})}function L8e(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._n(t)})}function N8e(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._n(t)})}function F8e(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._n(t)})}function D8e(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,..._n(t)})}function R8e(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,..._n(t)})}function O8e(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,..._n(t)})}function P8e(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,..._n(t)})}function B8e(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,..._n(t)})}function $8e(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,..._n(t)})}function z8e(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,..._n(t)})}function j8e(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,..._n(t)})}function H8e(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,..._n(t)})}function W8e(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,..._n(t)})}function q8e(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._n(t)})}function U8e(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._n(t)})}function V8e(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,..._n(t)})}function K8e(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,..._n(t)})}function Z8e(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,..._n(t)})}function G8e(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,..._n(t)})}function Q8e(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._n(t)})}function Y8e(e,t){return new e({type:"string",format:"date",check:"string_format",..._n(t)})}function J8e(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,..._n(t)})}function X8e(e,t){return new e({type:"string",format:"duration",check:"string_format",..._n(t)})}function e5e(e,t){return new e({type:"number",checks:[],..._n(t)})}function t5e(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",..._n(t)})}function n5e(e,t){return new e({type:"boolean",..._n(t)})}function i5e(e){return new e({type:"unknown"})}function o5e(e,t){return new e({type:"never",..._n(t)})}function fD(e,t){return new cU({check:"less_than",..._n(t),value:e,inclusive:!1})}function L8(e,t){return new cU({check:"less_than",..._n(t),value:e,inclusive:!0})}function hD(e,t){return new dU({check:"greater_than",..._n(t),value:e,inclusive:!1})}function N8(e,t){return new dU({check:"greater_than",..._n(t),value:e,inclusive:!0})}function pD(e,t){return new k3e({check:"multiple_of",..._n(t),value:e})}function yU(e,t){return new w3e({check:"max_length",..._n(t),maximum:e})}function xb(e,t){return new C3e({check:"min_length",..._n(t),minimum:e})}function kU(e,t){return new A3e({check:"length_equals",..._n(t),length:e})}function s5e(e,t){return new x3e({check:"string_format",format:"regex",..._n(t),pattern:e})}function r5e(e){return new S3e({check:"string_format",format:"lowercase",..._n(e)})}function l5e(e){return new _3e({check:"string_format",format:"uppercase",..._n(e)})}function a5e(e,t){return new I3e({check:"string_format",format:"includes",..._n(t),includes:e})}function u5e(e,t){return new M3e({check:"string_format",format:"starts_with",..._n(t),prefix:e})}function c5e(e,t){return new T3e({check:"string_format",format:"ends_with",..._n(t),suffix:e})}function Jm(e){return new E3e({check:"overwrite",tx:e})}function d5e(e){return Jm(t=>t.normalize(e))}function f5e(){return Jm(e=>e.trim())}function h5e(){return Jm(e=>e.toLowerCase())}function p5e(){return Jm(e=>e.toUpperCase())}function m5e(){return Jm(e=>xwe(e))}function g5e(e,t,n){return new e({type:"array",element:t,..._n(n)})}function v5e(e,t,n){return new e({type:"custom",check:"custom",fn:t,..._n(n)})}function y5e(e){const t=k5e(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push($v(i,n.value,t._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push($v(o))}},e(n.value,n)));return t}function k5e(e,t){const n=new Pl({check:"custom",..._n(t)});return n._zod.check=e,n}function bU(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??h0,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ps(e,t,n={path:[],schemaPath:[]}){var i;const o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const r={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,r);const l=e._zod.toJSONSchema?.();if(l)r.schema=l;else{const c={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,r.schema,c);else{const f=r.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,f,c)}const d=e._zod.parent;d&&(r.ref||(r.ref=d),ps(d,t,c),t.seen.get(d).isParent=!0)}const a=t.metadataRegistry.get(e);return a&&Object.assign(r.schema,a),t.io==="input"&&Hr(e)&&(delete r.schema.examples,delete r.schema.default),t.io==="input"&&r.schema._prefault&&((i=r.schema).default??(i.default=r.schema._prefault)),delete r.schema._prefault,t.seen.get(e).schema}function wU(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=new Map;for(const r of e.seen.entries()){const l=e.metadataRegistry.get(r[0])?.id;if(l){const a=i.get(l);if(a&&a!==r[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(l,r[0])}}const o=r=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(r[0])?.id,f=e.external.uri??(m=>m);if(d)return{ref:f(d)};const h=r[1].defId??r[1].schema.id??`schema${e.counter++}`;return r[1].defId=h,{defId:h,ref:`${f("__shared")}#/${l}/${h}`}}if(r[1]===n)return{ref:"#"};const u=`#/${l}/`,c=r[1].schema.id??`__schema${e.counter++}`;return{defId:c,ref:u+c}},s=r=>{if(r[1].schema.$ref)return;const l=r[1],{ref:a,defId:u}=o(r);l.def={...l.schema},u&&(l.defId=u);const c=l.schema;for(const d in c)delete c[d];c.$ref=a};if(e.cycles==="throw")for(const r of e.seen.entries()){const l=r[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const r of e.seen.entries()){const l=r[1];if(t===r[0]){s(r);continue}if(e.external){const u=e.external.registry.get(r[0])?.id;if(t!==r[0]&&u){s(r);continue}}if(e.metadataRegistry.get(r[0])?.id){s(r);continue}if(l.cycle){s(r);continue}if(l.count>1&&e.reused==="ref"){s(r);continue}}}function CU(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=r=>{const l=e.seen.get(r);if(l.ref===null)return;const a=l.def??l.schema,u={...a},c=l.ref;if(l.ref=null,c){i(c);const f=e.seen.get(c),h=f.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(a.allOf=a.allOf??[],a.allOf.push(h)):Object.assign(a,h),Object.assign(a,u),r._zod.parent===c)for(const g in a)g==="$ref"||g==="allOf"||g in u||delete a[g];if(h.$ref&&f.def)for(const g in a)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(a[g])===JSON.stringify(f.def[g])&&delete a[g]}const d=r._zod.parent;if(d&&d!==c){i(d);const f=e.seen.get(d);if(f?.schema.$ref&&(a.$ref=f.schema.$ref,f.def))for(const h in a)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(a[h])===JSON.stringify(f.def[h])&&delete a[h]}e.override({zodSchema:r,jsonSchema:a,path:l.path??[]})};for(const r of[...e.seen.entries()].reverse())i(r[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const r=e.external.registry.get(t)?.id;if(!r)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(r)}Object.assign(o,n.def??n.schema);const s=e.external?.defs??{};for(const r of e.seen.entries()){const l=r[1];l.def&&l.defId&&(s[l.defId]=l.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const r=JSON.parse(JSON.stringify(o));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:Sb(t,"input",e.processors),output:Sb(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch{throw new Error("Error converting schema to JSON.")}}function Hr(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Hr(i.element,n);if(i.type==="set")return Hr(i.valueType,n);if(i.type==="lazy")return Hr(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Hr(i.innerType,n);if(i.type==="intersection")return Hr(i.left,n)||Hr(i.right,n);if(i.type==="record"||i.type==="map")return Hr(i.keyType,n)||Hr(i.valueType,n);if(i.type==="pipe")return Hr(i.in,n)||Hr(i.out,n);if(i.type==="object"){for(const o in i.shape)if(Hr(i.shape[o],n))return!0;return!1}if(i.type==="union"){for(const o of i.options)if(Hr(o,n))return!0;return!1}if(i.type==="tuple"){for(const o of i.items)if(Hr(o,n))return!0;return!!(i.rest&&Hr(i.rest,n))}return!1}const b5e=(e,t={})=>n=>{const i=bU({...n,processors:t});return ps(e,i),wU(i,e),CU(i,e)},Sb=(e,t,n={})=>i=>{const{libraryOptions:o,target:s}=i??{},r=bU({...o??{},target:s,io:t,processors:n});return ps(e,r),wU(r,e),CU(r,e)},w5e={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},C5e=(e,t,n,i)=>{const o=n;o.type="string";const{minimum:s,maximum:r,format:l,patterns:a,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof r=="number"&&(o.maxLength=r),l&&(o.format=w5e[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),u&&(o.contentEncoding=u),a&&a.size>0){const c=[...a];c.length===1?o.pattern=c[0].source:c.length>1&&(o.allOf=[...c.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},A5e=(e,t,n,i)=>{const o=n,{minimum:s,maximum:r,format:l,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.type="number",typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=c,o.exclusiveMinimum=!0):o.exclusiveMinimum=c),typeof s=="number"&&(o.minimum=s,typeof c=="number"&&t.target!=="draft-04"&&(c>=s?delete o.minimum:delete o.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u),typeof r=="number"&&(o.maximum=r,typeof u=="number"&&t.target!=="draft-04"&&(u<=r?delete o.maximum:delete o.exclusiveMaximum)),typeof a=="number"&&(o.multipleOf=a)},x5e=(e,t,n,i)=>{n.type="boolean"},S5e=(e,t,n,i)=>{n.not={}},_5e=(e,t,n,i)=>{},I5e=(e,t,n,i)=>{const o=e._zod.def,s=Xq(o.entries);s.every(r=>typeof r=="number")&&(n.type="number"),s.every(r=>typeof r=="string")&&(n.type="string"),n.enum=s},M5e=(e,t,n,i)=>{const o=e._zod.def,s=[];for(const r of o.values)if(r===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof r=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(r))}else s.push(r);if(s.length!==0)if(s.length===1){const r=s[0];n.type=r===null?"null":typeof r,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[r]:n.const=r}else s.every(r=>typeof r=="number")&&(n.type="number"),s.every(r=>typeof r=="string")&&(n.type="string"),s.every(r=>typeof r=="boolean")&&(n.type="boolean"),s.every(r=>r===null)&&(n.type="null"),n.enum=s},T5e=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},E5e=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},L5e=(e,t,n,i)=>{const o=n,s=e._zod.def,{minimum:r,maximum:l}=e._zod.bag;typeof r=="number"&&(o.minItems=r),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=ps(s.element,t,{...i,path:[...i.path,"items"]})},N5e=(e,t,n,i)=>{const o=n,s=e._zod.def;o.type="object",o.properties={};const r=s.shape;for(const u in r)o.properties[u]=ps(r[u],t,{...i,path:[...i.path,"properties",u]});const l=new Set(Object.keys(r)),a=new Set([...l].filter(u=>{const c=s.shape[u]._zod;return t.io==="input"?c.optin===void 0:c.optout===void 0}));a.size>0&&(o.required=Array.from(a)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=ps(s.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},F5e=(e,t,n,i)=>{const o=e._zod.def,s=o.inclusive===!1,r=o.options.map((l,a)=>ps(l,t,{...i,path:[...i.path,s?"oneOf":"anyOf",a]}));s?n.oneOf=r:n.anyOf=r},D5e=(e,t,n,i)=>{const o=e._zod.def,s=ps(o.left,t,{...i,path:[...i.path,"allOf",0]}),r=ps(o.right,t,{...i,path:[...i.path,"allOf",1]}),l=u=>"allOf"in u&&Object.keys(u).length===1,a=[...l(s)?s.allOf:[s],...l(r)?r.allOf:[r]];n.allOf=a},R5e=(e,t,n,i)=>{const o=n,s=e._zod.def;o.type="object";const r=s.keyType,a=r._zod.bag?.patterns;if(s.mode==="loose"&&a&&a.size>0){const c=ps(s.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});o.patternProperties={};for(const d of a)o.patternProperties[d.source]=c}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=ps(s.keyType,t,{...i,path:[...i.path,"propertyNames"]})),o.additionalProperties=ps(s.valueType,t,{...i,path:[...i.path,"additionalProperties"]});const u=r._zod.values;if(u){const c=[...u].filter(d=>typeof d=="string"||typeof d=="number");c.length>0&&(o.required=c)}},O5e=(e,t,n,i)=>{const o=e._zod.def,s=ps(o.innerType,t,i),r=t.seen.get(e);t.target==="openapi-3.0"?(r.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},P5e=(e,t,n,i)=>{const o=e._zod.def;ps(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType},B5e=(e,t,n,i)=>{const o=e._zod.def;ps(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},$5e=(e,t,n,i)=>{const o=e._zod.def;ps(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},z5e=(e,t,n,i)=>{const o=e._zod.def;ps(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType;let r;try{r=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=r},j5e=(e,t,n,i)=>{const o=e._zod.def,s=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;ps(s,t,i);const r=t.seen.get(e);r.ref=s},H5e=(e,t,n,i)=>{const o=e._zod.def;ps(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0},AU=(e,t,n,i)=>{const o=e._zod.def;ps(o.innerType,t,i);const s=t.seen.get(e);s.ref=o.innerType},W5e=Ft("ZodISODateTime",(e,t)=>{q3e.init(e,t),xo.init(e,t)});function q5e(e){return Q8e(W5e,e)}const U5e=Ft("ZodISODate",(e,t)=>{U3e.init(e,t),xo.init(e,t)});function V5e(e){return Y8e(U5e,e)}const K5e=Ft("ZodISOTime",(e,t)=>{V3e.init(e,t),xo.init(e,t)});function Z5e(e){return J8e(K5e,e)}const G5e=Ft("ZodISODuration",(e,t)=>{K3e.init(e,t),xo.init(e,t)});function Q5e(e){return X8e(G5e,e)}const Y5e=(e,t)=>{iU.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Pwe(e,n)},flatten:{value:n=>Owe(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,QA,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,QA,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ka=Ft("ZodError",Y5e,{Parent:Error}),J5e=sS(Ka),X5e=rS(Ka),eCe=X4(Ka),tCe=ew(Ka),nCe=zwe(Ka),iCe=jwe(Ka),oCe=Hwe(Ka),sCe=Wwe(Ka),rCe=qwe(Ka),lCe=Uwe(Ka),aCe=Vwe(Ka),uCe=Kwe(Ka),Ao=Ft("ZodType",(e,t)=>(Co.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Sb(e,"input"),output:Sb(e,"output")}}),e.toJSONSchema=b5e(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Uf(t,{checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0}),e.with=e.check,e.clone=(n,i)=>Vf(e,n,i),e.brand=()=>e,e.register=((n,i)=>(n.add(e,i),e)),e.parse=(n,i)=>J5e(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>eCe(e,n,i),e.parseAsync=async(n,i)=>X5e(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>tCe(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>nCe(e,n,i),e.decode=(n,i)=>iCe(e,n,i),e.encodeAsync=async(n,i)=>oCe(e,n,i),e.decodeAsync=async(n,i)=>sCe(e,n,i),e.safeEncode=(n,i)=>rCe(e,n,i),e.safeDecode=(n,i)=>lCe(e,n,i),e.safeEncodeAsync=async(n,i)=>aCe(e,n,i),e.safeDecodeAsync=async(n,i)=>uCe(e,n,i),e.refine=(n,i)=>e.check(nAe(n,i)),e.superRefine=n=>e.check(iAe(n)),e.overwrite=n=>e.check(Jm(n)),e.optional=()=>vD(e),e.exactOptional=()=>WCe(e),e.nullable=()=>yD(e),e.nullish=()=>vD(yD(e)),e.nonoptional=n=>GCe(e,n),e.array=()=>pi(e),e.or=n=>DCe([e,n]),e.and=n=>PCe(e,n),e.transform=n=>kD(e,jCe(n)),e.default=n=>VCe(e,n),e.prefault=n=>ZCe(e,n),e.catch=n=>YCe(e,n),e.pipe=n=>kD(e,n),e.readonly=()=>eAe(e),e.describe=n=>{const i=e.clone();return h0.add(i,{description:n}),i},Object.defineProperty(e,"description",{get(){return h0.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return h0.get(e);const i=e.clone();return h0.add(i,n[0]),i},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),xU=Ft("_ZodString",(e,t)=>{lS.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(i,o,s)=>C5e(e,i,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...i)=>e.check(s5e(...i)),e.includes=(...i)=>e.check(a5e(...i)),e.startsWith=(...i)=>e.check(u5e(...i)),e.endsWith=(...i)=>e.check(c5e(...i)),e.min=(...i)=>e.check(xb(...i)),e.max=(...i)=>e.check(yU(...i)),e.length=(...i)=>e.check(kU(...i)),e.nonempty=(...i)=>e.check(xb(1,...i)),e.lowercase=i=>e.check(r5e(i)),e.uppercase=i=>e.check(l5e(i)),e.trim=()=>e.check(f5e()),e.normalize=(...i)=>e.check(d5e(...i)),e.toLowerCase=()=>e.check(h5e()),e.toUpperCase=()=>e.check(p5e()),e.slugify=()=>e.check(m5e())}),cCe=Ft("ZodString",(e,t)=>{lS.init(e,t),xU.init(e,t),e.email=n=>e.check(T8e(dCe,n)),e.url=n=>e.check(D8e(fCe,n)),e.jwt=n=>e.check(G8e(ICe,n)),e.emoji=n=>e.check(R8e(hCe,n)),e.guid=n=>e.check(dD(mD,n)),e.uuid=n=>e.check(E8e(Vy,n)),e.uuidv4=n=>e.check(L8e(Vy,n)),e.uuidv6=n=>e.check(N8e(Vy,n)),e.uuidv7=n=>e.check(F8e(Vy,n)),e.nanoid=n=>e.check(O8e(pCe,n)),e.guid=n=>e.check(dD(mD,n)),e.cuid=n=>e.check(P8e(mCe,n)),e.cuid2=n=>e.check(B8e(gCe,n)),e.ulid=n=>e.check($8e(vCe,n)),e.base64=n=>e.check(V8e(xCe,n)),e.base64url=n=>e.check(K8e(SCe,n)),e.xid=n=>e.check(z8e(yCe,n)),e.ksuid=n=>e.check(j8e(kCe,n)),e.ipv4=n=>e.check(H8e(bCe,n)),e.ipv6=n=>e.check(W8e(wCe,n)),e.cidrv4=n=>e.check(q8e(CCe,n)),e.cidrv6=n=>e.check(U8e(ACe,n)),e.e164=n=>e.check(Z8e(_Ce,n)),e.datetime=n=>e.check(q5e(n)),e.date=n=>e.check(V5e(n)),e.time=n=>e.check(Z5e(n)),e.duration=n=>e.check(Q5e(n))});function zt(e){return M8e(cCe,e)}const xo=Ft("ZodStringFormat",(e,t)=>{go.init(e,t),xU.init(e,t)}),dCe=Ft("ZodEmail",(e,t)=>{R3e.init(e,t),xo.init(e,t)}),mD=Ft("ZodGUID",(e,t)=>{F3e.init(e,t),xo.init(e,t)}),Vy=Ft("ZodUUID",(e,t)=>{D3e.init(e,t),xo.init(e,t)}),fCe=Ft("ZodURL",(e,t)=>{O3e.init(e,t),xo.init(e,t)}),hCe=Ft("ZodEmoji",(e,t)=>{P3e.init(e,t),xo.init(e,t)}),pCe=Ft("ZodNanoID",(e,t)=>{B3e.init(e,t),xo.init(e,t)}),mCe=Ft("ZodCUID",(e,t)=>{$3e.init(e,t),xo.init(e,t)}),gCe=Ft("ZodCUID2",(e,t)=>{z3e.init(e,t),xo.init(e,t)}),vCe=Ft("ZodULID",(e,t)=>{j3e.init(e,t),xo.init(e,t)}),yCe=Ft("ZodXID",(e,t)=>{H3e.init(e,t),xo.init(e,t)}),kCe=Ft("ZodKSUID",(e,t)=>{W3e.init(e,t),xo.init(e,t)}),bCe=Ft("ZodIPv4",(e,t)=>{Z3e.init(e,t),xo.init(e,t)}),wCe=Ft("ZodIPv6",(e,t)=>{G3e.init(e,t),xo.init(e,t)}),CCe=Ft("ZodCIDRv4",(e,t)=>{Q3e.init(e,t),xo.init(e,t)}),ACe=Ft("ZodCIDRv6",(e,t)=>{Y3e.init(e,t),xo.init(e,t)}),xCe=Ft("ZodBase64",(e,t)=>{J3e.init(e,t),xo.init(e,t)}),SCe=Ft("ZodBase64URL",(e,t)=>{e8e.init(e,t),xo.init(e,t)}),_Ce=Ft("ZodE164",(e,t)=>{t8e.init(e,t),xo.init(e,t)}),ICe=Ft("ZodJWT",(e,t)=>{i8e.init(e,t),xo.init(e,t)}),SU=Ft("ZodNumber",(e,t)=>{hU.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(i,o,s)=>A5e(e,i,o),e.gt=(i,o)=>e.check(hD(i,o)),e.gte=(i,o)=>e.check(N8(i,o)),e.min=(i,o)=>e.check(N8(i,o)),e.lt=(i,o)=>e.check(fD(i,o)),e.lte=(i,o)=>e.check(L8(i,o)),e.max=(i,o)=>e.check(L8(i,o)),e.int=i=>e.check(gD(i)),e.safe=i=>e.check(gD(i)),e.positive=i=>e.check(hD(0,i)),e.nonnegative=i=>e.check(N8(0,i)),e.negative=i=>e.check(fD(0,i)),e.nonpositive=i=>e.check(L8(0,i)),e.multipleOf=(i,o)=>e.check(pD(i,o)),e.step=(i,o)=>e.check(pD(i,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function kn(e){return e5e(SU,e)}const MCe=Ft("ZodNumberFormat",(e,t)=>{o8e.init(e,t),SU.init(e,t)});function gD(e){return t5e(MCe,e)}const TCe=Ft("ZodBoolean",(e,t)=>{s8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>x5e(e,n,i)});function y2(e){return n5e(TCe,e)}const ECe=Ft("ZodUnknown",(e,t)=>{r8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>_5e()});function Ts(){return i5e(ECe)}const LCe=Ft("ZodNever",(e,t)=>{l8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>S5e(e,n,i)});function _U(e){return o5e(LCe,e)}const NCe=Ft("ZodArray",(e,t)=>{a8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>L5e(e,n,i,o),e.element=t.element,e.min=(n,i)=>e.check(xb(n,i)),e.nonempty=n=>e.check(xb(1,n)),e.max=(n,i)=>e.check(yU(n,i)),e.length=(n,i)=>e.check(kU(n,i)),e.unwrap=()=>e.element});function pi(e,t){return g5e(NCe,e,t)}const FCe=Ft("ZodObject",(e,t)=>{c8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>N5e(e,n,i,o),Di(e,"shape",()=>t.shape),e.keyof=()=>wo(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ts()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ts()}),e.strict=()=>e.clone({...e._zod.def,catchall:_U()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Lwe(e,n),e.safeExtend=n=>Nwe(e,n),e.merge=n=>Fwe(e,n),e.pick=n=>Twe(e,n),e.omit=n=>Ewe(e,n),e.partial=(...n)=>Dwe(MU,e,n[0]),e.required=(...n)=>Rwe(TU,e,n[0])});function Gt(e,t){const n={type:"object",shape:e??{},..._n(t)};return new FCe(n)}const IU=Ft("ZodUnion",(e,t)=>{gU.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>F5e(e,n,i,o),e.options=t.options});function DCe(e,t){return new IU({type:"union",options:e,..._n(t)})}const RCe=Ft("ZodDiscriminatedUnion",(e,t)=>{IU.init(e,t),d8e.init(e,t)});function fd(e,t,n){return new RCe({type:"union",options:t,discriminator:e,..._n(n)})}const OCe=Ft("ZodIntersection",(e,t)=>{f8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>D5e(e,n,i,o)});function PCe(e,t){return new OCe({type:"intersection",left:e,right:t})}const BCe=Ft("ZodRecord",(e,t)=>{h8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>R5e(e,n,i,o),e.keyType=t.keyType,e.valueType=t.valueType});function aS(e,t,n){return new BCe({type:"record",keyType:e,valueType:t,..._n(n)})}const JA=Ft("ZodEnum",(e,t)=>{p8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(i,o,s)=>I5e(e,i,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(i,o)=>{const s={};for(const r of i)if(n.has(r))s[r]=t.entries[r];else throw new Error(`Key ${r} not found in enum`);return new JA({...t,checks:[],..._n(o),entries:s})},e.exclude=(i,o)=>{const s={...t.entries};for(const r of i)if(n.has(r))delete s[r];else throw new Error(`Key ${r} not found in enum`);return new JA({...t,checks:[],..._n(o),entries:s})}});function wo(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new JA({type:"enum",entries:n,..._n(t)})}const $Ce=Ft("ZodLiteral",(e,t)=>{m8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>M5e(e,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function zn(e,t){return new $Ce({type:"literal",values:Array.isArray(e)?e:[e],..._n(t)})}const zCe=Ft("ZodTransform",(e,t)=>{g8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>E5e(e,n),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Yq(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push($v(s,n.value,t));else{const r=s;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=e),n.issues.push($v(r))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function jCe(e){return new zCe({type:"transform",transform:e})}const MU=Ft("ZodOptional",(e,t)=>{vU.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>AU(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function vD(e){return new MU({type:"optional",innerType:e})}const HCe=Ft("ZodExactOptional",(e,t)=>{v8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>AU(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function WCe(e){return new HCe({type:"optional",innerType:e})}const qCe=Ft("ZodNullable",(e,t)=>{y8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>O5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function yD(e){return new qCe({type:"nullable",innerType:e})}const UCe=Ft("ZodDefault",(e,t)=>{k8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>B5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function VCe(e,t){return new UCe({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():tU(t)}})}const KCe=Ft("ZodPrefault",(e,t)=>{b8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>$5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function ZCe(e,t){return new KCe({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():tU(t)}})}const TU=Ft("ZodNonOptional",(e,t)=>{w8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>P5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function GCe(e,t){return new TU({type:"nonoptional",innerType:e,..._n(t)})}const QCe=Ft("ZodCatch",(e,t)=>{C8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>z5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function YCe(e,t){return new QCe({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const JCe=Ft("ZodPipe",(e,t)=>{A8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>j5e(e,n,i,o),e.in=t.in,e.out=t.out});function kD(e,t){return new JCe({type:"pipe",in:e,out:t})}const XCe=Ft("ZodReadonly",(e,t)=>{x8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>H5e(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function eAe(e){return new XCe({type:"readonly",innerType:e})}const tAe=Ft("ZodCustom",(e,t)=>{S8e.init(e,t),Ao.init(e,t),e._zod.processJSONSchema=(n,i,o)=>T5e(e,n)});function nAe(e,t={}){return v5e(tAe,e,t)}function iAe(e){return y5e(e)}const kp=zt().min(1),uS=zt().min(1),k2=zt().min(1),bp=zt().min(1),ga=zt().min(1),oAe=/^[A-Za-z0-9._-]{1,128}$/;function sAe(e){return oAe.test(e)&&e!=="."&&e!==".."}const EU=fd("kind",[Gt({kind:zn("user"),payload:Ts().optional()}),Gt({kind:zn("cron"),taskId:bp.optional(),payload:Ts().optional()}),Gt({kind:zn("task"),taskId:bp,payload:Ts().optional()}),Gt({kind:zn("hook"),payload:Ts().optional()}),Gt({kind:zn("compaction"),payload:Ts().optional()}),Gt({kind:zn("side"),payload:Ts().optional()}),Gt({kind:zn("other"),payload:Ts().optional()})]),rAe=Gt({inputTokens:kn().optional(),outputTokens:kn().optional(),cachedTokens:kn().optional(),cost:kn().optional()}),J0=Gt({inputOther:kn(),output:kn(),inputCacheRead:kn(),inputCacheCreation:kn()}),lAe=Gt({llmFirstTokenLatencyMs:kn().optional(),llmStreamDurationMs:kn().optional(),llmRequestBuildMs:kn().optional(),llmServerFirstTokenMs:kn().optional(),llmServerDecodeMs:kn().optional(),llmClientConsumeMs:kn().optional()}),aAe=Gt({failedAttempt:kn(),nextAttempt:kn(),maxAttempts:kn(),delayMs:kn(),errorName:zt(),errorMessage:zt(),statusCode:kn().optional()}),LU=wo(["queued","running","completed","failed","cancelled"]),uAe=wo(["running","completed","interrupted","failed"]),cAe=Gt({skillName:zt(),skillArgs:zt().optional()}),dAe=Gt({kind:zn("user"),skillActivations:pi(cAe).optional()}),bD={kind:zn("text"),frameId:k2,text:zt(),attachmentIds:pi(zt()).optional(),taskId:bp.optional(),promptIds:pi(zt()).optional()},fAe=fd("role",[Gt({...bD,role:zn("assistant"),origin:_U().optional()}),Gt({...bD,role:zn("user"),origin:dAe.optional()})]),hAe=Gt({kind:zn("thinking"),frameId:k2,text:zt()}),pAe=Gt({agentId:ga,role:wo(["child","member"]).optional()}),mAe=Gt({kind:wo(["stdout","stderr","progress","status","custom"]),text:zt().optional(),percent:kn().optional(),customKind:zt().optional(),customData:Ts().optional()}),gAe=Gt({kind:zn("tool"),frameId:k2,toolCallId:zt(),name:zt(),view:zt().optional(),state:wo(["running","done","error"]),input:Ts().optional(),output:Ts().optional(),display:Ts().optional(),error:zt().optional(),inputText:zt().optional(),progress:mAe.optional(),taskId:bp.optional(),approvalId:zt().optional(),todoId:zt().optional(),agentRefs:pi(pAe).optional()}),cS=Gt({interactionId:zt(),interactionKind:wo(["approval","question"]),toolCallId:zt().optional(),state:wo(["pending","approved","rejected","cancelled","answered","dismissed"]),request:Ts().optional(),response:Ts().optional()}),vAe=Gt({kind:zn("notice"),frameId:k2,level:wo(["error","warning","info"]),source:zt().optional(),message:zt(),detail:Ts().optional()}),NU=fd("kind",[fAe,hAe,gAe,vAe]),FU=Gt({kind:zn("step"),stepId:uS,turnId:kp,ordinal:kn().int(),state:uAe,frames:pi(NU),startedAt:zt().optional(),endedAt:zt().optional(),usage:J0.optional(),finishReason:zt().optional(),timing:lAe.optional(),retry:aAe.optional(),endReason:zt().optional(),endMessage:zt().optional()}),DU=Gt({kind:zn("turn"),turnId:kp,triggerPromptId:zt().min(1).optional(),ordinal:kn().int(),state:LU,origin:EU,prompt:zt().optional(),attachmentIds:pi(zt()).optional(),steps:pi(FU),startedAt:zt().optional(),endedAt:zt().optional(),usage:rAe.optional(),durationMs:kn().optional(),error:zt().optional()}),RU=Gt({kind:zn("marker"),markerId:zt(),marker:zt(),payload:Ts().optional(),at:zt().optional()}),OU=Gt({kind:zn("taskref"),refId:zt(),taskId:bp,at:zt().optional()}),PU=fd("kind",[DU,RU,OU]),dS=Gt({taskId:bp,kind:wo(["shell","subagent","tool","other"]),state:wo(["running","completed","failed","timed_out","killed","lost"]),detached:y2(),description:zt().optional(),agentId:ga.optional(),outputTail:zt(),startedAt:zt().optional(),endedAt:zt().optional(),resultSummary:zt().optional(),error:zt().optional(),stateReason:zt().optional(),usage:J0.optional(),model:zt().optional(),thinkingEffort:zt().optional()}),BU=Gt({objective:zt(),status:wo(["active","paused","blocked","complete"]),completionCriterion:zt().optional(),budgetUsed:kn().optional(),budgetLimit:kn().optional()}),yAe=Gt({plan:Gt({reviewPath:zt().optional(),version:kn().optional()}).optional(),swarm:Gt({trigger:zt().optional()}).optional(),tower:Gt({}).optional()}),kAe=Gt({plan:Gt({reviewPath:zt().optional(),version:kn().optional()}).nullable().optional(),swarm:Gt({trigger:zt().optional()}).nullable().optional(),tower:Gt({}).nullable().optional()}),bAe=fd("kind",[Gt({kind:zn("idle")}),Gt({kind:zn("running"),turnId:kn(),step:kn(),stepId:zt(),since:kn()}),Gt({kind:zn("streaming"),turnId:kn(),step:kn(),stepId:zt(),stream:wo(["assistant","thinking","tool_call"]),toolCallId:zt().optional(),toolName:zt().optional(),since:kn()}),Gt({kind:zn("tool_call"),turnId:kn(),step:kn(),toolCallId:zt(),name:zt(),since:kn()}),Gt({kind:zn("retrying"),turnId:kn(),step:kn(),stepId:zt(),failedAttempt:kn(),nextAttempt:kn(),maxAttempts:kn(),delayMs:kn(),errorName:zt().optional(),statusCode:kn().optional(),since:kn()}),Gt({kind:zn("awaiting_approval"),turnId:kn(),step:kn().optional(),approval:Ts().optional(),since:kn()}),Gt({kind:zn("interrupted"),turnId:kn(),step:kn().optional(),reason:wo(["aborted","max_steps","error"]),message:zt().optional(),at:kn()}),Gt({kind:zn("ended"),turnId:kn(),reason:wo(["completed","cancelled","failed","blocked"]),durationMs:kn().optional(),at:kn()})]),wAe=Gt({byModel:aS(zt(),J0).optional(),currentTurn:J0.optional(),total:J0.optional()}),CAe=Gt({model:zt().optional(),thinkingEffort:zt().optional(),usage:wAe.optional(),contextTokens:kn().optional(),maxContextTokens:kn().optional(),contextUsage:kn().optional(),permission:wo(["manual","yolo","auto"]).optional(),phase:bAe.optional()}),fS=Gt({goal:BU.optional(),modes:yAe.optional(),activity:wo(["idle","turn","disposing","unknown"]).optional(),agent:CAe.optional()}),AAe=fS.extend({goal:BU.nullable().optional(),modes:kAe.optional()}),nw=Gt({attachmentId:zt(),mediaType:zt(),name:zt().optional(),size:kn().optional(),source:fd("kind",[Gt({kind:zn("url"),url:zt()}),Gt({kind:zn("file"),fileId:zt()}),Gt({kind:zn("session_media"),fileId:zt()})]).optional(),placeholder:zt().optional()}),xAe=Gt({title:zt(),status:wo(["pending","in_progress","done"])}),hS=Gt({todoId:zt(),items:pi(xAe),updatedAt:zt().optional()}),pS=Gt({promptId:zt(),status:wo(["running","queued","blocked","completed","failed","aborted"]),userMessageId:zt().optional(),content:Ts().optional(),createdAt:zt(),finishedAt:zt().optional(),steeredAt:zt().optional()}),$U=Gt({items:pi(PU),tasks:pi(dS),interactions:pi(cS).default([]),attachments:pi(nw).default([]),todos:pi(hS).default([]),prompts:pi(pS).default([]),meta:fS,hasMoreOlder:y2().optional()}),SAe=DU.omit({steps:!0}),_Ae=FU.omit({frames:!0}),IAe=fd("type",[Gt({type:zn("frame"),turnId:kp,stepId:uS,frameId:k2}),Gt({type:zn("task"),taskId:bp})]),mS=fd("op",[Gt({op:zn("reset"),agentId:ga,snapshot:$U}),Gt({op:zn("turn.upsert"),turn:SAe}),Gt({op:zn("step.upsert"),turnId:kp,step:_Ae}),Gt({op:zn("frame.upsert"),turnId:kp,stepId:uS,frame:NU}),Gt({op:zn("append"),target:IAe,offset:kn().int().nonnegative(),text:zt()}),Gt({op:zn("marker.upsert"),item:RU,beforeTurn:kn().int().optional()}),Gt({op:zn("taskref.upsert"),item:OU,beforeTurn:kn().int().optional()}),Gt({op:zn("task.upsert"),task:dS}),Gt({op:zn("interaction.upsert"),interaction:cS}),Gt({op:zn("attachment.upsert"),attachment:nw}),Gt({op:zn("todo.upsert"),todo:hS}),Gt({op:zn("prompt.upsert"),prompt:pS}),Gt({op:zn("meta.merge"),meta:AAe}),Gt({op:zn("items.remove"),ids:pi(zt())})]);Gt({agentId:ga,ops:pi(mS)});const MAe=wo(["off","turn","block","delta"]),_m=kn().int().nonnegative(),TAe=aS(zt(),MAe);Gt({session_id:zt().min(1),transcript:TAe,transcript_since:aS(zt(),_m).optional()});Gt({agent_id:ga,before_turn:zt().min(1).optional(),after_turn:zt().min(1).optional(),page_size:kn().int().min(1).max(100).optional()}).superRefine((e,t)=>{e.before_turn!==void 0&&e.after_turn!==void 0&&t.addIssue({code:"custom",message:"before_turn and after_turn are mutually exclusive",path:["before_turn"]}),sAe(e.agent_id)||t.addIssue({code:"custom",message:"agent_id must be a plain agent id (no path separators)",path:["agent_id"]})});const EAe=Gt({agentId:ga,type:wo(["main","sub","independent"]).optional(),parentAgentId:ga.optional(),label:zt().optional(),createdAt:zt().optional(),disposedAt:zt().optional()}),LAe=Gt({agent_id:ga,items:pi(PU),has_more:y2(),tasks:pi(dS),interactions:pi(cS).default([]),attachments:pi(nw).default([]),todos:pi(hS).default([]),prompts:pi(pS).default([]),meta:fS,agents:pi(EAe),pending_interactions:pi(zt()),seq:_m.optional()});Gt({agent_id:ga,batches:pi(Gt({seq:_m,ops:pi(mS)})),latest_seq:_m,complete:y2()});const NAe=Gt({turn_id:kp,ordinal:kn().int(),state:LU,origin:EU,prompt:zt(),attachment_ids:pi(zt()).optional(),started_at:zt().optional()});Gt({agents:pi(Gt({agent_id:ga,messages:pi(NAe),attachments:pi(nw).default([])}))});const FAe=Gt({state:wo(["pending","approved","rejected","cancelled"]),selected_option:zt().optional(),feedback:zt().optional()}),DAe=Gt({tool_call_id:zt(),turn_id:kp,source:wo(["interaction","display","output"]),plan:zt(),path:zt().optional(),options:pi(Gt({label:zt(),description:zt().optional()})).optional(),review:FAe.optional()});Gt({agent_id:ga,plans:pi(DAe)});const RAe=Gt({agent_id:ga,snapshot:$U,has_more_older:y2(),seq:_m.optional()}),OAe=Gt({agent_id:ga,ops:pi(mS),seq:_m.optional()}),zU=RAe.extend({type:zn("transcript.reset")}),jU=OAe.extend({type:zn("transcript.ops")});fd("type",[zU,jU]);const wD=new Set(["turn.started","turn.step.started","turn.step.completed","turn.step.retrying","turn.step.interrupted","turn.ended","thinking.delta","assistant.delta","tool.call.started","tool.use","tool.call.delta","tool.progress","tool.result","agent.status.updated","prompt.submitted","prompt.completed","prompt.aborted","session.meta.updated","compaction.started","compaction.completed","compaction.cancelled","goal.updated","error","warning","subagent.spawned","subagent.started","subagent.suspended","subagent.completed","subagent.failed","task.started","task.terminated","background.task.started","background.task.terminated","cron.fired"]),PAe=new Set(["session.created","session.updated","session.deleted","session.status_changed","session.usage_updated","session.history_compacted","message.created","message.updated","approval.requested","approval.resolved","approval.expired","question.requested","question.answered","question.dismissed","task.created","task.progress","task.completed","assistant.tool_use_started","assistant.tool_use_delta","assistant.tool_use_completed","assistant.completed","tool.started","tool.output","tool.completed"]),BAe=new Set(["server_hello","ack","ping","resync_required","error","pong"]),$Ae=new Set(["assistant.delta","thinking.delta"]);function zAe(e,t){if(BAe.has(e))return{route:"ignore"};const n=e.startsWith("event."),i=n?e.slice(6):e;return $Ae.has(i)?jAe(t)?{route:"agent",agentType:i}:{route:"protocol"}:n?PAe.has(i)?{route:"protocol"}:wD.has(i)?{route:"agent",agentType:i}:{route:"protocol"}:wD.has(i)?{route:"agent",agentType:i}:{route:"agent",agentType:i}}function jAe(e){if(!e||typeof e!="object")return!1;const t=e;return"message_id"in t||"content_index"in t?!1:typeof t.delta=="string"}const HAe="kimi-code.bearer.",WAe=3e4;class CD{constructor(t){this.opts=t,this.tracer=t.tracer??eS}ws=null;connected=!1;closed=!1;subscriptions=new Map;transcriptSubscriptions=new Map;sideChannelAgents=new Map;pendingSubscriptions=[];terminalAttachments=new Map;msgSeq=0;clientHelloId=null;reconnectAttempts=0;reconnectTimer=null;heartbeatMs=3e4;lastActivityAt=0;tracer;connect(){if(this.ws!==null||this.closed)return;this.lastActivityAt=Date.now(),this.tracer.wsEvent?.({kind:"lifecycle",event:"connect",detail:{url:this.opts.wsUrl,attempt:this.reconnectAttempts}});const t=this.opts.credentialStore?.getToken(),n=t!==void 0?[`${HAe}${t}`]:void 0,i=new WebSocket(this.opts.wsUrl,n);this.ws=i,i.onopen=()=>{this.tracer.wsEvent?.({kind:"lifecycle",event:"open"})},i.onmessage=o=>{this.lastActivityAt=Date.now();try{const s=JSON.parse(String(o.data));this.tracer.wsEvent?.({kind:"in",frame:s}),this.handleFrame(s)}catch(s){this.tracer.wsEvent?.({kind:"lifecycle",event:"parse-error",detail:{error:String(s)}}),this.opts.handlers.onError(0,`Failed to parse WS frame: ${String(s)}`,!1)}},i.onerror=()=>{this.tracer.wsEvent?.({kind:"lifecycle",event:"error"}),this.opts.handlers.onError(0,"WebSocket error",!1)},i.onclose=o=>{this.tracer.wsEvent?.({kind:"lifecycle",event:"close",detail:o?{code:o.code,reason:o.reason,wasClean:o.wasClean}:void 0}),this.connected=!1,this.ws=null,this.opts.handlers.onConnectionState(!1),this.scheduleReconnect()}}scheduleReconnect(){if(this.closed||this.reconnectTimer!==null)return;const n=Math.min(3e4,1e3*2**this.reconnectAttempts)+Math.floor(Math.random()*250);this.reconnectAttempts+=1,this.tracer.wsEvent?.({kind:"lifecycle",event:"reconnect-scheduled",detail:{delayMs:n,attempt:this.reconnectAttempts}}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},n)}subscribe(t,n={seq:0}){if(this.subscriptions.set(t,{...n}),this.connected)this.sendSubscribe([t],{[t]:n});else{const i=this.pendingSubscriptions.findIndex(o=>o.sessionId===t);i!==-1&&this.pendingSubscriptions.splice(i,1),this.pendingSubscriptions.push({sessionId:t,cursor:{...n}})}}unsubscribe(t){this.subscriptions.delete(t);const n=this.pendingSubscriptions.findIndex(i=>i.sessionId===t);n!==-1&&this.pendingSubscriptions.splice(n,1),this.connected&&this.ws&&this.send({type:"unsubscribe",id:this.nextId(),payload:{session_ids:[t]}})}subscribeTranscript(t,n,i){let o=this.transcriptSubscriptions.get(t);o===void 0&&(o=new Map,this.transcriptSubscriptions.set(t,o)),o.set(n,i!==void 0?{sinceSeq:i}:{}),this.connected&&this.sendTranscriptSubscribe(t,n)}unsubscribeTranscript(t,n){const i=this.transcriptSubscriptions.get(t);if(i!==void 0)if(n===void 0)this.transcriptSubscriptions.delete(t);else{for(const o of n)i.delete(o);i.size===0&&this.transcriptSubscriptions.delete(t)}!this.connected||!this.ws||this.send({type:"unsubscribe_v2",id:this.nextId(),payload:{session_id:t,...n!==void 0?{agent_ids:n}:{}}})}markSideChannelAgent(t,n){if(!this.opts.mainAgentOnly)return;let i=this.sideChannelAgents.get(t);if(i===void 0&&(i=new Set,this.sideChannelAgents.set(t,i)),i.has(n))return;i.add(n);const o=this.subscriptions.get(t);this.connected&&o!==void 0&&this.sendSubscribe([t],{[t]:o})}abort(t,n){!this.connected||!this.ws||this.send({type:"abort",id:this.nextId(),payload:{session_id:t,prompt_id:n}})}terminalAttach(t,n,i){const o=Ky(t,n),s=this.terminalAttachments.get(o),r=i??s?.lastSeq??0;this.terminalAttachments.set(o,{sessionId:t,terminalId:n,lastSeq:r}),!(!this.connected||!this.ws)&&this.sendTerminalAttach(t,n,r)}terminalInput(t,n,i){!this.connected||!this.ws||this.send({type:"terminal_input",id:this.nextId(),payload:{session_id:t,terminal_id:n,data:i}})}terminalResize(t,n,i,o){!this.connected||!this.ws||this.send({type:"terminal_resize",id:this.nextId(),payload:{session_id:t,terminal_id:n,cols:i,rows:o}})}terminalDetach(t,n){this.terminalAttachments.delete(Ky(t,n)),!(!this.connected||!this.ws)&&this.send({type:"terminal_detach",id:this.nextId(),payload:{session_id:t,terminal_id:n}})}terminalClose(t,n){this.terminalAttachments.delete(Ky(t,n)),!(!this.connected||!this.ws)&&this.send({type:"terminal_close",id:this.nextId(),payload:{session_id:t,terminal_id:n}})}close(){this.closed=!0,this.connected=!1,this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(1e3),this.ws=null)}health(){const t=this.ws!==null&&this.ws.readyState===WebSocket.OPEN,n=Math.max(this.heartbeatMs*2,WAe),i=this.lastActivityAt>0&&Date.now()-this.lastActivityAt>n;return{connected:this.connected,open:t,stale:i}}reconnect(){if(this.closed)return;this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);const t=this.ws;if(t!==null){t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{t.close(1e3,"reconnect")}catch{}}const n=this.connected;this.ws=null,this.connected=!1,n&&this.opts.handlers.onConnectionState(!1),this.connect()}handleFrame(t){const n=t,i=t.type;if(i==="transcript.reset"){const o=zU.safeParse({type:i,...n.payload}),s=n.session_id;if(!o.success||typeof s!="string"){this.opts.handlers.onError(0,"Invalid transcript.reset frame",!1);return}const r=o.data;this.opts.handlers.onTranscriptReset?.(s,r.agent_id,{...r.snapshot,hasMoreOlder:r.has_more_older},r.seq);const l=this.transcriptSubscriptions.get(s)?.get(r.agent_id);l!==void 0&&r.seq!==void 0&&(l.sinceSeq=r.seq);return}if(i==="transcript.ops"){const o=jU.safeParse({type:i,...n.payload}),s=n.session_id;if(!o.success||typeof s!="string"){this.opts.handlers.onError(0,"Invalid transcript.ops frame",!1);return}const r=o.data,l=this.opts.handlers.onTranscriptOps?.(s,r.agent_id,r.ops,r.seq),a=this.transcriptSubscriptions.get(s)?.get(r.agent_id);l!==!1&&a!==void 0&&r.seq!==void 0&&(a.sinceSeq=r.seq);return}switch(i){case"server_hello":{const o=n.payload?.heartbeat_ms;typeof o=="number"&&o>0&&(this.heartbeatMs=o),this.onServerHello();break}case"ping":this.send({type:"pong",payload:{nonce:n.payload.nonce}});break;case"resync_required":{const o=n.payload.session_id,s=n.payload.epoch;this.subscriptions.set(o,{seq:n.payload.current_seq,epoch:s}),this.opts.handlers.onResync(o,n.payload.current_seq,s);break}case"error":{const o=n.session_id;typeof o=="string"&&this.opts.handlers.onRawAgentEvent?this.opts.handlers.onRawAgentEvent({type:"error",seq:n.seq,session_id:o,timestamp:n.timestamp,payload:n.payload}):this.opts.handlers.onError(n.payload.code,n.payload.msg,n.payload.fatal);break}case"ack":n.id===this.clientHelloId&&(this.clientHelloId=null,n.code===0&&this.opts.handlers.onReplayComplete?.());break;case"terminal_output":{const o=n.session_id,s=n.terminal_id,r=n.seq,l=Ky(o,s),a=this.terminalAttachments.get(l);a&&this.terminalAttachments.set(l,{...a,lastSeq:Math.max(a.lastSeq,r)});const u=typeof n.payload?.data=="string"?n.payload.data:"";this.opts.handlers.onTerminalOutput?.(o,s,u,r);break}case"terminal_exit":{const o=n.session_id,s=n.terminal_id,r=n.payload?.exit_code,l=typeof r=="number"?r:null;this.opts.handlers.onTerminalExit?.(o,s,l);break}default:{this.trackCursor(n);const o=n.type,s=zAe(o,n.payload);if(s.route==="protocol"){this.opts.handlers.onWireEvent(n);break}if(s.route==="agent"){if(this.opts.handlers.onRawAgentEvent&&typeof n.session_id=="string"){const r=n,l=n;this.opts.handlers.onRawAgentEvent({type:s.agentType,seq:r.seq,session_id:r.session_id,timestamp:r.timestamp,payload:r.payload,...l.volatile!==void 0?{volatile:l.volatile}:{},...l.offset!==void 0?{offset:l.offset}:{}})}break}break}}}onServerHello(){this.connected=!0,this.reconnectAttempts=0,this.opts.handlers.onConnectionState(!0);const t=Array.from(this.subscriptions.keys());for(const o of this.pendingSubscriptions)this.subscriptions.set(o.sessionId,o.cursor),t.includes(o.sessionId)||t.push(o.sessionId);this.pendingSubscriptions.length=0;const n={};for(const[o,s]of this.subscriptions.entries())n[o]=s;const i=this.nextId();this.clientHelloId=i,this.send({type:"client_hello",id:i,payload:{client_id:this.opts.clientId,subscriptions:t,cursors:n,...this.opts.mainAgentOnly?{agent_filter:this.rawAgentFilter(t)}:{}}});for(const o of this.transcriptSubscriptions.keys())this.sendTranscriptSubscribe(o);for(const o of this.terminalAttachments.values())this.sendTerminalAttach(o.sessionId,o.terminalId,o.lastSeq)}sendSubscribe(t,n){this.send({type:"subscribe",id:this.nextId(),payload:{session_ids:t,cursors:n,...this.opts.mainAgentOnly?{agent_filter:this.rawAgentFilter(t)}:{}}})}rawAgentFilter(t){return Object.fromEntries(t.map(n=>[n,["main",...this.sideChannelAgents.get(n)??[]]]))}sendTranscriptSubscribe(t,n){const i=this.transcriptSubscriptions.get(t);if(i===void 0||i.size===0)return;const o={},s={};for(const[r,l]of i)o[r]="delta",l.sinceSeq!==void 0&&(n===void 0||n===r)&&(s[r]=l.sinceSeq);this.send({type:"subscribe_v2",id:this.nextId(),payload:{session_id:t,transcript:o,...Object.keys(s).length>0?{transcript_since:s}:{}}})}sendTerminalAttach(t,n,i){this.send({type:"terminal_attach",id:this.nextId(),payload:{session_id:t,terminal_id:n,since_seq:i>0?i:void 0}})}trackCursor(t){if(t.volatile===!0)return;const n=t.session_id,i=t.seq;if(typeof n!="string"||typeof i!="number")return;const o=this.subscriptions.get(n);if(!o||i<=o.seq&&o.epoch!==void 0)return;const s=typeof t.epoch=="string"?t.epoch:o.epoch;this.subscriptions.set(n,{seq:Math.max(i,o.seq),epoch:s})}send(t){if(!(!this.ws||this.ws.readyState!==WebSocket.OPEN))try{this.ws.send(JSON.stringify(t)),this.tracer.wsEvent?.({kind:"out",frame:t})}catch{}}nextId(){return`c_${++this.msgSeq}`}}function Ky(e,t){return`${e}\0${t}`}async function qAe(e,t,n){const i=await e.get(`/sessions/${encodeURIComponent(t)}/transcript`,{agent_id:n.agentId,before_turn:n.beforeTurn,after_turn:n.afterTurn,page_size:n.pageSize}),o=LAe.parse(i),s={items:o.items,tasks:o.tasks,interactions:o.interactions,attachments:o.attachments,todos:o.todos,prompts:o.prompts,meta:o.meta,hasMoreOlder:o.has_more};return{agentId:o.agent_id,...s,agents:o.agents,pendingInteractions:o.pending_interactions,...o.seq!==void 0?{seq:o.seq}:{}}}const F8=10485760,UAe=5e3,AD=40001;function VAe(e,t){if(e===void 0)return t;let n;const i=/filename\*\s*=\s*UTF-8''([^;]+)/i.exec(e)?.[1]?.trim();if(i!==void 0)try{n=decodeURIComponent(i.replaceAll(/^"|"$/g,""))}catch{return t}else n=/filename\s*=\s*"([^"]*)"/i.exec(e)?.[1]??/filename\s*=\s*([^;]+)/i.exec(e)?.[1]?.trim();return n===void 0||n.length===0||n.length>200||n==="."||n===".."||/[\u0000-\u001F\u007F/\\]/.test(n)||!n.toLowerCase().endsWith(".zip")?t:n}function KAe(e){if(typeof e!="object"||e===null)return{errorName:typeof e};const t=e;return{errorName:typeof t.name=="string"?t.name:"Error",errorCode:typeof t.code=="number"?t.code:void 0,requestId:typeof t.requestId=="string"?t.requestId:void 0,phase:typeof t.phase=="string"?t.phase:void 0,httpStatus:typeof t.status=="number"?t.status:void 0}}function D8(e){return{id:e.id,sessionId:e.session_id,cwd:e.cwd,shell:e.shell,cols:e.cols,rows:e.rows,status:e.status,createdAt:e.created_at,exitedAt:e.exited_at,exitCode:e.exit_code}}function xD(e){return e==="auto_compact"||e==="manual_compact"}class ZAe{constructor(t){this.opts=t,this.tracer=t.tracer??eS,this.http=new UF({origin:t.origin,identity:t.identity,tracer:this.tracer,credentialStore:t.credentialStore}),this.httpV2=new UF({origin:t.origin,identity:t.identity,tracer:this.tracer,credentialStore:t.credentialStore,restBasePath:"/api/v2"})}http;httpV2;tracer;async getHealth(){return{status:"ok",uptimeSec:(await this.http.get("/healthz")).uptime_sec??0}}async getMeta(){const t=await this.http.get("/meta");return{serverVersion:t.server_version,serverId:t.server_id,startedAt:t.started_at,capabilities:t.capabilities,openInApps:Array.isArray(t.open_in_apps)?t.open_in_apps:[],dangerousBypassAuth:t.dangerous_bypass_auth===!0,experimentalFlags:t.experimental_flags??{},backend:t.backend==="v2"?"v2":"v1",webTitle:t.web_title??""}}async listSessions(t){const n={before_id:t?.beforeId,after_id:t?.afterId,page_size:t?.pageSize,busy:t?.busy,include_archive:t?.includeArchive,archived_only:t?.archivedOnly,exclude_empty:t?.excludeEmpty,workspace_id:t?.workspaceId},i=await this.http.get("/sessions",n);return{items:i.items.map(Wu),hasMore:i.has_more}}async listSessionsV2(t){const n={sort:t?.sort,page_size:t?.pageSize,page_token:t?.pageToken,page:t?.page,"meta.updated_after":t?.updatedAfter,"meta.updated_before":t?.updatedBefore,"meta.archived":t?.archived===void 0?void 0:String(t.archived),include:t?.include,"workspace.id":t?.workspaceIds,"activity.status":t?.statuses},i=await this.httpV2.get("/sessions",n);return{items:i.items,hasMore:i.has_more,nextPageToken:i.next_page_token,total:i.total}}async listSessionIdsV2(t){const n={sort:t?.sort,page_size:t?.pageSize,page_token:t?.pageToken,page:t?.page,"meta.updated_after":t?.updatedAfter,"meta.updated_before":t?.updatedBefore,"meta.archived":t?.archived===void 0?void 0:String(t.archived),fields:"id,archived","workspace.id":t?.workspaceIds,"activity.status":t?.statuses},i=await this.httpV2.get("/sessions",n);return{items:i.items,hasMore:i.has_more,nextPageToken:i.next_page_token,total:i.total}}async listSessionGroupsV2(t){const n={view:"by_workspace","group.page_size":t?.groupPageSize,"meta.has_prompt":t?.hasPrompt===void 0?void 0:String(t.hasPrompt),sort:t?.sort,page_size:t?.pageSize,page_token:t?.pageToken,"meta.archived":t?.archived===void 0?void 0:String(t.archived),"workspace.id":t?.workspaceIds,"activity.status":t?.statuses},i=await this.httpV2.get("/sessions",n);return{groups:i.groups,hasMore:i.has_more,nextPageToken:i.next_page_token,total:i.total}}async createSession(t){const n={metadata:t.cwd!==void 0?{cwd:t.cwd}:{}};t.workspaceId!==void 0&&(n.workspace_id=t.workspaceId),t.title!==void 0&&(n.title=t.title),t.model!==void 0&&(n.agent_config={model:t.model});const i=await this.http.post("/sessions",n);return Wu(i)}async getSession(t){const n=await this.http.get(`/sessions/${encodeURIComponent(t)}`);return Wu(n)}async updateSession(t,n){const i={};n.title!==void 0&&(i.title=n.title),n.cwd!==void 0&&(i.metadata={cwd:n.cwd});const o={};n.model!==void 0&&(o.model=n.model),n.permissionMode!==void 0&&(o.permission_mode=n.permissionMode),n.planMode!==void 0&&(o.plan_mode=n.planMode),n.swarmMode!==void 0&&(o.swarm_mode=n.swarmMode),n.towerMode!==void 0&&(o.tower_mode=n.towerMode),n.towerBase!==void 0&&(o.tower_base=n.towerBase),n.goalObjective!==void 0&&(o.goal_objective=n.goalObjective),n.goalControl!==void 0&&(o.goal_control=n.goalControl),n.thinking!==void 0&&(o.thinking=n.thinking),Object.keys(o).length>0&&(i.agent_config=o);const s=await this.http.post(`/sessions/${encodeURIComponent(t)}/profile`,i);return Wu(s)}async getSessionStatus(t){const n=await this.http.get(`/sessions/${encodeURIComponent(t)}/status`);return{model:n.model&&n.model.length>0?n.model:null,thinkingEffort:n.thinking_level,permission:n.permission,planMode:n.plan_mode===!0,swarmMode:n.swarm_mode===!0,towerMode:n.tower_mode===!0,contextTokens:n.context_tokens??0,maxContextTokens:n.max_context_tokens??0,contextUsage:n.context_usage??0}}async getSessionGoal(t){const n=await this.http.get(`/sessions/${encodeURIComponent(t)}/goal`);return Zq(n)}async getSessionPlans(t,n){const i=await this.http.get(`/sessions/${encodeURIComponent(t)}/transcript/plan`,{agent_id:n.agentId,tool_call_id:n.toolCallId});return i.plans.map(o=>({agentId:i.agent_id,toolCallId:o.tool_call_id,turnId:o.turn_id,source:o.source,plan:o.plan,...o.path!==void 0?{path:o.path}:{},...o.options!==void 0?{options:o.options.map(s=>({label:s.label,...s.description!==void 0?{description:s.description}:{}}))}:{},...o.review!==void 0?{review:{state:o.review.state,...o.review.selected_option!==void 0?{selectedOption:o.review.selected_option}:{},...o.review.feedback!==void 0?{feedback:o.review.feedback}:{}}}:{}}))}async getTurnFileChanges(t,n){const i=await this.http.get(`/sessions/${encodeURIComponent(t)}/file-history/changes`,{turn_id:n});return i.recorded===!1?"unrecorded":i.changes??[]}async getTurnFileContent(t,n,i,o){return(await this.http.get(`/sessions/${encodeURIComponent(t)}/file-history/content`,{turn_id:n,path:i,phase:o})).content??null}async getSessionWarnings(t){return(await this.http.get(`/sessions/${encodeURIComponent(t)}/warnings`)).warnings??[]}async archiveSession(t){return await this.http.post(`/sessions/${encodeURIComponent(t)}:archive`,{})}async restoreSession(t){const n=await this.http.post(`/sessions/${encodeURIComponent(t)}:restore`,{});return Wu(n)}async archiveSessions(t){return this.httpV2.post("/sessions:archive",{ids:t})}async restoreSessions(t){return this.httpV2.post("/sessions:restore",{ids:t})}async listMessages(t,n){const i={before_id:n?.beforeId,after_id:n?.afterId,page_size:n?.pageSize,role:n?.role},o=await this.http.get(`/sessions/${encodeURIComponent(t)}/messages`,i);return{items:o.items.map(Vq),hasMore:o.has_more}}async getSessionTranscript(t,n){return qAe(this.http,t,n)}async exportSession(t,n,i){const o=n===void 0?0:new TextEncoder().encode(n).byteLength,s=n===void 0||n.length===0?0:n.split(` +`).length,r=`/sessions/${encodeURIComponent(t)}/export`,l={web_log_bytes:o,web_log_entries:s},a=i?.desktop===!0;let u;try{u=await this.http.postZip(r,{web_log:n,...a?{desktop:!0}:{}},l)}catch(d){if(a&&li(d)&&d.code===AD)u=await this.http.postZip(r,{web_log:n},l);else throw d}const c=`${t}.zip`;return{blob:u.blob,fileName:VAe(u.contentDisposition,c)}}async submitPrompt(t,n){const i=Date.now();this.tracer.traceKeyEvent?.("prompt:start",{sessionId:t,contentCount:n.content.length,mediaCount:n.content.filter(o=>o.type==="image"||o.type==="video"||o.type==="file").length});try{const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/prompts`,$4e(n));return this.tracer.traceKeyEvent?.("prompt:accepted",{sessionId:t,promptId:o.prompt_id,status:o.status,durationMs:Date.now()-i}),{promptId:o.prompt_id,userMessageId:o.user_message_id,origin:o.origin,status:o.status}}catch(o){throw this.tracer.traceKeyEvent?.("prompt:failed",{sessionId:t,status:"failed",durationMs:Date.now()-i,...KAe(o)}),o}}async steerPrompts(t,n){const i=await this.http.post(`/sessions/${encodeURIComponent(t)}/prompts:steer`,{prompt_ids:n});return{steered:i.steered,promptIds:i.prompt_ids}}async abortPrompt(t,n){const i=await this.http.post(`/sessions/${encodeURIComponent(t)}/prompts/${encodeURIComponent(n)}:abort`,void 0,{allowCodes:[40903]});return{aborted:i.aborted,atSeq:i.at_seq}}async abortSession(t){return{aborted:(await this.http.post(`/sessions/${encodeURIComponent(t)}:abort`,{})).aborted}}async compactSession(t,n){await this.http.post(`/sessions/${encodeURIComponent(t)}:compact`,n?{instruction:n}:{})}async undoSession(t,n=1){await this.http.post(`/sessions/${encodeURIComponent(t)}:undo`,{count:n})}async generateSessionTitle(t,n){try{const i={};n?.force===!0&&(i.force=!0),n?.source!==void 0&&(i.source=n.source);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/title/generate`,i);return typeof o?.title=="string"&&o.title.length>0?o.title:null}catch{return null}}async forkSession(t,n){const i={};n?.title!==void 0&&(i.title=n.title);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}:fork`,i,{timeoutMs:HF});return Wu(o)}async createChildSession(t,n){const i={};n?.title!==void 0&&(i.title=n.title);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/children`,i,{timeoutMs:HF});return Wu(o)}async listChildSessions(t){return(await this.http.get(`/sessions/${encodeURIComponent(t)}/children`)).items.map(Wu)}async startBtw(t){return{agentId:(await this.http.post(`/sessions/${encodeURIComponent(t)}:btw`,{})).agent_id}}async respondApproval(t,n,i){const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}`,z4e(i));return{resolved:o.resolved,resolvedAt:o.resolved_at}}async respondQuestion(t,n,i){const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/questions/${encodeURIComponent(n)}`,V4e(i));return{resolved:o.resolved,resolvedAt:o.resolved_at}}async dismissQuestion(t,n){return{dismissed:!0,dismissedAt:(await this.http.post(`/sessions/${encodeURIComponent(t)}/questions/${encodeURIComponent(n)}:dismiss`,void 0,{allowCodes:[40909]})).dismissed_at}}async listTasks(t,n){const i={status:n};return(await this.http.get(`/sessions/${encodeURIComponent(t)}/tasks`,i)).items.map(s=>KA(s))}async getTask(t,n,i){const o={with_output:i?.withOutput,output_bytes:i?.outputBytes},s=await this.http.get(`/sessions/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}`,o);return KA(s)}async cancelTask(t,n){return await this.http.post(`/sessions/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}:cancel`)}async detachTask(t,n){return await this.http.post(`/sessions/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}:detach`)}async listTerminals(t){return(await this.http.get(`/sessions/${encodeURIComponent(t)}/terminals`)).items.map(D8)}async createTerminal(t,n={}){const i={cwd:n.cwd,shell:n.shell,cols:n.cols,rows:n.rows},o=await this.http.post(`/sessions/${encodeURIComponent(t)}/terminals`,i);return D8(o)}async getTerminal(t,n){const i=await this.http.get(`/sessions/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`);return D8(i)}async closeTerminal(t,n){return this.http.post(`/sessions/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}:close`)}async listSkills(t){return((await this.http.get(`/sessions/${encodeURIComponent(t)}/skills`)).skills??[]).map(i=>({name:i.name,description:i.description,path:i.path,source:i.source}))}async listSkillsForWorkspace(t){return((await this.http.get(`/workspaces/${encodeURIComponent(t)}/skills`)).skills??[]).map(i=>({name:i.name,description:i.description,path:i.path,source:i.source}))}async activateSkill(t,n,i,o){const s={};i!==void 0&&i.length>0&&(s.args=i),o!==void 0&&o.length>0&&(s.attachments=o.map(Kq));const r=await this.http.post(`/sessions/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}:activate`,s);return{activated:r.activated,skillName:r.skill_name}}async listCapabilities(){return(await this.http.get("/capabilities")).capabilities??[]}async getCapability(t){return this.http.get(`/capabilities/${encodeURIComponent(t)}`)}async installCapability(t){return this.http.post(`/capabilities/${encodeURIComponent(t)}:install`,{})}async listPlugins(){return(await this.http.get("/plugins")).plugins??[]}async listPluginMarketplace(){return(await this.http.get("/plugins/marketplace")).entries??[]}async installPlugin(t){return this.http.post("/plugins",{source:t})}async setPluginEnabled(t,n){return this.http.post(`/plugins/${encodeURIComponent(t)}:${n?"enable":"disable"}`,{})}async removePlugin(t){return this.http.post(`/plugins/${encodeURIComponent(t)}:remove`,{})}async listDirectory(t,n){const i={};n.path!==void 0&&(i.path=n.path),n.depth!==void 0&&(i.depth=n.depth),n.includeGitStatus!==void 0&&(i.include_git_status=n.includeGitStatus);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:list`,i),s=o.children_by_path?Object.fromEntries(Object.entries(o.children_by_path).map(([r,l])=>[r,l.map(ZF)])):void 0;return{items:o.items.map(ZF),childrenByPath:s,truncated:o.truncated}}async readFile(t,n){const i={path:n.path};n.offset!==void 0&&(i.offset=n.offset),n.length!==void 0&&(i.length=n.length);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:read`,i);return{path:o.path,content:o.content,encoding:o.encoding,size:o.size,truncated:o.truncated,etag:o.etag,mime:o.mime,languageId:o.language_id,lineCount:o.line_count,isBinary:o.is_binary}}async searchFiles(t,n,i){const o={workspace:t,query:n.query};n.limit!==void 0&&(o.limit=n.limit);const s=await this.http.post("/workspace/fs:search",o,{signal:i?.signal});return{items:s.items.map(r=>({path:r.path,name:r.name,kind:r.kind,score:r.score,matchPositions:r.match_positions})),truncated:s.truncated}}async suggestFiles(t,n,i){const o={workspace:t,query:n.query};n.limit!==void 0&&(o.limit=n.limit);const s=await this.http.post("/workspace/fs:suggest",o,{signal:i?.signal});return{items:s.items.map(r=>({path:r.path,name:r.name,kind:r.kind,score:r.score,matchPositions:r.match_positions})),truncated:s.truncated}}async grepFiles(t,n){const i={pattern:n.pattern};n.regex!==void 0&&(i.regex=n.regex),n.caseSensitive!==void 0&&(i.case_sensitive=n.caseSensitive);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:grep`,i);return{files:o.files,filesScanned:o.files_scanned,truncated:o.truncated,elapsedMs:o.elapsed_ms}}async getGitStatus(t,n){const i={};n!==void 0&&(i.paths=n);const o=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:git_status`,i);return{branch:o.branch,ahead:o.ahead,behind:o.behind,entries:o.entries,additions:o.additions,deletions:o.deletions,pullRequest:o.pullRequest??null}}async getFileDiff(t,n){const i=await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:diff`,{path:n});return{path:i.path,diff:i.diff,truncated:i.truncated??!1}}getFileDownloadUrl(t,n){const i=n.split("/").map(o=>encodeURIComponent(o)).join("/");return Jd(this.opts.origin,`/sessions/${encodeURIComponent(t)}/fs/${i}:download`)}async openFile(t,n){const i={path:n.path};return n.line!==void 0&&(i.line=n.line),this.http.post(`/sessions/${encodeURIComponent(t)}/fs:open`,i)}async revealFile(t,n){return this.http.post(`/sessions/${encodeURIComponent(t)}/fs:reveal`,{path:n.path})}async openInApp(t,n,i,o){const s={app_id:n,path:i};o!==void 0&&(s.line=o),await this.http.post(`/sessions/${encodeURIComponent(t)}/fs:open-in`,s)}async listWorkspaces(){try{return((await this.http.get("/workspaces")).items??[]).map(Y0)}catch{return[]}}async addWorkspace(t){const n={root:t.root};t.name!==void 0&&(n.name=t.name);const i=await this.http.post("/workspaces",n);return Y0(i)}async deleteWorkspace(t){await this.http.delete(`/workspaces/${encodeURIComponent(t)}`)}async updateWorkspace(t,n){const i=await this.http.patch(`/workspaces/${encodeURIComponent(t)}`,{name:n.name});return Y0(i)}async browseFs(t){try{const n=await this.http.get("/fs:browse",{path:t});return{path:n.path,parent:n.parent,entries:(n.entries??[]).map(i=>({name:i.name,path:i.path,isDir:i.is_dir}))}}catch{return{path:"",parent:null,entries:[]}}}async getFsHome(){try{const t=await this.http.get("/fs:home");return{home:t.home,recentRoots:t.recent_roots??[]}}catch{return{home:"",recentRoots:[]}}}async listModels(){return(await this.http.get("/models")).items.map(Z4e)}async listProviders(){return(await this.http.get("/providers")).items.map(f1)}async getProvider(t){const n=await this.http.get(`/providers/${encodeURIComponent(t)}`),i=f1(n);return n.api_key!==void 0?{...i,apiKey:n.api_key}:i}async addProvider(t){const n={id:t.id??"",type:t.type,models:(t.models??[]).map(o=>{const s={model:o.model,max_context_size:o.maxContextSize};return o.displayName!==void 0&&(s.display_name=o.displayName),o.capabilities!==void 0&&(s.capabilities=o.capabilities),o.maxOutputSize!==void 0&&(s.max_output_size=o.maxOutputSize),o.supportEfforts!==void 0&&(s.support_efforts=o.supportEfforts),o.adaptiveThinking!==void 0&&(s.adaptive_thinking=o.adaptiveThinking),s})};t.apiKey!==void 0&&(n.api_key=t.apiKey),t.baseUrl!==void 0&&(n.base_url=t.baseUrl),t.defaultModel!==void 0&&(n.default_model=t.defaultModel);const i=await this.http.post("/providers",n);return f1(i)}async updateProvider(t,n){const i={type:n.type,models:(n.models??[]).map(s=>{const r={model:s.model,max_context_size:s.maxContextSize};return s.displayName!==void 0&&(r.display_name=s.displayName),s.capabilities!==void 0&&(r.capabilities=s.capabilities),s.maxOutputSize!==void 0&&(r.max_output_size=s.maxOutputSize),s.supportEfforts!==void 0&&(r.support_efforts=s.supportEfforts),s.adaptiveThinking!==void 0&&(r.adaptive_thinking=s.adaptiveThinking),r})};n.newId!==void 0&&(i.new_id=n.newId),n.apiKey!==void 0&&(i.api_key=n.apiKey),n.baseUrl!==void 0&&(i.base_url=n.baseUrl),n.defaultModel!==void 0&&(i.default_model=n.defaultModel);const o=await this.http.put(`/providers/${encodeURIComponent(t)}`,i);return{provider:f1(o.provider)}}async deleteProvider(t){return await this.http.delete(`/providers/${encodeURIComponent(t)}`),{deleted:t}}async listCatalogProviders(){return(await this.http.get("/catalog/providers")).items.map(GF)}async getCatalogProvider(t){const n=await this.http.get(`/catalog/providers/${encodeURIComponent(t)}`);return GF(n)}async importCatalogProvider(t){const n={catalog_id:t.catalogId};t.apiKey!==void 0&&(n.api_key=t.apiKey),t.baseUrl!==void 0&&(n.base_url=t.baseUrl),t.id!==void 0&&(n.id=t.id);const i=await this.http.post("/providers:import_catalog",n);return{provider:f1(i.provider),modelsImported:i.models_imported}}async importCustomRegistry(t){const n={url:t.url};t.apiKey!==void 0&&(n.api_key=t.apiKey);const i=await this.http.post("/providers:import_registry",n);return{providers:i.providers.map(f1),modelsImported:i.models_imported}}async refreshProvider(t){const n=await this.http.post(`/providers/${encodeURIComponent(t)}:refresh`);return R8(n)}async refreshAllProviders(){const t=await this.http.post("/providers:refresh");return R8(t)}async refreshOAuthProviderModels(){const t=await this.http.post("/providers:refresh_oauth");return R8(t)}async getConfig(){const t=await this.http.get("/config");return ZA(t)}async setConfig(t){const n={},i={providers:"providers",defaultProvider:"default_provider",defaultModel:"default_model",secondaryModel:"secondary_model",models:"models",thinking:"thinking",planMode:"plan_mode",yolo:"yolo",defaultPermissionMode:"default_permission_mode",defaultPlanMode:"default_plan_mode",permission:"permission",hooks:"hooks",services:"services",mergeAllAvailableSkills:"merge_all_available_skills",extraSkillDirs:"extra_skill_dirs",loopControl:"loop_control",background:"background",experimental:"experimental",telemetry:"telemetry",raw:"raw"};for(const[s,r]of Object.entries(t)){const l=i[s];l!==void 0&&(n[l]=r)}const o=await this.http.post("/config",n);return ZA(o)}async getAuth(){const t=await this.http.get("/auth");return{modelsReady:t.models_ready,providersCount:t.providers_count,managedProvider:t.managed_provider?{status:t.managed_provider.status}:null}}async startOAuthLogin(t){let n;try{n=await this.http.post("/oauth/login",t===void 0?{}:{region:t})}catch(i){if(t!==void 0&&li(i)&&i.code===AD)n=await this.http.post("/oauth/login",{});else throw i}return n.status==="authenticated"?{flowId:n.flow_id,provider:n.provider,status:"authenticated"}:{flowId:n.flow_id,provider:n.provider,status:"pending",verificationUri:n.verification_uri,verificationUriComplete:n.verification_uri_complete,userCode:n.user_code,expiresIn:n.expires_in,interval:n.interval,expiresAt:n.expires_at}}async pollOAuthLogin(){const t=await this.http.get("/oauth/login");return t?{flowId:t.flow_id,status:t.status,resolvedAt:t.resolved_at,errorMessage:t.error_message}:null}async cancelOAuthLogin(){const t=await this.http.delete("/oauth/login");return{cancelled:t.cancelled,status:t.status}}async logout(){return{loggedOut:(await this.http.post("/oauth/logout",{})).logged_out}}async getUsage(){const t=await this.http.get("/oauth/usage");if(t.kind==="error")return{kind:"error",message:t.message,status:t.status};const n=i=>({name:i.name,window:i.window,used:i.used,limit:i.limit,resetAt:i.reset_at});return{kind:"ok",summary:t.summary===null?null:n(t.summary),limits:t.limits.map(n),extraUsage:t.extra_usage===null?null:{balanceCents:t.extra_usage.balance_cents,totalCents:t.extra_usage.total_cents,monthlyChargeLimitEnabled:t.extra_usage.monthly_charge_limit_enabled,monthlyChargeLimitCents:t.extra_usage.monthly_charge_limit_cents,monthlyUsedCents:t.extra_usage.monthly_used_cents,currency:t.extra_usage.currency}}}async getUserInfo(){return this.http.get("/oauth/userinfo")}async getOAuthRegion(){try{const t=await Promise.race([this.http.get("/oauth/region"),new Promise((n,i)=>{setTimeout(()=>i(new Error("oauth region probe timed out")),UAe)})]);return t.region==="mainland-cn"||t.region==="global"?t.region:null}catch{return null}}async uploadFile(t){const n=new FormData;n.append("file",t.file,t.name??(t.file instanceof File?t.file.name:"upload")),t.name!==void 0&&n.append("name",t.name);const i=await this.http.postForm("/files",n,t.onProgress===void 0?void 0:{onUploadProgress:t.onProgress});return{id:i.id,name:i.name,mediaType:i.media_type,size:i.size}}getFileUrl(t){return Jd(this.opts.origin,`/files/${encodeURIComponent(t)}`)}async getFileBlob(t){return this.http.getBlob(`/files/${encodeURIComponent(t)}`)}getSessionMediaUrl(t,n){return Jd(this.opts.origin,`/sessions/${encodeURIComponent(t)}/media/${encodeURIComponent(n)}`)}async getSessionMediaBlob(t,n){return this.http.getBlob(`/sessions/${encodeURIComponent(t)}/media/${encodeURIComponent(n)}`)}async readHostFileContent(t){const n=await this.http.getBlob("/fs:content",{path:t},{maxBytes:F8});if(n.size>F8)throw new z7({size:n.size,limit:F8});const i=n.type,o=!GAe(i),s=i||(o?"application/octet-stream":"text/plain");if(o){const l=await QAe(n);return{path:t,content:l,encoding:"base64",mime:s,isBinary:!0,size:n.size}}const r=await n.text();return{path:t,content:r,encoding:"utf-8",mime:s,isBinary:!1,size:n.size}}connectEvents(t){const n=jF(this.opts.origin,this.opts.identity.clientId),i=this.opts.projectorFactory(),o=new CD({wsUrl:n,clientId:this.opts.identity.clientId,tracer:this.tracer,credentialStore:this.opts.credentialStore,mainAgentOnly:this.opts.mainAgentOnly,handlers:{onWireEvent:s=>{const r=G4e(s),l=Q4e(s),a=K4e(s);a.type==="historyCompacted"&&!xD(a.reason)&&t.onResync(a.sessionId,a.beforeSeq),t.onEvent(a,{sessionId:r,seq:l})},onRawAgentEvent:s=>{const{type:r,seq:l,session_id:a,payload:u,offset:c}=s,d=i.project(r,u,a,{offset:c});for(const f of d){const h=u?.turnId,m=f.type==="assistantDelta"&&typeof h=="number"&&typeof c=="number"&&(r==="assistant.delta"||r==="thinking.delta")?{turnId:h,offset:c,kind:r==="assistant.delta"?"text":"thinking"}:void 0;f.type==="historyCompacted"&&!xD(f.reason)&&t.onResync(a,l),t.onEvent(f,{sessionId:a,seq:l,stream:m})}},onResync:(s,r,l)=>{i.reset(s),t.onResync(s,r,l)},onConnectionState:s=>{t.onConnectionChange(s)},onReplayComplete:()=>{t.onReplayComplete?.()},onError:(s,r,l)=>{t.onError(s,r,l)},onTerminalOutput:(s,r,l,a)=>{t.onTerminalOutput?.(s,r,l,a)},onTerminalExit:(s,r,l)=>{t.onTerminalExit?.(s,r,l)},onTranscriptReset:(s,r,l,a)=>{t.onTranscriptReset?.(s,r,l,a)},onTranscriptOps:(s,r,l,a)=>t.onTranscriptOps?.(s,r,l,a)??!0}});return o.connect(),{subscribe(s,r){o.subscribe(s,r??{seq:0})},unsubscribe(s){o.unsubscribe(s),i.forgetSession(s)},subscribeTranscript(s,r,l){o.subscribeTranscript(s,r,l)},unsubscribeTranscript(s,r){o.unsubscribeTranscript(s,r)},bindNextPromptId(s,r){i.bindNextPromptId(s,r)},abort(s,r){o.abort(s,r)},terminalAttach(s,r,l){o.terminalAttach(s,r,l)},terminalInput(s,r,l){o.terminalInput(s,r,l)},terminalResize(s,r,l,a){o.terminalResize(s,r,l,a)},terminalDetach(s,r){o.terminalDetach(s,r)},terminalClose(s,r){o.terminalClose(s,r)},markSideChannelAgent(s,r){o.markSideChannelAgent(s,r),i.markSideChannelAgent(r)},health(){return o.health()},reconnect(){o.reconnect()},close(){o.close()}}}connectTranscriptChannel(t){const n=`${this.opts.identity.clientId}-transcript`,i=new CD({wsUrl:jF(this.opts.origin,n),clientId:n,tracer:this.tracer,credentialStore:this.opts.credentialStore,handlers:{onWireEvent:()=>{},onResync:()=>{},onConnectionState:o=>t.onConnectionState?.(o),onError:(o,s,r)=>t.onError?.(o,s,r),onTranscriptReset:t.onTranscriptReset,onTranscriptOps:t.onTranscriptOps}});return i.connect(),{subscribe:()=>{},unsubscribe:()=>{},subscribeTranscript:(o,s,r)=>i.subscribeTranscript(o,s,r),unsubscribeTranscript:(o,s)=>i.unsubscribeTranscript(o,s),bindNextPromptId:()=>{},abort:()=>{},terminalAttach:()=>{},terminalInput:()=>{},terminalResize:()=>{},terminalDetach:()=>{},terminalClose:()=>{},markSideChannelAgent:()=>{},health:()=>i.health(),reconnect:()=>i.reconnect(),close:()=>i.close()}}}function R8(e){return{changed:e.changed.map(t=>({providerId:t.provider_id,providerName:t.provider_name,added:t.added,removed:t.removed})),unchanged:e.unchanged,failed:e.failed}}function GAe(e){const t=e.toLowerCase().split(";")[0].trim();return t===""||t==="text/plain"||t.startsWith("text/")?!0:/(json|xml|javascript|typescript|x-yaml|yaml|svg|x-sh|x-python|markdown|csv|html|css)$/.test(t)}function QAe(e){return new Promise((t,n)=>{const i=new FileReader;i.onload=()=>{const o=typeof i.result=="string"?i.result:"";t(o.slice(o.indexOf(",")+1))},i.onerror=()=>n(i.error),i.readAsDataURL(e)})}const YAe="main",JAe=new Set(["turn.started","turn.step.started","turn.step.completed","turn.step.retrying","turn.step.interrupted","turn.ended","thinking.delta","assistant.delta","tool.use","tool.call.started","tool.call.delta","tool.progress","tool.result","agent.status.updated","prompt.completed","prompt.aborted","error"]);function O8(e="msg_"){const t=Date.now().toString(36).padStart(10,"0"),n=Math.random().toString(36).slice(2,12).padEnd(10,"0");return`${e}${t}${n}`}function XAe(e){if(!e||typeof e!="object")return{input:0,output:0,cacheRead:0,cacheCreate:0};const t=e;return{input:t.inputOther??t.input_tokens??0,output:t.output??t.output_tokens??0,cacheRead:t.inputCacheRead??t.cache_read_input_tokens??0,cacheCreate:t.inputCacheCreation??t.cache_creation_input_tokens??0}}function SD(){return{turnPromptId:new Map,currentPromptId:void 0,totalInput:0,totalOutput:0,totalCacheRead:0,totalCacheCreate:0,contextTokens:0,contextLimit:0,turnCount:0,model:"",subagentMeta:new Map,restartedThisRun:new Set,settledByKernel:new Set,retiredBindings:new Set,registrationSeq:0,registrationOrderByKey:new Map,retryActive:!1}}function _r(e,t){const n=e[t];return typeof n=="string"?n:void 0}function nr(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function _a(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function e6e(e){if(!e||typeof e!="object")return null;const t=e,n=t.budget,i=n&&typeof n=="object"?n:{},o=_r(t,"status");if(o!=="active"&&o!=="paused"&&o!=="blocked"&&o!=="complete")return null;const s=_r(t,"goalId")??_r(t,"goal_id")??"goal",r=_r(t,"objective")??"";return{goalId:s,objective:r,completionCriterion:_r(t,"completionCriterion")??_r(t,"completion_criterion"),status:o,turnsUsed:nr(t,"turnsUsed")??nr(t,"turns_used")??0,tokensUsed:nr(t,"tokensUsed")??nr(t,"tokens_used")??0,wallClockMs:nr(t,"wallClockMs")??nr(t,"wall_clock_ms")??0,terminalReason:_r(t,"terminalReason")??_r(t,"terminal_reason"),budget:{tokenBudget:_a(i,"tokenBudget")??_a(i,"token_budget"),remainingTokens:_a(i,"remainingTokens")??_a(i,"remaining_tokens"),turnBudget:_a(i,"turnBudget")??_a(i,"turn_budget"),remainingTurns:_a(i,"remainingTurns")??_a(i,"remaining_turns"),wallClockBudgetMs:_a(i,"wallClockBudgetMs")??_a(i,"wall_clock_budget_ms"),remainingWallClockMs:_a(i,"remainingWallClockMs")??_a(i,"remaining_wall_clock_ms"),overBudget:i.overBudget===!0||i.over_budget===!0}}}function Wd(e,t,n,i,o){if(typeof i!="string"||i.length===0)return null;const r={...t.subagentMeta.get(i)??{id:i,agentId:i,sessionId:n,kind:"subagent",description:e("tasks.dockSubagent"),status:"running",createdAt:new Date().toISOString(),subagentPhase:"queued"},...o,id:i,sessionId:n,kind:"subagent"};return t.subagentMeta.set(i,r),r}function t6e(e,t,n){if(t==="turn.step.started")return null;if(t==="tool.use"||t==="tool.call.started"){const i=_r(n,"name")??_r(n,"toolName")??"tool",o=Ez(e,n6e(i)),s=i6e(e,i,n.args??n.input);return s?`Calling ${o}: ${s}`:`Calling ${o}`}if(t==="tool.progress"){const i=n.update;if(i&&typeof i=="object"){const s=_r(i,"text");if(s)return P8(s);const r=_r(i,"message");if(r)return P8(r)}const o=_r(n,"message");if(o)return P8(o)}return null}function n6e(e){return e.replace(/_\d+$/,"")}const _D=2e3;function P8(e){return e.length>_D?`${e.slice(0,_D)}…`:e}function i6e(e,t,n){if(n==null)return"";const i=typeof n=="string"?n:JSON.stringify(n);return $7(e,t,i)}function o6e(e,t,n,i,o,s,r){if(r.has(i)&&o==="turn.step.started")return[];if(o==="assistant.delta"){const h=_r(s,"delta");if(!h)return[];const m=t.subagentMeta.get(i),g=Wd(e,t,n,i,{status:"running",subagentPhase:"working",startedAt:m?.startedAt??new Date().toISOString()}),y=[];return g&&y.push({type:"taskCreated",sessionId:n,task:g}),y.push({type:"taskProgress",sessionId:n,taskId:i,outputChunk:h,stream:"stdout",kind:"text"}),y}const l=t6e(e,o,s);if(l===null||l.length===0)return[];const a=o==="tool.progress"?s.update:void 0,u=a!=null&&typeof a=="object"?a.replace===!0:!1,c=t.subagentMeta.get(i),d=Wd(e,t,n,i,{status:"running",subagentPhase:"working",startedAt:c?.startedAt??new Date().toISOString()}),f=[];return d&&f.push({type:"taskCreated",sessionId:n,task:d}),f.push({type:"taskProgress",sessionId:n,taskId:i,outputChunk:l,stream:"stdout",replace:u}),f}function s6e(e){return Array.isArray(e)?e.map(t=>Q4(t)):[]}function r6e(e){return{inputTokens:e.totalInput,outputTokens:e.totalOutput,cacheReadTokens:e.totalCacheRead,cacheCreationTokens:e.totalCacheCreate,totalCostUsd:0,contextTokens:e.contextTokens,contextLimit:e.contextLimit,turnCount:e.turnCount}}const l6e=new Set(["session.meta.updated","goal.updated","compaction.completed","compaction.started","compaction.cancelled","compaction.blocked","hook.result","mcp.server.status","skill.activated","tool.list.updated"]);function a6e(e,t,n){switch(e){case"session.meta.updated":{const i=t?.patch?.title??t?.title,o=t?.patch?.lastPrompt,s={};return typeof i=="string"&&i.length>0&&(s.title=i),typeof o=="string"&&(s.lastPrompt=o),s.title!==void 0||s.lastPrompt!==void 0?[{type:"sessionMetaUpdated",sessionId:n,...s}]:[]}case"goal.updated":{const i=e6e(t?.snapshot??null);return[{type:"goalUpdated",sessionId:n,goal:i?.status==="complete"?null:i}]}case"compaction.completed":{const i=t?.result??{};return[{type:"compactionCompleted",sessionId:n,tokensBefore:typeof i.tokensBefore=="number"?i.tokensBefore:void 0,tokensAfter:typeof i.tokensAfter=="number"?i.tokensAfter:void 0,summary:typeof i.summary=="string"?i.summary:void 0},{type:"historyCompacted",sessionId:n,beforeSeq:0,reason:"auto_compact"}]}case"compaction.started":return[{type:"compactionStarted",sessionId:n,trigger:t?.trigger==="manual"?"manual":"auto",instruction:typeof t?.instruction=="string"?t.instruction:void 0}];case"compaction.cancelled":return[{type:"compactionCancelled",sessionId:n}];default:return[]}}function u6e(e){const{t}=e,n=new Map,i=new Set;function o(f){let h=n.get(f);return h||(h=SD(),n.set(f,h)),h}function s(f){n.set(f,SD())}function r(f){n.delete(f)}function l(f){return n.has(f)}function a(f){i.add(f)}function u(f,h){const m=o(f);m.currentPromptId=h}function c(f,h,m,g){try{return d(f,h,m,g)}catch(y){return Gu("[agentProjector] Error projecting event:",f,y instanceof Error?y.message:y),[]}}function d(f,h,m,g){if(l6e.has(f))return a6e(f,h,m);const y=o(m),k=h,v=[],C=k?.agentId;if(typeof C=="string"&&C!==YAe){const w=i.has(C);if(f==="prompt.submitted"){if(!w)return[];const M=k?.promptId,L=k?.userMessageId;if(!M||!L)return[];const E=s6e(k?.content);return E.length===0?[]:[{type:"messageCreated",agentId:C,message:{id:L,sessionId:m,role:"user",content:E,createdAt:typeof k?.createdAt=="string"?k.createdAt:new Date().toISOString(),promptId:M}}]}if(w&&(f==="thinking.delta"||f==="assistant.delta")){const M=k?.delta??"";return M?[{type:"agentDelta",sessionId:m,agentId:C,delta:{[f==="thinking.delta"?"thinking":"text"]:M}}]:[]}if(w&&f==="turn.ended")return[{type:"agentTurnEnded",sessionId:m,agentId:C,reason:k?.reason}];if(JAe.has(f))return o6e(t,y,m,C,f,k??{},i)}switch(f){case"turn.started":{const w=k?.turnId,M=y.currentPromptId??O8("pr_");y.currentPromptId=M,w!==void 0&&y.turnPromptId.set(w,M),v.push({type:"turnActiveChanged",sessionId:m,active:!0});break}case"turn.step.started":case"thinking.delta":case"assistant.delta":case"tool.use":case"tool.call.started":case"tool.call.delta":case"tool.progress":case"tool.result":break;case"turn.step.completed":{const w=XAe(k?.usage);y.totalInput+=w.input,y.totalOutput+=w.output,y.totalCacheRead+=w.cacheRead,y.totalCacheCreate+=w.cacheCreate;break}case"agent.status.updated":{k?.model&&(y.model=k.model),k?.contextTokens!==void 0&&(y.contextTokens=k.contextTokens),k?.maxContextTokens!==void 0&&(y.contextLimit=k.maxContextTokens);const w=k?.phase;w!=null&&w.kind==="retrying"?(y.retryActive=!0,v.push({type:"turnRetry",sessionId:m,retry:{failedAttempt:nr(w,"failedAttempt")??0,nextAttempt:nr(w,"nextAttempt")??0,maxAttempts:nr(w,"maxAttempts")??0,delayMs:nr(w,"delayMs")??0,errorName:_r(w,"errorName"),statusCode:nr(w,"statusCode"),turnId:nr(w,"turnId")}})):y.retryActive&&w!==void 0&&w!==null&&typeof w.kind=="string"&&(y.retryActive=!1,v.push({type:"turnRetry",sessionId:m,retry:void 0})),v.push({type:"sessionUsageUpdated",sessionId:m,usage:r6e(y),model:y.model||void 0,swarmMode:k?.swarmMode===!0?!0:k?.swarmMode===!1?!1:void 0,towerMode:k?.towerMode===!0?!0:k?.towerMode===!1?!1:void 0,planMode:k?.planMode===!0?!0:k?.planMode===!1?!1:void 0,thinking:typeof k?.thinkingEffort=="string"&&k.thinkingEffort.length>0?k.thinkingEffort:void 0});break}case"turn.ended":{const w=k?.turnId,M=(w!==void 0?y.turnPromptId.get(w):void 0)??y.currentPromptId;v.push({type:"turnActiveChanged",sessionId:m,active:!1,reason:k?.reason,promptId:M}),y.turnCount++,y.currentPromptId=void 0;break}case"prompt.completed":{const w=k?.promptId;typeof w=="string"&&w.length>0&&v.push({type:"promptCompleted",sessionId:m,promptId:w,reason:k?.reason??"completed"});break}case"prompt.aborted":{const w=k?.promptId;typeof w=="string"&&w.length>0&&v.push({type:"promptAborted",sessionId:m,promptId:w});break}case"turn.step.retrying":{y.retryActive=!0,v.push({type:"turnRetry",sessionId:m,retry:{failedAttempt:nr(k??{},"failedAttempt")??0,nextAttempt:nr(k??{},"nextAttempt")??0,maxAttempts:nr(k??{},"maxAttempts")??0,delayMs:nr(k??{},"delayMs")??0,errorName:_r(k??{},"errorName"),statusCode:nr(k??{},"statusCode"),turnId:typeof k?.turnId=="number"?k.turnId:void 0}});break}case"turn.step.interrupted":break;case"subagent.spawned":{const w=typeof k?.subagentId=="string"&&k.subagentId.length>0?k.subagentId:O8("task_"),M=typeof k?.taskId=="string"&&k.taskId.length>0?k.taskId:void 0,L=M!==void 0&&M!==w?y.subagentMeta.get(M):void 0,E=y.subagentMeta.get(w);L!==void 0&&y.subagentMeta.delete(M),M!==void 0&&!y.registrationOrderByKey.has(M)&&y.registrationOrderByKey.set(M,++y.registrationSeq);const S=E===void 0||L===void 0?E??L:{...E,createdAt:L.createdAt,startedAt:L.startedAt??E.startedAt,runInBackground:!0,backgroundTaskId:E.backgroundTaskId??M},x=S?.backgroundTaskId??(S!==void 0&&M!==void 0&&S.id===M?M:void 0),A=M!==void 0?y.registrationOrderByKey.get(M):void 0,T=x!==void 0?y.registrationOrderByKey.get(x):void 0,I=y.retiredBindings.has(M??"")||A!==void 0&&T!==void 0&&A0?k.model:S?.model,thinkingEffort:typeof k?.thinkingEffort=="string"&&k.thinkingEffort.length>0?k.thinkingEffort:S?.thinkingEffort,parentToolCallId:typeof k?.parentToolCallId=="string"?k.parentToolCallId:S?.parentToolCallId,swarmIndex:typeof k?.swarmIndex=="number"?k.swarmIndex:S?.swarmIndex,runInBackground:O?k?.runInBackground===!0||k?.runInBackground===void 0&&S?.runInBackground===!0:k?.runInBackground===!0||S?.runInBackground===!0,outputPreview:O?void 0:S?.outputPreview,outputBytes:O?void 0:S?.outputBytes,outputLines:O?void 0:S?.outputLines,suspendedReason:O?void 0:S?.suspendedReason,text:O?void 0:S?.text,backgroundTaskId:I?S?.backgroundTaskId:O?M:M??S?.backgroundTaskId};y.subagentMeta.set(R.id,R),v.push({type:"taskCreated",sessionId:m,task:R});break}case"subagent.started":{const w=typeof k?.subagentId=="string"?k.subagentId:void 0,M=w!==void 0&&(y.subagentMeta.get(w)?.status!==void 0&&y.subagentMeta.get(w).status!=="running"||y.settledByKernel.has(w));M&&y.settledByKernel.delete(w);const L=Wd(t,y,m,k?.subagentId,{subagentPhase:"working",status:"running",startedAt:new Date().toISOString(),suspendedReason:void 0,...M?{createdAt:new Date().toISOString(),completedAt:void 0,completedAtEstimated:void 0,outputPreview:void 0,outputBytes:void 0,outputLines:void 0,text:void 0}:{}});M&&w!==void 0&&y.restartedThisRun.add(w),L&&v.push({type:"taskCreated",sessionId:m,task:L});break}case"subagent.suspended":{const w=Wd(t,y,m,k?.subagentId,{subagentPhase:"suspended",status:"running",suspendedReason:typeof k?.reason=="string"?k.reason:void 0});w&&v.push({type:"taskCreated",sessionId:m,task:w});break}case"subagent.completed":{const w=typeof k?.resultSummary=="string"?k.resultSummary:void 0,M=Wd(t,y,m,k?.subagentId,{subagentPhase:"completed",status:"completed",completedAt:new Date().toISOString(),completedAtEstimated:!0,outputPreview:w});M&&v.push({type:"taskCreated",sessionId:m,task:M}),M!==null&&y.restartedThisRun.delete(M.id),v.push({type:"taskCompleted",sessionId:m,taskId:k?.subagentId??"",status:"completed",outputPreview:w});break}case"subagent.failed":{const w=typeof k?.error=="string"?k.error:void 0,M=Wd(t,y,m,k?.subagentId,{subagentPhase:"failed",status:"failed",completedAt:new Date().toISOString(),completedAtEstimated:!0,outputPreview:w});M&&v.push({type:"taskCreated",sessionId:m,task:M}),M!==null&&y.restartedThisRun.delete(M.id),v.push({type:"taskCompleted",sessionId:m,taskId:k?.subagentId??"",status:"failed",outputPreview:w});break}case"error":{v.push({type:"unknown",raw:{_agentError:!0,code:k?.code,message:k?.message,name:k?.name,details:k?.details,retryable:k?.retryable}});break}case"warning":{v.push({type:"unknown",raw:{_agentWarning:!0,message:k?.message}});break}case"task.started":case"background.task.started":{const w=k?.info??{},M=typeof w.startedAt=="number"?new Date(w.startedAt).toISOString():void 0,L=typeof w.taskId=="string"?w.taskId:typeof w.taskId=="number"?String(w.taskId):O8("task_"),E=typeof w.description=="string"?w.description:typeof w.command=="string"?w.command:t("tasks.defaultDescription");if(w.kind==="agent"){const x=typeof w.agentId=="string"&&w.agentId.length>0?w.agentId:void 0;if(x!==void 0){const A=y.subagentMeta.get(x),T=y.registrationOrderByKey.get(L),I=A?.backgroundTaskId!==void 0?y.registrationOrderByKey.get(A.backgroundTaskId):void 0;if(y.retiredBindings.has(L)||T!==void 0&&I!==void 0&&TI.backgroundTaskId===L);if(A===void 0&&(y.retiredBindings.has(L)||y.registrationOrderByKey.has(L)&&y.registrationOrderByKey.get(L)0&&y.settledByKernel.add(w.agentId),v.push({type:"taskCompleted",sessionId:m,taskId:typeof w.taskId=="string"?w.taskId:typeof w.taskId=="number"?String(w.taskId):"",status:w.status==="killed"?"cancelled":M?"failed":"completed"});break}}return v}return{project:c,bindNextPromptId:u,reset:s,forgetSession:r,markSideChannelAgent:a,hasSessionState:l}}function c6e(e){return new ZAe({origin:e.origin,identity:e.identity,tracer:e.tracer,credentialStore:e.credentialStore,projectorFactory:()=>u6e({t:e.t}),mainAgentOnly:e.mainAgentOnly})}const d6e={t:e=>e},ID="Sub Agent";function f6e(){return{sessions:[],activeSessionId:void 0,approvalsBySession:{},planReviewByToolCallId:{},questionsBySession:{},tasksBySession:{},goalBySession:{},goalVersionBySession:{},lastSeqBySession:{},turnActiveBySession:{},turnErrorBySession:{},turnRetryBySession:{},compactionBySession:{},warnings:[]}}function h6e(e){return{...e,sessions:e.sessions,approvalsBySession:{...e.approvalsBySession},planReviewByToolCallId:{...e.planReviewByToolCallId},questionsBySession:{...e.questionsBySession},tasksBySession:{...e.tasksBySession},goalBySession:{...e.goalBySession},goalVersionBySession:{...e.goalVersionBySession},lastSeqBySession:{...e.lastSeqBySession},turnActiveBySession:{...e.turnActiveBySession},turnErrorBySession:{...e.turnErrorBySession},turnRetryBySession:{...e.turnRetryBySession},compactionBySession:{...e.compactionBySession},warnings:[...e.warnings]}}function p6e(e,t,n){if(t!==void 0&&n!==void 0&&n>0){const i=e.lastSeqBySession[t]??0;n>i&&(e.lastSeqBySession[t]=n)}}function Zy(e,t){const n=e.sessions.find(i=>i.id===t.sessionId)?.lastSeq??0;return t.seq>Math.max(e.lastSeqBySession[t.sessionId]??0,n)}const m6e={"provider.connection_error":"connection","provider.auth_error":"auth","provider.rate_limit":"rateLimit","provider.overloaded":"overloaded","provider.filtered":"filtered","provider.api_error":"api","context.overflow":"contextOverflow"};function XA(e,t){const n=[],i=(r,l)=>{typeof l=="number"||typeof l=="boolean"?n.push({label:r,value:String(l)}):typeof l=="string"&&l.length>0&&n.push({label:r,value:l})};i(t("warnings.details.code"),e.code);const o=e.details??{};i(t("warnings.details.status"),o.statusCode),i(t("warnings.details.requestId"),o.requestId),i(t("warnings.details.errorName"),e.name);for(const[r,l]of Object.entries(o))r==="statusCode"||r==="requestId"||i(r,l);const s=(e.code!==void 0?m6e[e.code]:void 0)??"title";return{severity:"error",title:t(`warnings.agentError.${s}`),message:e.message,details:n.length>0?n:void 0}}function g6e(e,t,n,i=d6e){const o=h6e(e);switch(p6e(o,n.sessionId,n.seq),t.type){case"sessionCreated":{o.sessions.some(r=>r.id===t.session.id)||(o.sessions=[t.session,...o.sessions]);break}case"sessionUpdated":{o.sessions=o.sessions.map(s=>s.id===t.session.id?{...t.session,pullRequest:s.pullRequest}:s);break}case"sessionDeleted":{const s=t.sessionId;o.sessions=o.sessions.filter(r=>r.id!==s),delete o.tasksBySession[s],delete o.goalBySession[s],delete o.goalVersionBySession[s],delete o.approvalsBySession[s],delete o.questionsBySession[s],delete o.lastSeqBySession[s],delete o.turnActiveBySession[s],delete o.turnErrorBySession[s],delete o.turnRetryBySession[s],o.activeSessionId===s&&(o.activeSessionId=void 0);break}case"sessionWorkChanged":{if(!Zy(e,n))break;let s;o.sessions=o.sessions.map(r=>r.id!==t.sessionId?r:(s=t.pendingInteraction??(t.busy?r.pendingInteraction:"none"),{...r,busy:t.busy,mainTurnActive:t.mainTurnActive??(t.busy?r.mainTurnActive:!1),pendingInteraction:s,lastTurnReason:t.lastTurnReason})),s==="none"?(delete o.approvalsBySession[t.sessionId],delete o.questionsBySession[t.sessionId]):s==="question"&&delete o.approvalsBySession[t.sessionId],t.mainTurnActive===!0?o.turnActiveBySession[t.sessionId]=!0:(t.mainTurnActive===!1||!t.busy)&&(delete o.turnActiveBySession[t.sessionId],delete o.turnRetryBySession[t.sessionId]);break}case"sessionMetaUpdated":{o.sessions=o.sessions.map(s=>s.id===t.sessionId?{...s,title:t.title??s.title,lastPrompt:t.lastPrompt??s.lastPrompt}:s);break}case"sessionUsageUpdated":{o.sessions=o.sessions.map(s=>{if(s.id!==t.sessionId)return s;const r=t.model&&t.model.length>0?t.model:s.model;return{...s,usage:t.usage,model:r}});break}case"historyCompacted":break;case"compactionStarted":{o.compactionBySession={...o.compactionBySession,[t.sessionId]:{status:"running",trigger:t.trigger}};break}case"compactionCompleted":{const s=t.sessionId,{[s]:r,...l}=o.compactionBySession;o.compactionBySession=l;break}case"compactionCancelled":{const{[t.sessionId]:s,...r}=o.compactionBySession;o.compactionBySession=r;break}case"messageCreated":case"messageUpdated":case"assistantDelta":case"toolOutput":break;case"approvalRequested":{const s=t.sessionId,r=o.approvalsBySession[s]??[];r.some(u=>u.approvalId===t.approval.approvalId)||(o.approvalsBySession[s]=[...r,t.approval]);const a=t.approval.display;a?.kind==="plan_review"&&typeof a.plan=="string"&&a.plan.length>0&&(o.planReviewByToolCallId={...o.planReviewByToolCallId,[t.approval.toolCallId]:{plan:a.plan,path:typeof a.path=="string"?a.path:void 0}});break}case"approvalResolved":case"approvalExpired":{const s=t.sessionId,r=t.approvalId,l=o.approvalsBySession[s]??[];o.approvalsBySession[s]=l.filter(a=>a.approvalId!==r);break}case"questionRequested":{const s=t.sessionId,r=o.questionsBySession[s]??[];r.some(a=>a.questionId===t.question.questionId)||(o.questionsBySession[s]=[...r,t.question]);break}case"questionAnswered":case"questionDismissed":{const s=t.sessionId,r=t.questionId,l=o.questionsBySession[s]??[];o.questionsBySession[s]=l.filter(a=>a.questionId!==r);break}case"taskCreated":{const s=t.sessionId,r=o.tasksBySession[s]??[],l=r.findIndex(f=>f.id===t.task.id),a=t.task.backgroundTaskId===void 0?-1:r.findIndex(f=>f.id===t.task.backgroundTaskId),u=a!==-1&&l!==-1&&a!==l?r[a]:void 0,c=u!==void 0?r.filter((f,h)=>h!==a):r,d=c.findIndex(f=>f.id===t.task.id||t.task.backgroundTaskId!==void 0&&f.id===t.task.backgroundTaskId);if(d===-1)o.tasksBySession[s]=[...c,t.task];else{const f=[...c],h=c[d],m=t.task.backgroundTaskId!==void 0&&(t.task.backgroundTaskId===h.backgroundTaskId||h.id===t.task.backgroundTaskId)||h.id===t.task.id&&(h.kind!=="subagent"||h.agentId===void 0),g=(m&&h.status!=="running"?h:void 0)??(u!==void 0&&u.status!=="running"?u:void 0),y=g!==void 0&&(t.task.status==="running"||t.task.status!==g.status),k=!m&&h.status!=="running"||t.task.backgroundTaskId!==void 0&&h.backgroundTaskId!==void 0&&t.task.backgroundTaskId!==h.backgroundTaskId,v=m&&h.completedAt!==void 0&&h.completedAtEstimated!==!0;f[d]={...t.task,status:y?g.status:t.task.status,subagentPhase:y?g.subagentPhase:t.task.subagentPhase,completedAt:y?g.completedAt:v?h.completedAt:t.task.completedAt,completedAtEstimated:y?g.completedAtEstimated:v?h.completedAtEstimated:t.task.completedAtEstimated,outputLines:y?g.outputLines:k?u?.outputLines??t.task.outputLines:h.outputLines??u?.outputLines??t.task.outputLines,text:y?g.text:k?u?.text??t.task.text:h.text??u?.text??t.task.text,outputPreview:y?g.outputPreview:t.task.outputPreview??(k?u?.outputPreview:h.outputPreview??u?.outputPreview),outputBytes:y?g.outputBytes:t.task.outputBytes??(k?u?.outputBytes:h.outputBytes??u?.outputBytes),description:t.task.description===ID&&h.description!==ID?h.description:t.task.description,swarmIndex:t.task.swarmIndex??h.swarmIndex,parentToolCallId:t.task.parentToolCallId??h.parentToolCallId,subagentType:t.task.subagentType??h.subagentType,model:t.task.model??h.model,thinkingEffort:t.task.thinkingEffort??h.thinkingEffort,runInBackground:k?t.task.runInBackground:t.task.runInBackground??h.runInBackground,backgroundTaskId:k?t.task.backgroundTaskId:t.task.backgroundTaskId??h.backgroundTaskId,agentId:t.task.agentId??h.agentId},o.tasksBySession[s]=f}break}case"taskProgress":{const s=t.sessionId,r=o.tasksBySession[s]??[];o.tasksBySession[s]=r.map(l=>{if(l.id!==t.taskId)return l;if(l.kind==="subagent"&&t.kind==="text")return{...l,text:(l.text??"")+t.outputChunk};const a=l.outputLines??[];if(t.replace===!0){const c=a.length>0?[...a.slice(0,-1),t.outputChunk]:[t.outputChunk];return{...l,outputLines:c}}if(a.at(-1)===t.outputChunk)return l;const u=[...a,t.outputChunk];return{...l,outputLines:l.kind==="subagent"?u:u.slice(-40)}});break}case"taskCompleted":{const s=t.sessionId,r=o.tasksBySession[s]??[];o.tasksBySession[s]=r.map(l=>l.id!==t.taskId&&l.backgroundTaskId!==t.taskId||t.status==="completed"&&(l.status==="cancelled"||l.status==="failed")||t.status==="failed"&&l.status==="cancelled"?l:{...l,status:t.status,completedAt:l.completedAt??new Date().toISOString(),completedAtEstimated:l.completedAt===void 0?!0:l.completedAtEstimated,outputPreview:t.outputPreview??l.outputPreview,outputBytes:t.outputBytes??l.outputBytes});break}case"goalUpdated":{const s=t.sessionId;o.goalVersionBySession[s]=(o.goalVersionBySession[s]??0)+1,t.goal===null||t.goal.status==="complete"?delete o.goalBySession[s]:o.goalBySession[s]=t.goal;break}case"configChanged":{o.config=t.config;break}case"modelCatalogChanged":break;case"agentDelta":case"agentTurnEnded":break;case"promptCompleted":case"promptAborted":break;case"turnActiveChanged":{if(!Zy(e,n))break;if(o.sessions=o.sessions.map(s=>s.id===t.sessionId?{...s,mainTurnActive:t.active}:s),t.active)o.turnActiveBySession[t.sessionId]=!0,delete o.turnErrorBySession[t.sessionId],delete o.turnRetryBySession[t.sessionId];else{delete o.turnActiveBySession[t.sessionId],delete o.turnRetryBySession[t.sessionId];const s=t.reason===void 0||t.reason==="completed"?"completed":"failed",r=o.tasksBySession[t.sessionId];r!==void 0&&(o.tasksBySession[t.sessionId]=r.map(l=>l.kind!=="subagent"||l.status!=="running"||l.runInBackground===!0?l:{...l,status:s,subagentPhase:s,completedAt:l.completedAt??new Date().toISOString(),completedAtEstimated:l.completedAt===void 0?!0:l.completedAtEstimated,suspendedReason:void 0}))}break}case"turnRetry":{if(!Zy(e,n))break;t.retry===void 0?delete o.turnRetryBySession[t.sessionId]:o.turnRetryBySession[t.sessionId]=t.retry;break}case"unknown":{const s=t.raw;if(!(s&&s._noop===!0))if(s&&s._agentError){if(Zy(e,n)){if(n.sessionId!==void 0){const r=s.details??{};o.turnErrorBySession[n.sessionId]={code:s.code,message:s.message,name:s.name,retryable:s.retryable,statusCode:typeof r.statusCode=="number"?r.statusCode:void 0,requestId:typeof r.requestId=="string"?r.requestId:void 0}}(n.sessionId===void 0||n.sessionId!==e.activeSessionId)&&(o.warnings=[...o.warnings,XA(s,i.t)])}}else if(s&&s._agentWarning){const r=s.message??s.code??i.t("warnings.agentWarningFallback");o.warnings=[...o.warnings,`${i.t("warnings.noteLabel")}: ${r}`]}else{const r=s?.type??"(unknown)";o.warnings=[...o.warnings,i.t("warnings.unhandledEvent",{type:r})]}break}}return o}function v6e(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const o of n)if(e[o]!==t[o])return!1;return!0}function y6e(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n]*)>([\s\S]*?)<\/notification>/g,b6e=/([\w-]+)="([^"]*)"/g,w6e=/]*)>[\s\S]*?<\/output-file>/,C6e=/]*)>([\s\S]*?)<\/output-preview>/,A6e=/^Title: (.*)$/m,x6e=/^Severity: (.*)$/m;function Z9(e){return e.replaceAll(""",'"').replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}function B8(e){const t={};for(const n of e.matchAll(b6e))n[1]!==void 0&&n[2]!==void 0&&(t[n[1]]=Z9(n[2]));return t}function S6e(e,t,n){const i=B8(e),o=A6e.exec(t)?.[1]?.trim()??"",s=x6e.exec(t)?.[1]?.trim()??"";let r=t.split(` +`).filter(f=>!f.startsWith("Title: ")&&!f.startsWith("Severity: ")).join(` +`);const l=r.search(/^<\w/m);l!==-1&&(r=r.slice(0,l)),r=r.trim();const a=w6e.exec(t),u=a?(()=>{const f=B8(a[1]??""),h=Number(f.bytes);return f.path!==void 0&&f.path!==""?{path:f.path,bytes:Number.isFinite(h)?h:void 0}:void 0})():void 0,c=C6e.exec(t),d=c?(()=>{const f=B8(c[1]??""),h=(c[2]??"").replace(/^\n/,""),m=h.indexOf(` +`),g=Z9(m===-1?"":h.slice(m+1)).replace(/\n$/,""),y=Number(f.bytes),k=Number(f.total_bytes);return{text:g,bytes:Number.isFinite(y)?y:void 0,totalBytes:Number.isFinite(k)?k:void 0,truncated:f.truncated==="true"?!0:f.truncated==="false"?!1:void 0}})():void 0;return{id:i.id??"",category:i.category??"",type:i.type??"",sourceKind:i.source_kind??"",sourceId:i.source_id??"",agentId:i.agent_id,title:Z9(o),severity:s,body:Z9(r),outputFile:u,outputPreview:d,raw:n}}function _6e(e){if(!e.includes("(/^Background (process|agent)$/.test(u.description)&&(u={...u,description:""}),u),r=E6e.exec(n);if(r?.[1]!==void 0&&r[2]!==void 0)return s({status:r[2]==="timed out"?"timed_out":r[2],description:r[1],reason:r[3],rest:o});const l=L6e.exec(n);if(l?.[1]!==void 0)return s({status:"killed",description:l[1],userStopped:l[2]!==void 0,reason:l[3],rest:o});const a=N6e.exec(n);if(a?.[1]!==void 0&&a[2]!==void 0)return s({status:a[2]==="was killed"?"killed":a[2]==="timed out"?"timed_out":a[2],description:a[1],reason:a[3],rest:o})}function D6e(e){if(!WU(e.title))return;const t=F6e(e.body);if(!(t===void 0||t.status!==_b(e)))return t}const R6e=1e6,MD=5e3;function hc(e){return e===""?[]:e.endsWith(` +`)?e.slice(0,-1).split(` +`):e.split(` +`)}const qU="\0";function TD(e){return e===""||e.endsWith(` +`)?e:`${e}${qU}`}function UU(e,t){const n=Ib(TD(e),TD(t));return n===null?null:n.map(i=>i.text.endsWith(qU)?{...i,text:i.text.slice(0,-1)}:i)}function Ib(e,t){const n=hc(e),i=hc(t),o=n.length,s=i.length;if(o===0&&s===0)return[];if(o>MD||s>MD||(o+1)*(s+1)>R6e)return null;const r=Array.from({length:o+1},()=>Array.from({length:s+1},()=>0));for(let h=1;h<=o;h++)for(let m=1;m<=s;m++)r[h][m]=n[h-1]===i[m-1]?r[h-1][m-1]+1:Math.max(r[h-1][m],r[h][m-1]);const l=[];let a=o,u=s;for(;a>0||u>0;)a>0&&u>0&&n[a-1]===i[u-1]?(l.push({type:"context",text:n[a-1]}),a--,u--):u>0&&(a===0||r[a][u-1]>=r[a-1][u])?(l.push({type:"add",text:i[u-1]}),u--):(l.push({type:"del",text:n[a-1]}),a--);l.reverse();const c=[];let d=1,f=1;for(const h of l)h.type==="context"?(c.push({type:"context",text:h.text,oldNo:d,newNo:f}),d++,f++):h.type==="add"?(c.push({type:"add",text:h.text,newNo:f}),f++):(c.push({type:"del",text:h.text,oldNo:d}),d++);return c}const ED=500;function LD(e,t){const n=[],i=hc(e),o=hc(t),s=Math.min(i.length,ED),r=Math.min(o.length,ED);for(let l=1;l<=s;l++)n.push({type:"del",text:i[l-1],oldNo:l});i.length>s&&n.push({type:"context",text:`… ${i.length-s} more lines …`});for(let l=1;l<=r;l++)n.push({type:"add",text:o[l-1],newNo:l});return o.length>r&&n.push({type:"context",text:`… ${o.length-r} more lines …`}),n}function O6e(e){let t=0,n=0;for(const i of e)i.type==="add"?t++:i.type==="del"&&n++;return{added:t,removed:n}}function td(e){const t=e;return t?.kind!=="user"||!Array.isArray(t.skillActivations)?[]:t.skillActivations.flatMap(n=>{if(typeof n!="object"||n===null)return[];const i=n;return typeof i.skillName!="string"?[]:[{name:i.skillName,...typeof i.skillArgs=="string"?{args:i.skillArgs}:{}}]})}function P6e(e){return{content:e.content,skillActivations:td(e.metadata?.origin)}}function X0(e,t){return e.length===t.length&&e.every((n,i)=>{const o=t[i];return o!==void 0&&n.name===o.name&&n.args===o.args})}const B6e=/^read[_-]?media(?:file)?$/i,$6e=/^data:([^;]+);base64,(.*)$/s,z6e=/^<(image|video|audio)\s+path="([^"]+)">$/,j6e=/^<(image|video|audio)\s+path="([^"]+)">(?:<\/\1>)?$/,H6e=/Mime type:\s*([^.\s]+)/i,W6e=/Size:\s*(\d+)\s*bytes/i,q6e=/Original dimensions:\s*(\d+)x(\d+)\s*pixels/i,U6e="Image compressed to fit model limits:",V6e=/Image compressed to fit model limits:[\s\S]*?<\/system>/g;function ND(e){return e.includes(U6e)?e.replace(V6e,""):e}function K6e(e){return e.replaceAll(""",'"').replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}function FD(e){const t=j6e.exec(e.trim());return t?{kind:t[1],path:K6e(t[2])}:null}const VU=/^f_(?:[0-9A-Za-z]{26}|[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})$/,Z6e=/f_(?:[0-9A-Za-z]{26}|[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})$/;function e6(e){const t=e.split(/[\\/]/).at(-1)??"",n=t.lastIndexOf("."),i=n>0?t.slice(0,n):t;return VU.test(i)?i:void 0}const Gc='Attached file "',KU=" — open it with the Read tool";function G6e(e,t,n,i){const o=`-${e}`,s=i.endsWith(o)?i.slice(0,-o.length):i,r=Z6e.exec(s)?.[0];return{name:e,mediaType:t,size:Number(n),fileId:r!==void 0&&VU.test(r)?r:void 0}}const ZU="attachmentRecords",Q6e=65536;function Y6e(e,t,n){const i=t+Gc.length,o=e.slice(i,n),s=o.indexOf('" (');if(s<=0)return!1;const r=o.indexOf(", ",s+3);if(r<=s+3)return!1;let l=i+r+2;if(l>=n||e.charCodeAt(l)<48||e.charCodeAt(l)>57)return!1;for(;l=48&&e.charCodeAt(l)<=57;)l++;return e.startsWith(" bytes): ",l)}function J6e(e,t,n){let i=e.indexOf(Gc,t);for(;i>=0&&i=n?n:s;if(Y6e(e,i,r))return i;if(s<0||s>=n)return-1;i=s}return-1}function X6e(e,t){const n=t+Gc.length,i=Math.min(e.length,n+Q6e),o=e.slice(n,i),s=o.indexOf('" (');if(s<=0)return null;const r=n+s,l=o.indexOf(", ",s+3);if(l<=s+3)return null;const a=n+l+2;let u=a;for(;u=48&&e.charCodeAt(u)<=57;)u++;if(u===a||!e.startsWith(" bytes): ",u))return null;const c=e.slice(a,u),d=u+9,f=J6e(e,r,i),h=f>=0?Math.min(f,i):i,m=e.slice(d,h),g=o.slice(0,s),y=`-${g}${KU}`;let k=m.lastIndexOf(y);for(;k>=0;){const C=m.slice(0,k),w=Math.max(C.lastIndexOf("/"),C.lastIndexOf("\\"));if(!/\s/.test(C.slice(w+1)))break;k=m.lastIndexOf(y,k-1)}if(k<0)return null;const v=m.slice(0,k+1+g.length);return{start:t,end:d+k+y.length,info:G6e(g,o.slice(s+3,l),c,v)}}function gS(e){if(!e.includes(KU))return[];const t=[];let n=e.indexOf(Gc);for(;n>=0;){const i=X6e(e,n);n=i?e.indexOf(Gc,i.end):e.indexOf(Gc,n+Gc.length),i&&t.push(i)}return t}function DD(e){const t=gS(e);if(t.length===0)return e;let n="",i=0;for(const o of t)n+=e.slice(i,o.start),i=o.end;return n+e.slice(i)}function e7e(e){const t=[];for(const o of e.content)o.type==="file"&&t.push({fileId:o.fileId,name:o.name});const n=[...t],i=e.metadata?.[ZU];if(Array.isArray(i))for(const o of i){if(typeof o!="object"||o===null)continue;const s=o.fileId,r=o.name,l={fileId:typeof s=="string"&&s.length>0?s:void 0,name:typeof r=="string"&&r.length>0?r:void 0},a=n.findIndex(u=>l.fileId!==void 0?u.fileId===l.fileId:u.fileId===void 0&&u.name===l.name);a>=0?n.splice(a,1):t.push(l)}return t.length>0?t:null}function t7e(e){const t=e7e(e);if(t)return{kind:"paired",records:t};let n=0;for(const s of e.content)if(s.type==="text")for(const r of t6(s.text))n=Math.max(n,r);const i=e.metadata?.origin;for(const s of[i?.skillArgs,i?.commandArgs])if(typeof s=="string")for(const r of t6(s))n=Math.max(n,r);if(n===0)return{kind:"legacy"};let o=0;for(const s of e.content)s.type==="text"&&(o+=gS(s.text).length);return{kind:"pill",keepLast:n,total:o}}function n7e(e){let t=0;const n=e.kind==="pill"?Math.max(0,e.total-e.keepLast):0;return i=>{const o=gS(i);if(o.length===0)return{notices:[],text:i};const s=[];for(const a of o){const u=t++;if(e.kind==="legacy")s.push(a);else if(e.kind==="pill")u>=n&&s.push(a);else{const c=a.info.fileId,d=e.records.findIndex(f=>c!==void 0?f.fileId===c:f.fileId===void 0&&f.name===a.info.name);d>=0&&(e.records.splice(d,1),s.push(a))}}if(s.length===0)return{notices:[],text:i};let r="",l=0;for(const a of s)r+=i.slice(l,a.start),l=a.end;return{notices:s.map(a=>a.info),text:r+i.slice(l)}}}const i7e=/(?=0&&e[i]==="\\";)n+=1,i-=1;return n%2===1}function GU(e){let t="",n=0,i=0;for(;i0?t:void 0}return[JSON.stringify(e)]}}function d7e(e,t){if(hr(e)==="task")for(const n of t??[]){const i=/^agent_id:\s*(\S+)\s*$/.exec(n);if(i?.[1])return i[1]}}function f7e(e,t){return{id:e.agentId??e.id,toolCallId:e.parentToolCallId,name:e.description,kind:e.kind,subagentType:e.subagentType,prompt:e.command??t,model:e.model,thinkingEffort:e.thinkingEffort,phase:e.status==="completed"?"completed":e.status==="failed"?"failed":e.status==="cancelled"?"cancelled":e.subagentPhase??"working",status:e.status,summary:e.outputPreview,outputLines:e.outputLines,text:e.text,suspendedReason:e.suspendedReason,swarmIndex:e.swarmIndex}}function QU(e){const t=e.display??{},n=typeof t.kind=="string"?t.kind:"";if(n==="diff"){const i=typeof t.path=="string"?t.path:"";if(Array.isArray(t.diff))return{kind:"diff",path:i,diff:t.diff};const o=typeof t.old_text=="string"?t.old_text:typeof t.before=="string"?t.before:void 0,s=typeof t.new_text=="string"?t.new_text:typeof t.after=="string"?t.after:void 0;if(o!==void 0&&s!==void 0){const r=UU(o,s)??LD(o,s);return{kind:"diff",path:i,diff:r}}return{kind:"diff",path:i,diff:[]}}if(n==="file_io"){const i=typeof t.path=="string"?t.path:"",o=typeof t.operation=="string"?t.operation:"";if(o==="write"&&typeof t.content=="string")return{kind:"file",path:i,content:t.content};if(o==="edit"&&typeof t.before=="string"&&typeof t.after=="string"){const r=Ib(t.before,t.after)??LD(t.before,t.after);return{kind:"diff",path:i,diff:r}}const s=typeof t.detail=="string"?t.detail:void 0;return{kind:"fileop",op:o||n,path:i,detail:s}}if(n==="shell"||n==="command"){const i=typeof t.command=="string"?t.command:e.action;return{kind:"shell",command:i,cwd:typeof t.cwd=="string"?t.cwd:void 0,danger:typeof t.danger=="string"?t.danger:Uae(i)}}if(n==="file_content"||n==="file")return{kind:"file",path:typeof t.path=="string"?t.path:"",content:typeof t.content=="string"?t.content:"",language:typeof t.language=="string"?t.language:void 0};if(n==="file_op"||n==="fileop")return{kind:"fileop",op:typeof t.operation=="string"?t.operation:typeof t.op=="string"?t.op:n,path:typeof t.path=="string"?t.path:"",detail:typeof t.detail=="string"?t.detail:void 0};if(n==="url_fetch"||n==="url")return{kind:"url",method:typeof t.method=="string"?t.method:void 0,url:typeof t.url=="string"?t.url:e.action};if(n==="search")return{kind:"search",query:typeof t.query=="string"?t.query:e.action,scope:typeof t.scope=="string"?t.scope:void 0};if(n==="invocation"||n==="agent_call"||n==="skill_call")return{kind:"invocation",kind2:typeof t.kind=="string"?t.kind:n,name:typeof t.name=="string"?t.name:e.toolName,description:typeof t.description=="string"?t.description:void 0};if(n==="todo"||n==="todo_list")return{kind:"todo",items:(Array.isArray(t.items)?t.items:[]).map(s=>{const r=s??{};return{title:typeof r.title=="string"?r.title:"",status:typeof r.status=="string"?r.status:"pending"}})};if(n==="plan_review"){const i=typeof t.plan=="string"?t.plan:"",o=typeof t.path=="string"?t.path:void 0,r=(Array.isArray(t.options)?t.options:[]).map(l=>{const a=l??{},u=typeof a.label=="string"?a.label:"";if(!u)return null;const c=typeof a.description=="string"?a.description:void 0;return{label:u,description:c}}).filter(l=>l!==null);return{kind:"plan_review",plan:i,path:o,options:r.length>0?r:void 0}}return{kind:"generic",summary:e.action}}function YU(e){const t=` +`,n=` +`,i=e.indexOf(t),o=e.lastIndexOf(n);return i>=0&&o>=i+t.length?e.slice(i+t.length,o):h7e(e)}function h7e(e){const t=e.split(` +`);return t.length>=2&&t[0]?.startsWith(""?t.slice(1,-1).join(` +`):e}function p7e(e){const t=e.metadata?.origin;if(t?.kind==="cron_job"||t?.kind==="cron_missed")return t.kind}function m7e(e){const t=e.content.filter(n=>n.type==="text").map(n=>n.text).join(` +`);return YU(t)}function g7e(e,t){const n=e.metadata?.origin??{},i=m7e(e);return t==="cron_missed"?{text:i,cron:{missedCount:typeof n.count=="number"?n.count:void 0}}:{text:i,cron:{jobId:typeof n.jobId=="string"?n.jobId:void 0,cron:typeof n.cron=="string"?n.cron:void 0,recurring:typeof n.recurring=="boolean"?n.recurring:void 0,coalescedCount:typeof n.coalescedCount=="number"?n.coalescedCount:void 0,stale:typeof n.stale=="boolean"?n.stale:void 0}}}function v7e(e,t,n){const{text:i,cron:o}=g7e(e,n);return{id:e.id,role:"cron",no:t,text:i,createdAt:e.createdAt,cron:o}}function y7e(e){const t=e.metadata?.origin,n=t?.kind;return n===void 0||n==="user"?!0:n==="skill_activation"||n==="plugin_command"?t?.trigger==="user-slash":!1}function k7e(e){const t=e.metadata?.["kimiWeb.steeredPromptIds"];if(Array.isArray(t)){const i=t.filter(o=>typeof o=="string"&&o.length>0);if(i.length>0)return i}if(e.promptId!==void 0&&e.promptId.length>0)return[e.promptId];const n=e.metadata?.["kimiWeb.promptId"];if(typeof n=="string"&&n.length>0)return[n]}function b7e(e){return e.metadata?.origin?.kind==="compaction_summary"}function w7e(e,t){return e===null?!1:e.promptId===void 0||t===void 0||e.promptId===t}function C7e(e){if(!e||e.length===0)return;const t="Plan saved to: ";for(const n of e)if(n.startsWith(t))return n.slice(t.length).trim()}function A7e(e){const t=[];for(const n of e){const i=t.at(-1);n.type==="text"&&i?.type==="text"?i.text+=n.text:n.type==="thinking"&&i?.type==="thinking"?i.thinking+=n.thinking:n.type==="thinking"?t.push({type:"thinking",thinking:n.thinking}):t.push({...n})}return JSON.stringify(t)}function iw(e,t,n,i=!0,o={},s={},r){const l=[];let a=r?.startNo??1;const u=r?.collect,c=new Map;for(const g of t)c.set(g.toolCallId,g);let d=null;function f(g=!1){if(!d)return;const y=d;if(d=null,!g&&y.blocks.length===0&&y.textParts.length===0&&y.thinkingParts.length===0&&y.tools.length===0)return;if(!g||!i)for(let C=0;CE.kind==="tool"&&E.tool.id===M.id);L&&L.kind==="tool"&&(L.tool=M)}const k=y.sources.find(C=>C.daemonTurnId!==void 0),v={id:y.id,sessionId:y.sources.find(C=>C.sessionId)?.sessionId||void 0,role:"assistant",no:a++,text:y.textParts.join(` +`),thinking:y.thinkingParts.length>0?y.thinkingParts.join(` +`):void 0,tools:y.tools.length>0?y.tools:void 0,blocks:y.blocks.length>0?y.blocks:void 0,approval:y.approval,approvalId:y.approvalId,durationMs:y.durationMs,createdAt:y.createdAt,endedAt:y.endedAt,goalContinuation:y.goalContinuation,daemonTurnId:k?.daemonTurnId,daemonTurnState:k?.daemonTurnState};l.push(v),u?.(v,y.sources)}function h(g,y){let k=null;for(const v of y)if(v.type==="text"){if(v.text){k==="text"?g.textParts[g.textParts.length-1]+=v.text:g.textParts.push(v.text);const C=g.blocks.at(-1);C&&C.kind==="text"?C.text+=(k==="text"?"":` +`)+v.text:g.blocks.push({kind:"text",text:v.text}),k="text"}}else if(v.type==="thinking"){if(v.thinking){k==="thinking"?g.thinkingParts[g.thinkingParts.length-1]+=v.thinking:g.thinkingParts.push(v.thinking);const C=g.blocks.at(-1);if(C&&C.kind==="thinking"){C.thinking+=(k==="thinking"?"":` +`)+v.thinking;const w=[C.startedAt,v.startedAt].filter(E=>E!==void 0).sort()[0],M=C.startedAt!==void 0&&C.durationMs===void 0||v.startedAt!==void 0&&v.durationMs===void 0,L=[C,v].flatMap(E=>E.startedAt!==void 0&&E.durationMs!==void 0?[Date.parse(E.startedAt)+E.durationMs]:[]);C.startedAt=w,C.durationMs=!M&&w!==void 0&&L.length>0?Math.max(...L)-Date.parse(w):void 0}else g.blocks.push({kind:"thinking",thinking:v.thinking,startedAt:v.startedAt,durationMs:v.durationMs});k="thinking"}}else if(v.type==="toolUse"){k=null;const C=c.get(v.toolCallId),w=v.toolName==="ExitPlanMode"?s[v.toolCallId]:void 0,M={id:v.toolCallId,name:v.toolName,arg:typeof v.input=="string"?v.input:JSON.stringify(v.input),agentId:hr(v.toolName)==="task"?v.agentRefs?.find(L=>L.role!=="member")?.agentId??v.agentRefs?.[0]?.agentId:void 0,status:"running",output:v.outputLines,plan:w,planPath:v.toolName==="ExitPlanMode"?w?.path??o[v.toolCallId]?.path:void 0};g.tools.push(M),g.blocks.push({kind:"tool",tool:M}),C&&(g.approval=QU(C),g.approvalId=C.approvalId)}else if(v.type==="toolResult"){k=null;const C=g.tools.findIndex(w=>w.id===v.toolCallId);if(C!==-1){const w=g.tools[C],M=vS(v.output),L={...w,status:v.isError?"error":"ok",output:M,media:v.isError?void 0:c7e(w.name,v.output),agentId:w.agentId??d7e(w.name,M)};L.name==="ExitPlanMode"&&!L.planPath&&(L.planPath=C7e(L.output)),g.tools[C]=L;const E=g.blocks.find(S=>S.kind==="tool"&&S.tool.id===v.toolCallId);E&&E.kind==="tool"&&(E.tool=L)}}else k=null}function m(g,y){if(g.type==="image"||g.type==="video"){const k=g.type,v=g.source;if(v.kind==="url")return{url:v.url,kind:k};if(v.kind==="base64")return{url:`data:${v.mediaType};base64,${v.data}`,kind:k};if(v.kind==="file"&&n)return{url:n(v.fileId),kind:k,fileId:v.fileId};if(v.kind==="sessionMedia")return{url:r?.getSessionMediaUrl?.(y,v.fileId)??"",kind:k,fileId:v.fileId,sessionId:y}}if(g.type==="file"&&n){if(g.mediaType.startsWith("image/"))return{url:n(g.fileId),kind:"image",fileId:g.fileId};if(g.mediaType.startsWith("video/"))return{url:n(g.fileId),kind:"video",fileId:g.fileId}}}for(const g of e){if(g.role==="system")continue;if(b7e(g)){f();const w=g.metadata?.[tj],M={id:g.id,role:"compaction",no:a,text:g.content.filter(L=>L.type==="text").map(L=>L.text).join(` +`),compaction:{trigger:w?.trigger,tokensBefore:w?.tokensBefore,tokensAfter:w?.tokensAfter}};l.push(M),u?.(M,[g]);continue}if(g.role==="user"){const w=p7e(g),M=g.metadata?.origin?.kind,L=M==="skill_activation"&&g.metadata?.origin?.trigger!=="user-slash";if(w===void 0&&(M==="injection"||L))continue;if(w===void 0&&(M==="task"||M==="background_task"||M==="task_notification")){const J=g.content.filter(ue=>ue.type==="text").map(ue=>ue.text).join(` +`),U=I6e(g.metadata),Q=U!==void 0?[U]:_6e(J);if(Q.length>0){d??={id:g.id,promptId:void 0,textParts:[],thinkingParts:[],tools:[],blocks:[],approval:void 0,approvalId:void 0,seenSigs:new Set,sources:[g],createdAt:g.createdAt};for(const ue of Q)d.blocks.push({kind:"notification",notification:{...ue,createdAt:g.createdAt}})}continue}if(f(),w!==void 0){const J=v7e(g,a++,w);l.push(J),u?.(J,[g]);continue}if(M==="system_trigger"&&g.metadata?.origin?.name==="goal_continuation"){d={id:g.id,promptId:void 0,textParts:[],thinkingParts:[],tools:[],blocks:[],approval:void 0,approvalId:void 0,seenSigs:new Set,sources:[g],createdAt:g.createdAt,goalContinuation:!0};continue}if(!y7e(g))continue;const E=g.metadata?.origin,S=E?.kind==="skill_activation"&&E?.trigger==="user-slash",x=E?.kind==="plugin_command"&&E?.trigger==="user-slash",A=P6e(g),T=A.skillActivations,I=A.content,O=[];let H=[];const R=n7e(t7e(g)),F=new Set,P=J=>{const U={kind:"file",url:J.fileId&&n?n(J.fileId):"",fileId:J.fileId,name:J.name,mediaType:J.mediaType,size:J.size};H.push(U),F.add(U)};for(const J of I){if(J.type==="text")if(S){const Q=FD(J.text);if(Q&&(Q.kind==="video"||Q.kind==="image")&&n){const ue=e6(Q.path);if(ue){H.push({url:n(ue),kind:Q.kind,fileId:ue});continue}}for(const ue of R(J.text).notices)P(ue)}else if(x)O.push(E.commandArgs??"");else{const Q=FD(J.text);if(Q&&(Q.kind==="video"||Q.kind==="image")&&n){const pe=e6(Q.path);if(pe){H.push({url:n(pe),kind:Q.kind,fileId:pe});continue}}const ue=R(J.text);if(ue.notices.length>0){for(const ee of ue.notices)P(ee);if(ue.text.trim().length===0)continue;const pe=ND(ue.text);if(pe!==ue.text&&pe.trim().length===0)continue;O.push(pe);continue}const me=ND(J.text);if(me!==J.text&&me.trim().length===0)continue;O.push(me)}const U=m(J,g.sessionId);if(U){H.push({url:U.url,kind:U.kind,name:J.type==="file"?J.name:void 0,fileId:U.fileId,sessionId:U.sessionId});continue}J.type==="file"&&n&&H.push({kind:"file",url:n(J.fileId),fileId:J.fileId,name:J.name,mediaType:J.mediaType||void 0,size:J.size})}const z=new Map;for(const J of F){if(J.fileId===void 0)continue;const U=`${J.kind}|${J.fileId}`;z.set(U,(z.get(U)??0)+1)}H=H.filter(J=>{if(F.has(J)||J.fileId===void 0)return!0;const U=`${J.kind}|${J.fileId}`,Q=z.get(U)??0;return Q>0?(z.set(U,Q-1),!1):!0});const W=S?E?.skillArgs??"":O.join(` +`),$=t6(W),K=r7e(W),ne=H.filter(J=>J.kind==="file"),G=H.filter(J=>J.kind==="image"||J.kind==="video"),te=[...$].some(J=>J<=ne.length),le=[...K].some(J=>J<=G.length),ie=te||le?H:[];let _e=0,Z=0;const se=H.filter(J=>J.kind==="file"?(_e+=1,!(te&&$.has(_e))):J.kind==="image"||J.kind==="video"?(Z+=1,!(le&&K.has(Z))):!0),he=g.metadata?.["kimiWeb.steeredPromptIds"],Y={id:g.id,role:"user",no:a++,text:W,hasUndoAnchor:g.metadata?.["kimiWeb.settledWithoutEcho"]===!0||g.metadata?.["kimiWeb.steered"]===!0?!1:void 0,steered:g.metadata?.["kimiWeb.steered"]===!0||Array.isArray(he)&&he.length>0?!0:void 0,promptIds:k7e(g),attachments:se.length>0?se:void 0,inlineAttachments:ie.length>0?ie:void 0,skillActivation:S?{name:E.skillName,args:E.skillArgs}:void 0,skillActivations:T.length>0?T.map(J=>({name:J.name,args:J.args})):void 0,pluginCommand:x?{pluginId:E.pluginId,commandName:E.commandName,args:E.commandArgs}:void 0,createdAt:g.createdAt};l.push(Y),u?.(Y,[g]);continue}if(g.role==="tool"){d&&(d.sources.push(g),h(d,g.content),d.endedAt=g.createdAt);continue}const y=g.promptId;w7e(d,y)?d!==null&&d.promptId===void 0&&y!==void 0&&(d.promptId=y):(f(),d={id:g.id,promptId:y,textParts:[],thinkingParts:[],tools:[],blocks:[],approval:void 0,approvalId:void 0,seenSigs:new Set,sources:[],durationMs:g.durationMs,createdAt:g.createdAt});const v=d;if(v===null)continue;const C=A7e(g.content);v.promptId!==void 0&&v.seenSigs.has(C)||(v.seenSigs.add(C),v.sources.push(g),g.durationMs!==void 0&&(v.durationMs=g.durationMs),h(v,g.content),g.endedAt!==void 0?v.endedAt=g.endedAt:g.id!==v.id&&(v.endedAt=g.createdAt))}return f(!0),l}function JU(e,t,n){return e.state==="running"&&e.frames.at(-1)===t&&!n}function x7e(e,t){if(t.size===0)return;let n=!1;for(const l of t.values())if(l.settledAt===void 0){n=!0;break}if(!n)return;const i=new Date().toISOString(),o=e.items.findLast(l=>l.kind==="turn"&&l.state==="running"),s=o?.kind==="turn"?o.steps.findLast(l=>l.state==="running"):void 0,r=e.interactions.some(l=>l.state==="pending");for(const l of e.items)if(l.kind==="turn")for(const a of l.steps){const u=r&&a===s;for(const c of a.frames){if(c.kind!=="thinking")continue;const d=t.get(c.frameId);d===void 0||d.settledAt!==void 0||JU(a,c,u)||(d.settledAt=i)}}}function S7e(e,t){if(t.size===0)return;const n=new Set;for(const i of e.items)if(i.kind==="turn")for(const o of i.steps)for(const s of o.frames)s.kind==="thinking"&&n.add(s.frameId);for(const i of[...t.keys()])n.has(i)||t.delete(i)}function _7e(e,t,n,i){const o=e.items.filter(f=>f.kind==="turn"),s=o[0]?.turnId,r=o.length===1?s:void 0,l=new Map(e.tasks.map(f=>[f.taskId,f])),a=new Map(e.prompts.map(f=>[f.promptId,f])),u=eV(e.prompts,XU(e.items)),c=e.items.flatMap(f=>f.kind==="turn"?yS(f,e.attachments,l,f.turnId===s?n?.createdAt:void 0,f.turnId===r?n?.disposedAt:void 0,i?.sessionId,{promptById:a,promptForTurn:u}):[]),d=e.meta.activity==="turn";return iw(c,[],t,d,{},{},{getSessionMediaUrl:i?.getSessionMediaUrl}).map(L7e)}function RD(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n!="object"||n===null)continue;const i=n;if(i.type!=="file")continue;const o=typeof i.fileId=="string"?i.fileId:i.file_id;t.push({fileId:typeof o=="string"?o:void 0,name:typeof i.name=="string"?i.name:void 0})}return t}function OD(e,t){return t.length===0?e:{...e,[ZU]:t}}const I7e=new Set(["user","skill_activation","plugin_command"]);function M7e(e){return(e.origin.payload??e.origin)?.kind}function T7e(e){const t=e.content;if(!Array.isArray(t))return;const n=[];for(const i of t)if(typeof i=="object"&&i!==null&&i.type==="text"){const o=i.text;typeof o=="string"&&n.push(o)}return n.join("")}function XU(e){const t=new Set;for(const n of e)if(n.kind==="turn"){for(const i of n.steps)for(const o of i.frames)if(o.kind==="text")for(const s of o.promptIds??[])t.add(s)}return t}function eV(e,t){const n=new Set(t??[]);return i=>{const o=M7e(i);if(o!==void 0&&!I7e.has(o)||i.prompt===void 0&&(i.attachmentIds??[]).length===0)return;const s=DD(i.prompt??"");for(const r of e){if(n.has(r.promptId))continue;const l=T7e(r);if(l!==void 0&&DD(l)===s)return n.add(r.promptId),r}}}function yS(e,t,n,i,o,s="",r){const l=[],a=new Map(t.map(k=>[k.attachmentId,k])),u=n6([e.startedAt,...e.steps.map(k=>k.startedAt),i])??"",c=PD(e.endedAt)??PD(o),d=e.triggerPromptId??e.turnId,f=e.origin.payload??e.origin,h=(e.attachmentIds??[]).length>0,m=r?.includeOrigin===!0&&td(f).length>0;if(e.prompt!==void 0&&e.prompt.length>0||h||m){const k=e.prompt!==void 0&&e.prompt.length>0?[{type:"text",text:e.prompt}]:[];for(const v of e.attachmentIds??[]){const C=BD(a.get(v));C!==void 0&&k.push(C)}l.push({id:`${e.turnId}:input`,sessionId:s,role:"user",content:k,createdAt:u,promptId:d,metadata:OD(r?.includeOrigin===!0||e.origin.kind==="task"&&(e.prompt??"").includes("0;if(v.role==="user"){if(v.taskId!==void 0){if(v.text.length===0&&!C)continue;const A=E7e(v.taskId,v.text,n.get(v.taskId));l.push({id:v.frameId,sessionId:s,role:"user",content:[{type:"text",text:v.text}],createdAt:k.startedAt??u,promptId:d,metadata:{origin:{kind:"task",taskId:v.taskId},[HU]:A}});continue}const w=v.text.length>0?[{type:"text",text:v.text}]:[];for(const A of v.attachmentIds??[]){const T=BD(a.get(A));T!==void 0&&w.push(T)}const M=v.promptIds?.map(A=>r?.promptById?.get(A)).find(A=>A!==void 0),L=[];for(const A of v.promptIds??[])L.push(...RD(r?.promptById?.get(A)?.content));const E=v.origin,S=td(E);if(v.text.length===0&&!C&&S.length===0)continue;const x={...S.length>0?{origin:E}:{},...(v.promptIds?.length??0)>0?{"kimiWeb.steeredPromptIds":v.promptIds}:{}};l.push({id:v.frameId,sessionId:s,role:"user",content:w,createdAt:M?.createdAt??k.startedAt??u,promptId:d,metadata:OD(Object.keys(x).length>0?x:void 0,L)});continue}if(v.text.length===0&&!C)continue;l.push({id:v.frameId,sessionId:s,role:"assistant",content:[{type:"text",text:v.text}],createdAt:k.startedAt??u,promptId:d})}else if(v.kind==="thinking"){if(v.text.length===0)continue;const C=r?.pendingInteractionAtByStepId?.get(k.stepId),w=JU(k,v,C!==void 0),M=r?.thinkingTiming,L=M?.get(v.frameId);let E,S;if(L!==void 0)L.settledAt===void 0&&!w&&(L.settledAt=new Date().toISOString()),E=L.startedAt,S=$8(L.startedAt,L.settledAt);else if(M!==void 0&&w){const x=new Date().toISOString();M.set(v.frameId,{startedAt:x}),E=x}else E=k.startedAt,S=$8(k.startedAt,n6([k.endedAt,C]));l.push({id:v.frameId,sessionId:s,role:"assistant",content:[{type:"thinking",thinking:v.text,startedAt:E,durationMs:S}],createdAt:k.startedAt??u,promptId:d})}else v.kind==="tool"&&(l.push({id:`${v.frameId}:call`,sessionId:s,role:"assistant",content:[{type:"toolUse",toolCallId:v.toolCallId,toolName:v.name,input:v.input??v.display??{},outputLines:v.state==="running"?vS(v.output):void 0,agentRefs:v.agentRefs}],createdAt:k.startedAt??u,promptId:d}),v.state!=="running"&&l.push({id:`${v.frameId}:result`,sessionId:s,role:"tool",content:[{type:"toolResult",toolCallId:v.toolCallId,output:v.output??v.error??"",isError:v.state==="error"}],createdAt:k.endedAt??k.startedAt??u,promptId:d}));const g=e.durationMs??$8(u||void 0,c),y=l.findLastIndex(k=>k.role==="assistant");y>=0&&(g!==void 0||c!==void 0)&&(l[y]={...l[y],durationMs:g,endedAt:c??l[y].endedAt});for(const k of l)k.daemonTurnId=e.ordinal,k.daemonTurnState=e.state;return l}function E7e(e,t,n){const[i="",...o]=t.split(` +`),s=n?.state??"info";return{id:`task:${e}:${s}`,category:"task",type:`task.${s}`,sourceKind:n?.kind==="subagent"?"subagent":"background_task",sourceId:e,agentId:n?.agentId,title:i.trim(),severity:s==="completed"?"info":"warning",body:o.join(` +`).trim(),raw:t}}function L7e(e){if(e.createdAt!==""&&e.endedAt!=="")return e;const t={...e};return t.createdAt===""&&delete t.createdAt,t.endedAt===""&&delete t.endedAt,t}function n6(e){let t;for(const n of e){if(n===void 0)continue;const i=Date.parse(n);Number.isFinite(i)&&(t===void 0||i=0?n:void 0}const $D=6e3,Im=256*1024,N7e=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;function zD(e,t){return t===0?e:e-1}function F7e(e,t){const n=hc(t),i=[];let o=0;for(const s of e){if(s.type==="hunk"){const r=N7e.exec(s.text);if(!r)return null;const l=zD(Number(r[1]),r[2]===void 0?1:Number(r[2])),a=zD(Number(r[3]),r[4]===void 0?1:Number(r[4]));if(an.length)return null;for(;o=n.length||n[o]!==s.text)return null;o++,s.type==="context"&&i.push(s.text)}for(;oIm||hc(n).length>$D)return null;const i=F7e(e,n);return i===null||i.length>Im||hc(i).length>$D?null:{before:i,after:n}}const R7e=new Set(["assistantDelta","agentDelta","toolOutput","taskProgress"]);function O7e(e){return R7e.has(e.type)}const P7e=50,B7e=100,i6=32*1024,$7e={requestFrame(e){return typeof requestAnimationFrame=="function"?requestAnimationFrame(e):null},cancelFrame(e){typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(e)},requestTask(e){return setTimeout(e,P7e)},cancelTask(e){clearTimeout(e)}};function z7e(e,t,n={}){const i=n.scheduler??$7e,o=Math.max(1,Math.floor(n.maxItemsPerSlice??B7e)),s=[];let r=0,l=null,a=null,u=0,c=!1;const d=()=>s.length-r,f=()=>{u+=1,l!==null&&(i.cancelFrame(l),l=null),a!==null&&(i.cancelTask(a),a=null)},h=()=>{r===s.length?(s.length=0,r=0):r>=1024&&(s.splice(0,r),r=0)};let m;const g=()=>{if(c||l!==null||a!==null||d()===0)return;const k=++u,v=()=>{k===u&&m()};l=i.requestFrame(v),a=i.requestTask(v)};m=()=>{f();let k=0;for(;!c&&k{if(!c){if(t(k)){const v=s.length>r?s.at(-1):void 0,C=v===void 0?void 0:n.coalesce?.(v,k);C===void 0?s.push(k):s[s.length-1]=C,g();return}if(d()===0){e(k);return}s.push(k),m()}});return y.flush=()=>{if(!c){for(f();!c&&r{if(c||d()===0)return;let v=r;for(let C=r;C{c||(c=!0,f(),s.length=0,r=0)},y}function o6(e){if(e.type==="assistantDelta"){if(e.delta.text!==void 0&&e.delta.thinking===void 0)return{kind:"text",value:e.delta.text};if(e.delta.thinking!==void 0&&e.delta.text===void 0)return{kind:"thinking",value:e.delta.thinking}}}function j7e(e){if(e.appEvent.type!=="assistantDelta")return[e];const t=e.appEvent,n=e.meta.stream,i=o6(t);if(n===void 0||i===void 0||n.kind!==i.kind||i.value.length<=i6)return[e];const o=[];let s=0;for(;ss&&/[\uD800-\uDBFF]/u.test(i.value[r-1])&&/[\uDC00-\uDFFF]/u.test(i.value[r])&&(r-=1);const l=i.value.slice(s,r);o.push({appEvent:{...t,delta:i.kind==="text"?{text:l}:{thinking:l}},meta:{...e.meta,stream:{...n,offset:n.offset+s}}}),s=r}return o}function H7e(e,t){if(e.appEvent.type!=="assistantDelta"||t.appEvent.type!=="assistantDelta")return;const n=e.meta.stream,i=t.meta.stream,o=o6(e.appEvent),s=o6(t.appEvent);if(n===void 0||i===void 0||o===void 0||s===void 0||e.meta.sessionId!==t.meta.sessionId||e.appEvent.sessionId!==t.appEvent.sessionId||e.appEvent.messageId!==t.appEvent.messageId||e.appEvent.contentIndex!==t.appEvent.contentIndex||n.turnId!==i.turnId||n.kind!==i.kind||o.kind!==s.kind||n.kind!==o.kind||i.kind!==s.kind||i.offset!==n.offset+o.value.length||o.value.length+s.value.length>i6)return;const r=o.value+s.value;return{appEvent:{...e.appEvent,delta:o.kind==="text"?{text:r}:{thinking:r}},meta:{...t.meta,stream:{...n}}}}function tV(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&t.type==="text").map(t=>t.text).join(""):""}function W7e(e){for(let t=e.items.length-1;t>=0;t--){const n=e.items[t];if(n.kind==="marker"){const i=n.at;if(typeof i=="string")return i;continue}if(n.kind==="turn"){let i;const o=s=>{typeof s=="string"&&(i===void 0||s>i)&&(i=s)};o(n.endedAt),o(n.startedAt);for(const s of n.steps)o(s.endedAt),o(s.startedAt);if(i!==void 0)return i}}}function q7e(e,t){if(t===void 0)return;const n=e.find(i=>i.kind==="turn"&&i.turnId===t);return n?.kind==="turn"?n.startedAt:void 0}function wp(e,t){const n=q7e(e,t?.["kimiWeb.anchorTurnId"]),i=t?.["kimiWeb.anchorPromptCreatedAt"];return typeof i=="string"&&(n===void 0||i>=n)?{at:i,exclusive:!0}:n!==void 0?{at:n,exclusive:!1}:void 0}function kS(e,t,n){const i=new Map,o=new Set(n??[]);for(const s of e){if(s.skills.length>0)continue;const r=t.find(l=>!o.has(l.promptId)&&l.status!=="queued"&&(s.floor===void 0||(s.floor.exclusive?l.createdAt>s.floor.at:l.createdAt>=s.floor.at))&&tV(l.content)===s.text);r!==void 0&&(o.add(r.promptId),i.set(s.id,r.promptId))}return i}function bS(e,t,n){const i=[];for(const r of t.items){if(r.kind!=="turn")continue;const l=td(r.origin.payload);l.length>0&&i.push({id:`turn:${r.turnId}`,text:r.prompt??"",attachmentCount:r.attachmentIds?.length??0,at:r.startedAt,skills:l})}const o=new Map,s=new Set(n??[]);for(const r of e){const l=i.find(a=>s.has(a.id)||r.floor!==void 0&&(a.at===void 0||(r.floor.exclusive?a.at<=r.floor.at:a.atr.kind==="turn"&&r.turnId===t);return t!==void 0&&s===-1?!1:e.slice(s+1).some(r=>{if(r.kind!=="marker"||r.marker!=="skill")return!1;if(o!==void 0){const a=r.at;if(typeof a!="string"||a<=o)return!1}const l=r.payload?.origin;return l?.kind==="skill_activation"&&l.skillName===n&&l.skillArgs===i})}function nV(e,t,n,i,o){const s=t===void 0?-1:e.findIndex(r=>r.kind==="turn"&&r.turnId===t);return t!==void 0&&s===-1?!1:e.slice(s+1).some(r=>{if(r.kind!=="turn"||o?.terminalOnly===!0&&r.state==="running")return!1;const l=r.origin.payload??r.origin;return l.kind==="skill_activation"&&l.skillName===n&&l.skillArgs===i})}function wS(e,t,n){const i=new Map,o=new Set(n??[]);for(const s of e){const r=s.anchorTurnId===void 0?-1:t.findIndex(a=>a.kind==="turn"&&a.turnId===s.anchorTurnId);if(s.anchorTurnId!==void 0&&r===-1)continue;const l=t.slice(r+1).find(a=>{if(a.kind==="turn"){if(o.has(a.turnId))return!1;const u=a.origin.payload??a.origin;return u.kind==="skill_activation"&&u.skillName===s.skillName&&u.skillArgs===s.skillArgs}if(a.kind==="marker"&&a.marker==="skill"){if(o.has(a.markerId))return!1;if(s.promptFloor!==void 0){const c=a.at;if(typeof c!="string"||c<=s.promptFloor)return!1}const u=a.payload?.origin;return u?.kind==="skill_activation"&&u.skillName===s.skillName&&u.skillArgs===s.skillArgs}return!1});if(l!==void 0){const a=l.kind==="turn"?l.turnId:l.markerId;o.add(a),i.set(s.id,a)}}return i}function Qs(e){return td(e?.origin)}function s6(e,t){const n=Qs(e.metadata);if(n.length===0)return!1;const i=e.content.filter(u=>u.type==="text").map(u=>"text"in u?u.text:"").join(""),o=e.content.filter(u=>u.type!=="text").length,s=e.metadata?.["kimiWeb.promptId"];if(s!==void 0)return t.items.some(c=>c.kind==="turn"&&c.steps.some(d=>d.frames.some(f=>f.kind==="text"&&f.role==="user"&&(f.promptIds?.includes(s)??!1)&&X0(td(f.origin),n))))?!0:t.items.some(c=>c.kind==="turn"&&c.triggerPromptId===s&&(c.prompt??"")===i&&(c.attachmentIds?.length??0)===o&&X0(td(c.origin.payload),n));const r=e.metadata?.["kimiWeb.anchorTurnId"],l=r===void 0?-1:t.items.findIndex(u=>u.kind==="turn"&&u.turnId===r);return r!==void 0&&l===-1?!1:(l===-1?t.items:t.items.slice(l+1)).some(u=>u.kind==="turn"&&(u.prompt??"")===i&&(u.attachmentIds?.length??0)===o&&X0(td(u.origin.payload),n))}function V7e(e,t){const i=e.items.filter(h=>h.kind==="turn")[0]?.turnId,o=new Map(e.tasks.map(h=>[h.taskId,h])),s=new Map(e.prompts.map(h=>[h.promptId,h])),r=eV(e.prompts,XU(e.items)),l=h=>h.kind==="turn"?h.origin.payload??h.origin:void 0,a=new Set,u=K7e(e.items),c=e.items.flatMap((h,m)=>{if(h.kind==="turn"){const g=u.turnPart.get(m)??h,y=g.startedAt!==void 0||g.steps.some(k=>k.startedAt!==void 0);return jD(g,e.attachments,o,h.turnId===i&&!y&&e.hasMoreOlder!==!0?t.agentCreatedAt:void 0,void 0,t.sessionId,t.pendingInteractionAtByStepId,t.thinkingTiming,s,r)}if(h.kind==="marker"&&h.marker==="compaction"){const g=Z7e(h.payload,h.at,t.sessionId,h.markerId,Q7e(e.items,m));if(g===void 0)return[];const y=u.continuation.get(h.markerId);return y===void 0?[g]:[g,...jD(y,e.attachments,o,void 0,void 0,t.sessionId,t.pendingInteractionAtByStepId,t.thinkingTiming,s,r,!0,`:${h.markerId}`)]}if(h.kind==="marker"&&h.marker==="cron.fired"){const g=h.payload,y=g?.origin?.jobId,k=typeof g?.prompt=="string"?g.prompt:void 0,v=e.items.slice(m+1).find(w=>{if(w.kind!=="turn"||a.has(w.turnId))return!1;const M=l(w);return M?.kind==="cron_job"&&(y===void 0||M.jobId===y)&&(k===void 0||w.kind==="turn"&&YU(w.prompt??"")===k)});if(v!==void 0&&v.kind==="turn")return a.add(v.turnId),[];const C=G7e(h.payload,h.at,t.sessionId,h.markerId);return C===void 0?[]:[C]}return[]}),d=e.interactions.map(h=>_1(h,t.sessionId)).filter(h=>h!==void 0),f=e.meta.activity==="turn";return iw(c,d,t.getFileUrl,f,t.planReviewByToolCallId??{},t.plansByToolCallId??{},{getSessionMediaUrl:t.getSessionMediaUrl}).map(X7e)}function K7e(e){const t=new Map,n=new Map;for(let i=0;i[]);let a=-1;for(const u of o.steps){for(;a+1=s[a+1].at;)a+=1;a<0?r.push(u):l[a].push(u)}if(r.length!==o.steps.length){t.set(i,{...o,steps:r,endedAt:r.at(-1)?.endedAt,durationMs:void 0});for(let u=0;ug.startedAt),i])??"",promptId:e.turnId,daemonTurnId:e.ordinal,daemonTurnState:e.state,metadata:{origin:f}}]:[],...yS(e,t,n,i,o,s,{includeOrigin:c!==!0,pendingInteractionAtByStepId:r,thinkingTiming:l,promptById:a,promptForTurn:u})]}function Z7e(e,t,n,i,o){const s=e;if(s?.phase!=="completed")return;const r=s.result??{},l={trigger:o,tokensBefore:typeof r.tokensBefore=="number"?r.tokensBefore:void 0,tokensAfter:typeof r.tokensAfter=="number"?r.tokensAfter:void 0};return{id:i,sessionId:n,role:"assistant",content:typeof r.summary=="string"?[{type:"text",text:r.summary}]:[],createdAt:t??"",metadata:{origin:{kind:"compaction_summary"},[tj]:l}}}function G7e(e,t,n,i){const o=e,s=o?.origin;if(!(s?.kind!=="cron_job"||typeof o?.prompt!="string"))return{id:i,sessionId:n,role:"user",content:[{type:"text",text:o.prompt}],createdAt:t??"",metadata:{origin:s}}}function Q7e(e,t){for(let n=t-1;n>=0;n--){const i=e[n];if(i?.kind!=="marker"||i.marker!=="compaction")continue;const o=i.payload;if(o?.phase==="started")return o.trigger==="manual"?"manual":"auto"}return"auto"}function _1(e,t){if(e.interactionKind!=="approval"||e.state!=="pending")return;const n=e.request??{};if(typeof n.toolName!="string"||typeof n.action!="string")return;const i=typeof e.toolCallId=="string"?e.toolCallId:typeof n.toolCallId=="string"?n.toolCallId:void 0;if(i!==void 0)return{approvalId:e.interactionId,sessionId:t,turnId:typeof n.turnId=="number"?n.turnId:void 0,toolCallId:i,toolName:n.toolName,action:n.action,display:n.display,expiresAt:"",createdAt:""}}function Hg(e,t){if(e.interactionKind!=="question"||e.state!=="pending")return;const n=e.request??{};if(!Array.isArray(n.questions))return;const i=typeof e.toolCallId=="string"?e.toolCallId:typeof n.toolCallId=="string"?n.toolCallId:typeof n.tool_call_id=="string"?n.tool_call_id:void 0;return{questionId:e.interactionId,sessionId:t,turnId:typeof n.turnId=="number"?n.turnId:typeof n.turn_id=="number"?n.turn_id:void 0,toolCallId:i,questions:n.questions.map(Y7e),createdAt:""}}function Y7e(e){const t=Array.isArray(e.options)?e.options:[];return{id:typeof e.id=="string"?e.id:"",question:typeof e.question=="string"?e.question:"",header:typeof e.header=="string"?e.header:void 0,body:typeof e.body=="string"?e.body:void 0,options:t.map(J7e),multiSelect:e.multi_select===!0,allowOther:e.allow_other===!0,otherLabel:typeof e.other_label=="string"?e.other_label:void 0,otherDescription:typeof e.other_description=="string"?e.other_description:void 0}}function J7e(e){const t=e??{};return{id:typeof t.id=="string"?t.id:"",label:typeof t.label=="string"?t.label:"",description:typeof t.description=="string"?t.description:void 0,recommended:t.recommended===!0||t.is_recommended===!0}}function X7e(e){if(e.createdAt!==""&&e.endedAt!=="")return e;const t={...e};return t.createdAt===""&&delete t.createdAt,t.endedAt===""&&delete t.endedAt,t}function exe(){let e=[];const t=(n,i)=>{const s=V7e(n,i).map((r,l)=>{const a=JSON.stringify(r),u=e[l],c=u!==void 0&&u.fingerprint===a?u.turn:r;return e[l]={turn:c,fingerprint:a},c});return e.length=s.length,s};return t.reset=()=>{e=[]},t}function iV(e){if(e instanceof Error)return typeof e.stack=="string"&&e.stack?e.stack:e.message?`${e.name}: ${e.message}`:e.name;if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function txe(e){if(e instanceof Error)return{name:e.name,message:e.message};const t=e;return{name:typeof t?.name=="string"?t.name:void 0,message:typeof t?.message=="string"?t.message:void 0}}function nxe(e){return e instanceof Error&&typeof e.stack=="string"&&e.stack?e.stack:void 0}function ixe(e){if(!(typeof e!="number"||!Number.isFinite(e)))return new Date(e).toISOString()}function HD(e){if(!(typeof e!="number"||!Number.isFinite(e)))return`${Math.round(e)}ms`}function oxe(e,t,n){const i=lxe(e),o=rxe(e),s=new Map(e.prompts.map(d=>[d.promptId,d])),r=n.filter(d=>{const f=d.metadata?.["kimiWeb.promptId"];if(f===void 0||o===void 0)return!0;const h=s.get(f)?.steeredAt;return h===void 0||h>=o}),l=e.prompts.filter(sxe).filter(d=>!i.has(d.promptId)).filter(d=>o===void 0||d.steeredAt>=o);if(l.length===0)return[...r];l.sort((d,f)=>d.steeredAtt)&&(t=n.startedAt);return t}function lxe(e){const t=new Set;for(const n of e.items)if(n.kind==="turn"){for(const i of n.steps)for(const o of i.frames)if(!(o.kind!=="text"||o.role!=="user"))for(const s of o.promptIds??[])t.add(s)}return t}function axe(e){return Array.isArray(e)?e.map(t=>Q4(t)).filter(t=>t.type!=="text"||t.text.length>0):[]}function uxe(e){return e.startsWith("diff --git")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ ")||e.startsWith("new file mode")||e.startsWith("deleted file mode")||e.startsWith("old mode")||e.startsWith("new mode")||e.startsWith("similarity index")||e.startsWith("dissimilarity index")||e.startsWith("rename from")||e.startsWith("rename to")||e.startsWith("copy from")||e.startsWith("copy to")||e.startsWith("Binary files")}function cxe(e){const t=[];if(!e)return t;let n=0,i=0,o=!1;for(const s of e.split(` +`)){if(s.startsWith("diff --git")){o=!1;continue}if(!o&&uxe(s))continue;if(s.startsWith("@@")){const a=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(s);a&&(n=Number.parseInt(a[1],10),i=Number.parseInt(a[2],10)),o=!0,t.push({type:"hunk",text:s});continue}if(!o||s.startsWith("\\"))continue;const r=s.charAt(0),l=s.slice(1);r==="+"?(t.push({type:"add",text:l,newNo:i}),i+=1):r==="-"?(t.push({type:"del",text:l,oldNo:n}),n+=1):r===" "&&(t.push({type:"context",text:l,oldNo:n,newNo:i}),n+=1,i+=1)}return t}function WD(e){return e?e.split(` +`).map(t=>t.trimEnd()).filter(Boolean).at(-1)??"":""}function dxe(e){return e.suspendedReason||WD(e.text)||WD(e.outputLines?.join(` +`))||e.summary||""}function fxe(e){return e.suspendedReason?e.suspendedReason:e.text?e.text:e.outputLines&&e.outputLines.length>0?e.outputLines.join(` +`):e.summary??""}function hxe(e){return e==="completed"?"completed":e==="failed"?"failed":e==="aborted"?"cancelled":"working"}function qD(e,t){return{id:e.agentId??e.item??`result-${t}`,agentId:e.agentId,name:e.item??`subagent ${t+1}`,activity:e.body.split(` +`)[0]??"",phase:hxe(e.outcome),body:e.body}}function pxe(e,t){return!!(t.agentId&&e.agentId===t.agentId||t.item&&e.name.includes(t.item))}function mxe(e,t){const n=e.map(o=>({id:o.id,agentId:o.agentId,name:o.name,activity:dxe(o),phase:o.phase,body:fxe(o)}));if(!t)return n;const i=t.subagents.filter(o=>(o.outcome==="aborted"||o.state==="not_started")&&!e.some(s=>pxe(s,o))).map((o,s)=>qD(o,s));return n.length>0?[...n,...i]:t.subagents.map((o,s)=>qD(o,s))}const gxe=["queued","working","suspended","completed","failed","cancelled"];function oV(e){return e.status==="completed"?"completed":e.status==="failed"?"failed":e.status==="cancelled"?"cancelled":e.subagentPhase?e.subagentPhase:"working"}function vxe(){return{queued:0,working:0,suspended:0,completed:0,failed:0,cancelled:0}}function yxe(e){const t=new Map;for(const n of e){if(n.kind!=="subagent"||n.swarmIndex===void 0)continue;const i=n.parentToolCallId??"swarm",o=t.get(i)??[];o.push({id:n.id,agentId:n.agentId,name:n.description,subagentType:n.subagentType,model:n.model,thinkingEffort:n.thinkingEffort,phase:oV(n),summary:n.outputPreview,outputLines:n.outputLines,text:n.text,suspendedReason:n.suspendedReason,swarmIndex:n.swarmIndex}),t.set(i,o)}return[...t.entries()].map(([n,i])=>{const o=i.toSorted((r,l)=>r.swarmIndex-l.swarmIndex||r.id.localeCompare(l.id)),s=vxe();for(const r of o)s[r.phase]++;return{id:n,members:o,counts:s}}).filter(n=>n.members.length>1).toSorted((n,i)=>{const o=n.members.at(0)?.swarmIndex??0,s=i.members.at(0)?.swarmIndex??0;return o!==s?o-s:n.id.localeCompare(i.id)})}function kxe(e){let t=0,n=0;for(const i of e){n+=i.members.length;for(const o of gxe)(o==="completed"||o==="failed"||o==="cancelled")&&(t+=i.counts[o])}return{done:t,total:n}}function bxe(e){const t=new Map;for(const n of e){if(n.kind!=="subagent"||!n.parentToolCallId)continue;const i=t.get(n.parentToolCallId)??[];i.push({id:n.id,agentId:n.agentId,name:n.description,subagentType:n.subagentType,model:n.model,thinkingEffort:n.thinkingEffort,phase:oV(n),summary:n.outputPreview,outputLines:n.outputLines,text:n.text,suspendedReason:n.suspendedReason,swarmIndex:n.swarmIndex??Number.MAX_SAFE_INTEGER}),t.set(n.parentToolCallId,i)}for(const[n,i]of t)t.set(n,i.toSorted((o,s)=>o.swarmIndex-s.swarmIndex||o.id.localeCompare(s.id)));return t}function CS(e){const t=e.trim();if(!t.startsWith("{"))return null;try{const n=JSON.parse(t);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function sV(e){for(const t of["path","file_path","filePath","filename"]){const n=e[t];if(typeof n=="string"&&n.length>0)return n}}const p0=100*1024;function wxe(e){const t=hr(e.name);if(t!=="edit"&&t!=="multi_edit")return null;const n=CS(e.arg);if(!n)return null;if(t==="edit"){if(n.replace_all===!0)return null;const l=typeof n.old_string=="string"?n.old_string:void 0,a=typeof n.new_string=="string"?n.new_string:void 0;return l===void 0||a===void 0||l.length>p0||a.length>p0?null:Ib(l,a)}const i=Array.isArray(n.edits)?n.edits:void 0;if(!i||i.length===0)return null;const o=[];let s=0,r=0;for(const l of i){if(!l||typeof l!="object")return null;const a=l;if(a.replace_all===!0)return null;const u=typeof a.old_string=="string"?a.old_string:void 0,c=typeof a.new_string=="string"?a.new_string:void 0;if(u===void 0||c===void 0||u.length>p0||c.length>p0)return null;const d=Ib(u,c);if(d===null)return null;o.length>0&&o.push({type:"hunk",text:"···"});for(const f of d)o.push({...f,oldNo:f.oldNo!==void 0?f.oldNo+s:void 0,newNo:f.newNo!==void 0?f.newNo+r:void 0});s+=hc(u).length,r+=hc(c).length}return o}const Cxe=5e3;function Axe(e){if(hr(e.name)!=="write")return null;const t=CS(e.arg);return!t||typeof t.content!="string"||t.content.length>p0||t.content.split(` +`).length>Cxe?null:{content:t.content,path:sV(t)}}function xxe(e){const t=CS(e.arg);return t?sV(t):void 0}function Sxe(e){switch(e){case"running":return"running";case"completed":return"completed";case"killed":return"cancelled";default:return"failed"}}function _xe(e,t){return t==="running"?e.stateReason!==void 0?"suspended":"working":t}function Ixe(e){return e==="subagent"?"subagent":e==="shell"?"bash":"tool"}function Mxe(e){return rV(e).parents}function rV(e){const t=new Map,n=new Map;for(const i of e.items)if(i.kind==="turn")for(const o of i.steps)for(const s of o.frames)s.kind!=="tool"||s.agentRefs===void 0||s.agentRefs.forEach((r,l)=>{t.set(r.agentId,s.toolCallId),n.set(r.agentId,l)});return{parents:t,swarmIndexes:n}}function Txe(e,t,n){const i=rV(e);let o=i.parents,s=i.swarmIndexes;if(n!==void 0){for(const[u,c]of i.parents)n.parents.set(u,c);for(const[u,c]of i.swarmIndexes)n.swarmIndexes.set(u,c);o=n.parents,s=n.swarmIndexes}const r=e.tasks.map(u=>{const c=Sxe(u.state);return{id:u.taskId,agentId:u.agentId,sessionId:t,kind:Ixe(u.kind),description:u.description??"",status:c,createdAt:u.startedAt??"",startedAt:u.startedAt,completedAt:u.endedAt,outputPreview:u.outputTail.length>0?u.outputTail:void 0,text:u.resultSummary,subagentPhase:u.kind==="subagent"?_xe(u,c):void 0,suspendedReason:c==="running"?u.stateReason:void 0,model:u.model,thinkingEffort:u.thinkingEffort,runInBackground:u.detached,parentToolCallId:u.agentId!==void 0?o.get(u.agentId):void 0,swarmIndex:u.agentId!==void 0?s.get(u.agentId):void 0}}),l=new Map;r.forEach((u,c)=>{u.agentId!==void 0&&u.id===u.agentId&&l.set(u.agentId,c)});const a=new Set;return r.forEach((u,c)=>{if(u.agentId===void 0||u.id===u.agentId)return;const d=l.get(u.agentId);if(d===void 0)return;const f=r[d],h=u.completedAt!==void 0&&f.startedAt!==void 0&&u.completedAt>=f.startedAt,m=f.status==="running"&&u.status!=="running"&&h;r[d]={...f,backgroundTaskId:u.status==="running"||h?u.id:void 0,status:m?u.status:f.status,subagentPhase:m?u.status==="completed"?"completed":u.status==="cancelled"?"cancelled":"failed":f.subagentPhase,description:f.description.length>0?f.description:u.description,model:f.model??u.model,thinkingEffort:f.thinkingEffort??u.thinkingEffort,completedAt:h?u.completedAt??f.completedAt:f.completedAt,outputPreview:h?f.outputPreview??u.outputPreview:f.outputPreview,text:h?f.text??u.text:f.text},a.add(c)}),r.filter((u,c)=>!a.has(c))}function Exe(){let e=[],t=null,n=null,i=null,o,s,r=!0;const l=new WeakMap,a=u=>{const{messages:c,approvals:d}=u,f=u.sessionActive??!0,h=u.planReviewByToolCallId??{},m=u.plansByToolCallId??{},g=(S,x)=>l.set(S,x);let y=n!==null;if(y){const S=n,x=Object.keys(h);y=x.length===Object.keys(S).length&&x.every(A=>h[A]===S[A])}let k=i!==null;if(k){const S=i,x=Object.keys(m);k=x.length===Object.keys(S).length&&x.every(A=>m[A]===S[A])}const v=e.length>0&&d===t&&y&&k&&u.getFileUrl===o&&u.getSessionMediaUrl===s;let C=0,w=0,M=1;if(v){let S=-1;for(let x=e.length-1;x>=0;x--)if(e[x].role==="assistant"){S=x;break}for(let x=0;x0?[...e.slice(0,C),...L]:L;return e=E,t=d,n={...h},i={...m},o=u.getFileUrl,s=u.getSessionMediaUrl,r=f,E};return a.reset=()=>{e=[],t=null,n=null,i=null,o=void 0,r=!0},a}function Lxe(e){const t=new Map;let n=0;for(let i=e.length-1;i>=0;i--){const o=e[i];if(o.role==="compaction"||o.goalContinuation===!0)break;o.role==="user"&&o.hasUndoAnchor!==!1&&(n++,t.set(o.id,n))}return t}const lV=["light","dark","system"],Nxe=["small","medium","large","xlarge"],z8="medium",aV="kimi-web.color-scheme",r6="kimi-web.font-scale",UD="kimi-web.ui-font-size";function l6(e){try{return globalThis.localStorage.getItem(e)}catch{return null}}function AS(e,t){try{globalThis.localStorage.setItem(e,t)}catch{}}function Fxe(e){try{globalThis.localStorage.removeItem(e)}catch{}}function Dxe(){const e=l6(aV);return e&&lV.includes(e)?e:"system"}const Gy={light:"#ffffff",dark:"#121212"};function Rxe(e){if(typeof document>"u"||!document.documentElement)return;document.documentElement.dataset.colorScheme=e;const t=document.querySelectorAll('meta[name="theme-color"]');if(t.length===0)return;const n=e==="dark"?Gy.dark:e==="light"?Gy.light:null;t.forEach(i=>{const s=(i.getAttribute("media")??"").includes("dark")?Gy.dark:Gy.light;i.setAttribute("content",n??s)})}function uV(e){return Nxe.includes(e)}function Oxe(e){return e<=13?"small":e<=15?"medium":e<=17?"large":"xlarge"}function Pxe(){const e=l6(r6);if(e==="xxlarge")return"xlarge";if(e!==null)return uV(e)?e:z8;const t=l6(UD);if(t===null)return z8;const n=Number(t),i=Number.isFinite(n)?Oxe(n):z8;return AS(r6,i),Fxe(UD),i}function Bxe(e){typeof document>"u"||!document.documentElement||(document.documentElement.dataset.fontScale=e)}const xS=q(Dxe()),SS=q(Pxe());let VD=!1;function $xe(){VD||(VD=!0,ze(xS,Rxe,{immediate:!0}),ze(SS,Bxe,{immediate:!0}))}function zxe(e){lV.includes(e)&&(xS.value=e,AS(aV,e))}function jxe(e){uV(e)&&(SS.value=e,AS(r6,e))}function Xm(){return $xe(),{colorScheme:xS,fontScale:SS,setColorScheme:zxe,setFontScale:jxe}}const Qy=q(!1);let KD=!1;function j8(){const e=document.documentElement.dataset.colorScheme;return e==="dark"?!0:e==="light"?!1:window.matchMedia("(prefers-color-scheme: dark)").matches}function ow(){return!KD&&typeof window<"u"&&typeof document<"u"&&(KD=!0,Qy.value=j8(),new MutationObserver(()=>{Qy.value=j8()}).observe(document.documentElement,{attributes:!0,attributeFilter:["data-color-scheme"]}),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",()=>{Qy.value=j8()})),Qy}const cV="kimi-web.sidebar-multi-tab";function Hxe(e){try{return globalThis.localStorage.getItem(e)}catch{return null}}function Wxe(e,t){try{globalThis.localStorage.setItem(e,t)}catch{}}function qxe(){return Hxe(cV)==="1"}const dV=q(qxe());function Uxe(e){dV.value=e,Wxe(cV,e?"1":"0")}function Dp(){return{sidebarTabs:dV,setSidebarTabs:Uxe}}function ev(e){let t="";for(const n of e)n.codePointAt(0)>127||/[A-Za-z0-9\-._~]/.test(n)?t+=n:t+=`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`;return t}function Vxe(e){const t=e.split("/").map(ev).join("/");return t.startsWith("//")?`/%2F${t.slice(2)}`:t}function _S(e){return e.replace(/%/g,"%25").replace(/&/g,"%26").replace(//g,"%3E").replace(/([\\[\]])/g,"\\$1").replace(/\n/g,"%0A").replace(/\r/g,"%0D")}function ZD(e){return e.replace(/\\([\\[\]])/g,"$1").replace(/%0A/g,` +`).replace(/%0D/g,"\r").replace(/%26/g,"&").replace(/%3C/g,"<").replace(/%3E/g,">").replace(/%25/g,"%")}function Kxe(e){return e.replace(/%0A/g,` +`).replace(/%0D/g,"\r").replace(/%26/g,"&").replace(/%3C/g,"<").replace(/%3E/g,">").replace(/%25/g,"%")}function Zxe(e,t){const n=t?e.replace(/\\([\\<>])/g,"$1"):e.replace(/\\([\\()])/g,"$1");return tv(n)}function tv(e){try{return decodeURIComponent(e)}catch{return e}}let GD;function a6(e){return GD??=new Intl.Segmenter("und",{granularity:"grapheme"}),[...GD.segment(e)].map(t=>t.segment)}function fV(e,t){const n=a6(e);return n.length<=t?e:`${n.slice(0,t-1).join("")}…`}const Mb="kimi-code://skill/";function IS(e){return e?e.startsWith(Mb)&&e.length>Mb.length?"skill":e.startsWith("#")||e.startsWith("?")||e.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!/^[a-zA-Z]:(?:[\\/]|%5c)/i.test(e)?null:e.endsWith("/")||e.endsWith("\\")||/%5c$/i.test(e)?"folder":"file":null}function z1(e){const t=e.search(/[#?]/);return t>0?e.slice(0,t):e}function hV(e){const t=e.slice(Mb.length);return tv(t)}function Rp(e){const t=_S(e.name);if(e.kind==="skill")return`[${t}](${Mb}${ev(e.name)})`;const n=e.kind==="folder"&&!e.path.endsWith("/")&&!e.path.endsWith("\\")?`${e.path}/`:e.path;return`[${t}](${Vxe(n)})`}const G9="kimi-code-composer://attachments/";function Nf(e){return`[${_S(e.name)}](${G9}${e.attId})`}const qh="kimi-code-composer://quote/",Gxe=12;function Mm(e){const t=e.split(` +`).map(i=>i.trim()).find(i=>i.length>0)??"",n=fV(t,Gxe);return n.length>0?n:"…"}function sw(e){const t=e.source!==void 0&&e.source.length>0?`?source=${ev(e.source)}`:"",n=e.comment!==void 0&&e.comment.length>0?`?comment=${ev(e.comment)}`:"";return`[${_S(Mm(e.text))}](${qh}${ev(e.text)}${t}${n})`}function pV(e){const t=e.indexOf("?source="),n=e.indexOf("?comment="),i=[t,n].filter(s=>s>=0).sort((s,r)=>s-r)[0]??-1,o={text:tv(i===-1?e:e.slice(0,i))};if(t>=0){const s=n>t?n:e.length;o.source=tv(e.slice(t+8,s))}if(n>=0){const s=t>n?t:e.length;o.comment=tv(e.slice(n+9,s))}return o}const QD=document.createElement("i");function Qxe(e){const t="&"+e+";";QD.innerHTML=t;const n=QD.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function pc(e,t,n,i){const o=e.length;let s=0,r;if(t<0?t=-t>o?0:o+t:t=t>o?o:t,n=n>0?n:0,i.length<1e4)r=Array.from(i),r.unshift(t,n),e.splice(...r);else for(n&&e.splice(t,n);s0?(pc(e,e.length,0,t),e):t}const YD={}.hasOwnProperty;function Yxe(e){const t={};let n=-1;for(;++n-1&&e.test(String.fromCharCode(n))}}function oo(e,t,n,i){const o=i?i-1:Number.POSITIVE_INFINITY;let s=0;return r;function r(a){return Ii(a)?(e.enter(n),l(a)):t(a)}function l(a){return Ii(a)&&s++r))return;const E=t.events.length;let S=E,x,A;for(;S--;)if(t.events[S][0]==="exit"&&t.events[S][1].type==="chunkFlow"){if(x){A=t.events[S][1].end;break}x=!0}for(k(i),L=E;LC;){const M=n[w];t.containerState=M[1],M[0].exit.call(t,e)}n.length=C}function v(){o.write([null]),s=void 0,o=void 0,t.containerState._closeFlow=void 0}}function uSe(e,t,n){return oo(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function XD(e){if(e===null||Nl(e)||oSe(e))return 1;if(iSe(e))return 2}function TS(e,t,n){const i=[];let o=-1;for(;++o1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[i][1].end},f={...e[n][1].start};eR(d,-a),eR(f,a),r={type:a>1?"strongSequence":"emphasisSequence",start:d,end:{...e[i][1].end}},l={type:a>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},s={type:a>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[n][1].start}},o={type:a>1?"strong":"emphasis",start:{...r.start},end:{...l.end}},e[i][1].end={...r.start},e[n][1].start={...l.end},u=[],e[i][1].end.offset-e[i][1].start.offset&&(u=Da(u,[["enter",e[i][1],t],["exit",e[i][1],t]])),u=Da(u,[["enter",o,t],["enter",r,t],["exit",r,t],["enter",s,t]]),u=Da(u,TS(t.parser.constructs.insideSpan.null,e.slice(i+1,n),t)),u=Da(u,[["exit",s,t],["enter",l,t],["exit",l,t],["exit",o,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Da(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,pc(e,i-1,n-i+3,u),n=i+u.length-c-2;break}}for(n=-1;++n0&&Ii(L)?oo(e,v,"linePrefix",s+1)(L):v(L)}function v(L){return L===null||jn(L)?e.check(tR,g,w)(L):(e.enter("codeFlowValue"),C(L))}function C(L){return L===null||jn(L)?(e.exit("codeFlowValue"),v(L)):(e.consume(L),C)}function w(L){return e.exit("codeFenced"),t(L)}function M(L,E,S){let x=0;return A;function A(R){return L.enter("lineEnding"),L.consume(R),L.exit("lineEnding"),T}function T(R){return L.enter("codeFencedFence"),Ii(R)?oo(L,I,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):I(R)}function I(R){return R===l?(L.enter("codeFencedFenceSequence"),O(R)):S(R)}function O(R){return R===l?(x++,L.consume(R),O):x>=r?(L.exit("codeFencedFenceSequence"),Ii(R)?oo(L,H,"whitespace")(R):H(R)):S(R)}function H(R){return R===null||jn(R)?(L.exit("codeFencedFence"),E(R)):S(R)}}}function wSe(e,t,n){const i=this;return o;function o(r){return r===null?n(r):(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s)}function s(r){return i.parser.lazy[i.now().line]?n(r):t(r)}}const H8={name:"codeIndented",tokenize:ASe},CSe={partial:!0,tokenize:xSe};function ASe(e,t,n){const i=this;return o;function o(u){return e.enter("codeIndented"),oo(e,s,"linePrefix",5)(u)}function s(u){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?r(u):n(u)}function r(u){return u===null?a(u):jn(u)?e.attempt(CSe,r,a)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||jn(u)?(e.exit("codeFlowValue"),r(u)):(e.consume(u),l)}function a(u){return e.exit("codeIndented"),t(u)}}function xSe(e,t,n){const i=this;return o;function o(r){return i.parser.lazy[i.now().line]?n(r):jn(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),o):oo(e,s,"linePrefix",5)(r)}function s(r){const l=i.events[i.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(r):jn(r)?o(r):n(r)}}const SSe={name:"codeText",previous:ISe,resolve:_Se,tokenize:MSe};function _Se(e){let t=e.length-4,n=3,i,o;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(i=n;++i=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(t,n,i){const o=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-o,Number.POSITIVE_INFINITY);return i&&Wg(this.left,i),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Wg(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Wg(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(r):e.interrupt(i.parser.constructs.flow,n,t)(r)}}function kV(e,t,n,i,o,s,r,l,a){const u=a||Number.POSITIVE_INFINITY;let c=0;return d;function d(k){return k===60?(e.enter(i),e.enter(o),e.enter(s),e.consume(k),e.exit(s),f):k===null||k===32||k===41||u6(k)?n(k):(e.enter(i),e.enter(r),e.enter(l),e.enter("chunkString",{contentType:"string"}),g(k))}function f(k){return k===62?(e.enter(s),e.consume(k),e.exit(s),e.exit(o),e.exit(i),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),h(k))}function h(k){return k===62?(e.exit("chunkString"),e.exit(l),f(k)):k===null||k===60||jn(k)?n(k):(e.consume(k),k===92?m:h)}function m(k){return k===60||k===62||k===92?(e.consume(k),h):h(k)}function g(k){return!c&&(k===null||k===41||Nl(k))?(e.exit("chunkString"),e.exit(l),e.exit(r),e.exit(i),t(k)):c999||h===null||h===91||h===93&&!a||h===94&&!l&&"_hiddenFootnoteSupport"in r.parser.constructs?n(h):h===93?(e.exit(s),e.enter(o),e.consume(h),e.exit(o),e.exit(i),t):jn(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(h))}function d(h){return h===null||h===91||h===93||jn(h)||l++>999?(e.exit("chunkString"),c(h)):(e.consume(h),a||(a=!Ii(h)),h===92?f:d)}function f(h){return h===91||h===92||h===93?(e.consume(h),l++,d):d(h)}}function wV(e,t,n,i,o,s){let r;return l;function l(f){return f===34||f===39||f===40?(e.enter(i),e.enter(o),e.consume(f),e.exit(o),r=f===40?41:f,a):n(f)}function a(f){return f===r?(e.enter(o),e.consume(f),e.exit(o),e.exit(i),t):(e.enter(s),u(f))}function u(f){return f===r?(e.exit(s),a(r)):f===null?n(f):jn(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),oo(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(f))}function c(f){return f===r||f===null||jn(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:c)}function d(f){return f===r||f===92?(e.consume(f),c):c(f)}}function nv(e,t){let n;return i;function i(o){return jn(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n=!0,i):Ii(o)?oo(e,i,n?"linePrefix":"lineSuffix")(o):t(o)}}const OSe={name:"definition",tokenize:BSe},PSe={partial:!0,tokenize:$Se};function BSe(e,t,n){const i=this;let o;return s;function s(h){return e.enter("definition"),r(h)}function r(h){return bV.call(i,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function l(h){return o=MS(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),a):n(h)}function a(h){return Nl(h)?nv(e,u)(h):u(h)}function u(h){return kV(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function c(h){return e.attempt(PSe,d,d)(h)}function d(h){return Ii(h)?oo(e,f,"whitespace")(h):f(h)}function f(h){return h===null||jn(h)?(e.exit("definition"),i.parser.defined.push(o),t(h)):n(h)}}function $Se(e,t,n){return i;function i(l){return Nl(l)?nv(e,o)(l):n(l)}function o(l){return wV(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function s(l){return Ii(l)?oo(e,r,"whitespace")(l):r(l)}function r(l){return l===null||jn(l)?t(l):n(l)}}const zSe={name:"hardBreakEscape",tokenize:jSe};function jSe(e,t,n){return i;function i(s){return e.enter("hardBreakEscape"),e.consume(s),o}function o(s){return jn(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const HSe={name:"headingAtx",resolve:WSe,tokenize:qSe};function WSe(e,t){let n=e.length-2,i=3,o,s;return e[i][1].type==="whitespace"&&(i+=2),n-2>i&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(i===n-1||n-4>i&&e[n-2][1].type==="whitespace")&&(n-=i+1===n?2:4),n>i&&(o={type:"atxHeadingText",start:e[i][1].start,end:e[n][1].end},s={type:"chunkText",start:e[i][1].start,end:e[n][1].end,contentType:"text"},pc(e,i,n-i+1,[["enter",o,t],["enter",s,t],["exit",s,t],["exit",o,t]])),e}function qSe(e,t,n){let i=0;return o;function o(c){return e.enter("atxHeading"),s(c)}function s(c){return e.enter("atxHeadingSequence"),r(c)}function r(c){return c===35&&i++<6?(e.consume(c),r):c===null||Nl(c)?(e.exit("atxHeadingSequence"),l(c)):n(c)}function l(c){return c===35?(e.enter("atxHeadingSequence"),a(c)):c===null||jn(c)?(e.exit("atxHeading"),t(c)):Ii(c)?oo(e,l,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function a(c){return c===35?(e.consume(c),a):(e.exit("atxHeadingSequence"),l(c))}function u(c){return c===null||c===35||Nl(c)?(e.exit("atxHeadingText"),l(c)):(e.consume(c),u)}}const USe=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],iR=["pre","script","style","textarea"],VSe={concrete:!0,name:"htmlFlow",resolveTo:GSe,tokenize:QSe},KSe={partial:!0,tokenize:JSe},ZSe={partial:!0,tokenize:YSe};function GSe(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function QSe(e,t,n){const i=this;let o,s,r,l,a;return u;function u(G){return c(G)}function c(G){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(G),d}function d(G){return G===33?(e.consume(G),f):G===47?(e.consume(G),s=!0,g):G===63?(e.consume(G),o=3,i.interrupt?t:$):Yu(G)?(e.consume(G),r=String.fromCharCode(G),y):n(G)}function f(G){return G===45?(e.consume(G),o=2,h):G===91?(e.consume(G),o=5,l=0,m):Yu(G)?(e.consume(G),o=4,i.interrupt?t:$):n(G)}function h(G){return G===45?(e.consume(G),i.interrupt?t:$):n(G)}function m(G){const te="CDATA[";return G===te.charCodeAt(l++)?(e.consume(G),l===te.length?i.interrupt?t:I:m):n(G)}function g(G){return Yu(G)?(e.consume(G),r=String.fromCharCode(G),y):n(G)}function y(G){if(G===null||G===47||G===62||Nl(G)){const te=G===47,le=r.toLowerCase();return!te&&!s&&iR.includes(le)?(o=1,i.interrupt?t(G):I(G)):USe.includes(r.toLowerCase())?(o=6,te?(e.consume(G),k):i.interrupt?t(G):I(G)):(o=7,i.interrupt&&!i.parser.lazy[i.now().line]?n(G):s?v(G):C(G))}return G===45||mu(G)?(e.consume(G),r+=String.fromCharCode(G),y):n(G)}function k(G){return G===62?(e.consume(G),i.interrupt?t:I):n(G)}function v(G){return Ii(G)?(e.consume(G),v):A(G)}function C(G){return G===47?(e.consume(G),A):G===58||G===95||Yu(G)?(e.consume(G),w):Ii(G)?(e.consume(G),C):A(G)}function w(G){return G===45||G===46||G===58||G===95||mu(G)?(e.consume(G),w):M(G)}function M(G){return G===61?(e.consume(G),L):Ii(G)?(e.consume(G),M):C(G)}function L(G){return G===null||G===60||G===61||G===62||G===96?n(G):G===34||G===39?(e.consume(G),a=G,E):Ii(G)?(e.consume(G),L):S(G)}function E(G){return G===a?(e.consume(G),a=null,x):G===null||jn(G)?n(G):(e.consume(G),E)}function S(G){return G===null||G===34||G===39||G===47||G===60||G===61||G===62||G===96||Nl(G)?M(G):(e.consume(G),S)}function x(G){return G===47||G===62||Ii(G)?C(G):n(G)}function A(G){return G===62?(e.consume(G),T):n(G)}function T(G){return G===null||jn(G)?I(G):Ii(G)?(e.consume(G),T):n(G)}function I(G){return G===45&&o===2?(e.consume(G),F):G===60&&o===1?(e.consume(G),P):G===62&&o===4?(e.consume(G),K):G===63&&o===3?(e.consume(G),$):G===93&&o===5?(e.consume(G),W):jn(G)&&(o===6||o===7)?(e.exit("htmlFlowData"),e.check(KSe,ne,O)(G)):G===null||jn(G)?(e.exit("htmlFlowData"),O(G)):(e.consume(G),I)}function O(G){return e.check(ZSe,H,ne)(G)}function H(G){return e.enter("lineEnding"),e.consume(G),e.exit("lineEnding"),R}function R(G){return G===null||jn(G)?O(G):(e.enter("htmlFlowData"),I(G))}function F(G){return G===45?(e.consume(G),$):I(G)}function P(G){return G===47?(e.consume(G),r="",z):I(G)}function z(G){if(G===62){const te=r.toLowerCase();return iR.includes(te)?(e.consume(G),K):I(G)}return Yu(G)&&r.length<8?(e.consume(G),r+=String.fromCharCode(G),z):I(G)}function W(G){return G===93?(e.consume(G),$):I(G)}function $(G){return G===62?(e.consume(G),K):G===45&&o===2?(e.consume(G),$):I(G)}function K(G){return G===null||jn(G)?(e.exit("htmlFlowData"),ne(G)):(e.consume(G),K)}function ne(G){return e.exit("htmlFlow"),t(G)}}function YSe(e,t,n){const i=this;return o;function o(r){return jn(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s):n(r)}function s(r){return i.parser.lazy[i.now().line]?n(r):t(r)}}function JSe(e,t,n){return i;function i(o){return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),e.attempt(rw,t,n)}}const XSe={name:"htmlText",tokenize:e_e};function e_e(e,t,n){const i=this;let o,s,r;return l;function l($){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume($),a}function a($){return $===33?(e.consume($),u):$===47?(e.consume($),M):$===63?(e.consume($),C):Yu($)?(e.consume($),S):n($)}function u($){return $===45?(e.consume($),c):$===91?(e.consume($),s=0,m):Yu($)?(e.consume($),v):n($)}function c($){return $===45?(e.consume($),h):n($)}function d($){return $===null?n($):$===45?(e.consume($),f):jn($)?(r=d,P($)):(e.consume($),d)}function f($){return $===45?(e.consume($),h):d($)}function h($){return $===62?F($):$===45?f($):d($)}function m($){const K="CDATA[";return $===K.charCodeAt(s++)?(e.consume($),s===K.length?g:m):n($)}function g($){return $===null?n($):$===93?(e.consume($),y):jn($)?(r=g,P($)):(e.consume($),g)}function y($){return $===93?(e.consume($),k):g($)}function k($){return $===62?F($):$===93?(e.consume($),k):g($)}function v($){return $===null||$===62?F($):jn($)?(r=v,P($)):(e.consume($),v)}function C($){return $===null?n($):$===63?(e.consume($),w):jn($)?(r=C,P($)):(e.consume($),C)}function w($){return $===62?F($):C($)}function M($){return Yu($)?(e.consume($),L):n($)}function L($){return $===45||mu($)?(e.consume($),L):E($)}function E($){return jn($)?(r=E,P($)):Ii($)?(e.consume($),E):F($)}function S($){return $===45||mu($)?(e.consume($),S):$===47||$===62||Nl($)?x($):n($)}function x($){return $===47?(e.consume($),F):$===58||$===95||Yu($)?(e.consume($),A):jn($)?(r=x,P($)):Ii($)?(e.consume($),x):F($)}function A($){return $===45||$===46||$===58||$===95||mu($)?(e.consume($),A):T($)}function T($){return $===61?(e.consume($),I):jn($)?(r=T,P($)):Ii($)?(e.consume($),T):x($)}function I($){return $===null||$===60||$===61||$===62||$===96?n($):$===34||$===39?(e.consume($),o=$,O):jn($)?(r=I,P($)):Ii($)?(e.consume($),I):(e.consume($),H)}function O($){return $===o?(e.consume($),o=void 0,R):$===null?n($):jn($)?(r=O,P($)):(e.consume($),O)}function H($){return $===null||$===34||$===39||$===60||$===61||$===96?n($):$===47||$===62||Nl($)?x($):(e.consume($),H)}function R($){return $===47||$===62||Nl($)?x($):n($)}function F($){return $===62?(e.consume($),e.exit("htmlTextData"),e.exit("htmlText"),t):n($)}function P($){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume($),e.exit("lineEnding"),z}function z($){return Ii($)?oo(e,W,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)($):W($)}function W($){return e.enter("htmlTextData"),r($)}}const ES={name:"labelEnd",resolveAll:o_e,resolveTo:s_e,tokenize:r_e},t_e={tokenize:l_e},n_e={tokenize:a_e},i_e={tokenize:u_e};function o_e(e){let t=-1;const n=[];for(;++t=3&&(u===null||jn(u))?(e.exit("thematicBreak"),t(u)):n(u)}function a(u){return u===o?(e.consume(u),i++,a):(e.exit("thematicBreakSequence"),Ii(u)?oo(e,l,"whitespace")(u):l(u))}}const vl={continuation:{tokenize:k_e},exit:w_e,name:"list",tokenize:y_e},g_e={partial:!0,tokenize:C_e},v_e={partial:!0,tokenize:b_e};function y_e(e,t,n){const i=this,o=i.events[i.events.length-1];let s=o&&o[1].type==="linePrefix"?o[2].sliceSerialize(o[1],!0).length:0,r=0;return l;function l(h){const m=i.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!i.containerState.marker||h===i.containerState.marker:c6(h)){if(i.containerState.type||(i.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(Q9,n,u)(h):u(h);if(!i.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),a(h)}return n(h)}function a(h){return c6(h)&&++r<10?(e.consume(h),a):(!i.interrupt||r<2)&&(i.containerState.marker?h===i.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):n(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||h,e.check(rw,i.interrupt?n:c,e.attempt(g_e,f,d))}function c(h){return i.containerState.initialBlankLine=!0,s++,f(h)}function d(h){return Ii(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):n(h)}function f(h){return i.containerState.size=s+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function k_e(e,t,n){const i=this;return i.containerState._closeFlow=void 0,e.check(rw,o,s);function o(l){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,oo(e,t,"listItemIndent",i.containerState.size+1)(l)}function s(l){return i.containerState.furtherBlankLines||!Ii(l)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,r(l)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(v_e,t,r)(l))}function r(l){return i.containerState._closeFlow=!0,i.interrupt=void 0,oo(e,e.attempt(vl,t,n),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function b_e(e,t,n){const i=this;return oo(e,o,"listItemIndent",i.containerState.size+1);function o(s){const r=i.events[i.events.length-1];return r&&r[1].type==="listItemIndent"&&r[2].sliceSerialize(r[1],!0).length===i.containerState.size?t(s):n(s)}}function w_e(e){e.exit(this.containerState.type)}function C_e(e,t,n){const i=this;return oo(e,o,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function o(s){const r=i.events[i.events.length-1];return!Ii(s)&&r&&r[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const oR={name:"setextUnderline",resolveTo:A_e,tokenize:x_e};function A_e(e,t){let n=e.length,i,o,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){i=n;break}e[n][1].type==="paragraph"&&(o=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const r={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[o][1].type="setextHeadingText",s?(e.splice(o,0,["enter",r,t]),e.splice(s+1,0,["exit",e[i][1],t]),e[i][1].end={...e[s][1].end}):e[i][1]=r,e.push(["exit",r,t]),e}function x_e(e,t,n){const i=this;let o;return s;function s(u){let c=i.events.length,d;for(;c--;)if(i.events[c][1].type!=="lineEnding"&&i.events[c][1].type!=="linePrefix"&&i.events[c][1].type!=="content"){d=i.events[c][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||d)?(e.enter("setextHeadingLine"),o=u,r(u)):n(u)}function r(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===o?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),Ii(u)?oo(e,a,"lineSuffix")(u):a(u))}function a(u){return u===null||jn(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const S_e={tokenize:__e};function __e(e){const t=this,n=e.attempt(rw,i,e.attempt(this.parser.constructs.flowInitial,o,oo(e,e.attempt(this.parser.constructs.flow,o,e.attempt(LSe,o)),"linePrefix")));return n;function i(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function o(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const I_e={resolveAll:AV()},M_e=CV("string"),T_e=CV("text");function CV(e){return{resolveAll:AV(e==="text"?E_e:void 0),tokenize:t};function t(n){const i=this,o=this.parser.constructs[e],s=n.attempt(o,r,l);return r;function r(c){return u(c)?s(c):l(c)}function l(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),a}function a(c){return u(c)?(n.exit("data"),s(c)):(n.consume(c),a)}function u(c){if(c===null)return!0;const d=o[c];let f=-1;if(d)for(;++f-1){const l=r[0];typeof l=="string"?r[0]=l.slice(i):r.shift()}s>0&&r.push(e[o].slice(0,s))}return r}function W_e(e,t){let n=-1;const i=[];let o;for(;++n0;if(s||e[c]!==(h?"!":"[")||r===null)continue;const m=e.slice(c+(h?2:1),d-1);let g=e.slice(r.start,r.end),y=!1;g.startsWith("<")&&(y=!0,g=g.slice(1,-1)),!(!m||!g)&&n.push({start:c,end:f,rawText:m,rawDest:g,angle:y,image:h})}return n}function Z_e(e,t){const{start:n,end:i,rawText:o,rawDest:s,angle:r,image:l}=e;if(l&&!s.startsWith(qh))return null;if(s.startsWith(G9)&&s.length>G9.length){const u=ZD(o),c=s.slice(G9.length);return{type:"attachment",start:n,end:i,attrs:{attId:c,name:u,kind:t?.(c)??(u.endsWith("/")?"folder":"file")},rawDest:s}}if(s.startsWith(qh)&&s.length>qh.length)return{type:"quote",start:n,end:i,attrs:pV(s.slice(qh.length)),rawDest:s};const a=IS(s);return a===null?null:a==="skill"?{type:"mention",start:n,end:i,attrs:{kind:a,name:hV(s),path:""},rawDest:s}:{type:"mention",start:n,end:i,attrs:{kind:a,name:ZD(o),path:Zxe(s,r)},rawDest:s}}const rR=/\[(?:\\.|[^\\[\]\n])*\]\((kimi-code-composer:\/\/quote\/[^\s)]+)\)/g;function G_e(e){const t=[];rR.lastIndex=0;let n;for(;(n=rR.exec(e))!==null;){let i=0;for(let s=n.index-1;s>=0&&e[s]==="\\";s-=1)i+=1;if(i%2===0)continue;const o=n[1];o===void 0||o.length<=qh.length||t.push({type:"quote",start:n.index-1,end:n.index+n[0].length,attrs:pV(o.slice(qh.length)),rawDest:o})}return t}function lw(e,t){const n=[];for(const i of xV(e)){const o=Z_e(i,t);o&&n.push(o)}return n.push(...G_e(e)),n.sort((i,o)=>i.start-o.start),n}function Ff(e){return lw(e).filter(t=>t.type==="mention").map(({start:t,end:n,attrs:i,rawDest:o})=>({start:t,end:n,attrs:i,rawDest:o}))}function Al(e){return lw(e).filter(t=>t.type==="attachment").map(({start:t,end:n,attrs:i,rawDest:o})=>({start:t,end:n,attrs:i,rawDest:o}))}function SV(e){return lw(e).filter(t=>t.type==="quote").map(({start:t,end:n,attrs:i,rawDest:o})=>({start:t,end:n,attrs:i,rawDest:o}))}function _V(e,t){const n=lw(e,t);if(n.length===0)return[{type:"text",value:e}];const i=[];let o=0;for(const s of n)s.start>o&&i.push({type:"text",value:e.slice(o,s.start)}),s.type==="mention"?i.push({type:"mention",attrs:s.attrs,rawDest:s.rawDest}):s.type==="attachment"?i.push({type:"attachment",attrs:s.attrs,rawDest:s.rawDest}):i.push({type:"quote",attrs:s.attrs,rawDest:s.rawDest}),o=s.end;return o[a,u+1])),s=new Map(t.mediaAttIds.map((a,u)=>[a,u+1]));let r="",l=0;for(const a of i){r+=e.slice(l,a.start),l=a.end;const{attId:u,name:c,kind:d}=a.attrs,f=d==="folder"?n?.resolveFolder?.(u):void 0;if(f!==void 0){const y=f==="/"||/^[a-zA-Z]:\/$/.test(f)?f.slice(0,-1)||"/":c.endsWith("/")?c.slice(0,-1):c;r+=Rp({kind:"folder",name:y,path:f});continue}const h=o.get(u);if(h!==void 0){r+=Nf({attId:String(h),name:c});continue}const m=s.get(u);if(m!==void 0){r+=Nf({attId:`m${m}`,name:c});continue}r+=c}return r+=e.slice(l),r}function lR(e,t,n=0){if(t<=0&&n<=0)return e;const i=Al(e);if(i.length===0)return e;let o="",s=0;for(const r of i){const{attId:l,name:a,kind:u}=r.attrs;let c;t>0&&/^[1-9]\d*$/.test(l)?c=String(Number(l)+t):n>0&&/^m[1-9]\d*$/.test(l)&&(c=`m${Number(l.slice(1))+n}`),c!==void 0&&(o+=e.slice(s,r.start),s=r.end,o+=Nf({attId:c,name:a}))}return o+=e.slice(s),o}function tf(e,t){const n=Al(e);if(n.length===0)return e;let i="",o=0;for(const s of n)i+=e.slice(o,s.start)+(t?.(s.attrs.name)??s.attrs.name),o=s.end;return i+=e.slice(o),i}function aR(e,t){const n=Al(e);if(n.length===0)return e;let i="",o=0;for(const s of n)t.has(s.attrs.attId)||(i+=e.slice(o,s.start)+s.attrs.name,o=s.end);return i+=e.slice(o),i}function f6(e){const t=Al(e);if(t.length===0)return e;let n="",i=0;for(const o of t)n+=e.slice(i,o.start),i=o.end;return n+=e.slice(i),n}let Y_e=!0;const J_e=/^> (.*)$/,X_e=/^>$/;function LS(e){return e.replaceAll("%","%25").replaceAll(` +`,"%0A").replaceAll("\r","%0D")}function eIe(e){return e.replaceAll("%0A",` +`).replaceAll("%0D","\r").replaceAll("%25","%")}const tIe=/^from: (.+)$/;function IV(e){let t=e,n;const i=e.indexOf(` +`),o=tIe.exec(i===-1?e:e.slice(0,i));o!==null&&(n=eIe(o[1]),t=i===-1?"":e.slice(i+1));const s=[];for(const r of t.split(` +`)){const l=J_e.exec(r);if(l!==null){s.push(l[1]??"");continue}if(X_e.test(r)){s.push("");continue}return null}return{text:s.join(` +`),...n!==void 0?{source:n}:{}}}function NS(e){const t=[];for(const i of e.split(/(\n{2,})/)){if(i==="")continue;if(/^\n{2,}$/.test(i)){t.push({type:"sep",text:i});continue}const o=IV(i);t.push(o===null?{type:"inline",text:i}:{type:"quote",text:o.text,...o.source!==void 0?{source:o.source}:{}})}const n=[];for(let i=0;i`> ${t}`).join(` +`)}function iIe(e){const t=e.split(/(\n{2,})/),n=new Array(t.length).fill(!1);let i=!1;for(let s=t.length-1;s>=0;s-=1){n[s]=i;const r=t[s];r!==""&&!/^\n{2,}$/.test(r)&&(i=!0)}let o="";for(let s=0;s{i.type==="sep"&&i.text===` + +`&&t[o-1]?.type==="quote"&&t[o+1]?.type==="quote"&&n.add(o)}),t.map((i,o)=>{if(n.has(o))return" ";if(i.type!=="quote")return i.text;const s={text:i.text};return i.source!==void 0&&(s.source=i.source),i.comment!==void 0&&(s.comment=i.comment),sw(s)}).join("")}function tr(e){this.content=e}tr.prototype={constructor:tr,find:function(e){for(var t=0;t>1}};tr.from=function(e){if(e instanceof tr)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new tr(t)};function EV(e,t,n){for(let i=0;;i++){if(i==e.childCount||i==t.childCount)return e.childCount==t.childCount?null:n;let o=e.child(i),s=t.child(i);if(o==s){n+=o.nodeSize;continue}if(!o.sameMarkup(s))return n;if(o.isText&&o.text!=s.text){let r=o.text,l=s.text,a=0;for(;r[a]==l[a];a++)n++;return a&&a0&&f>0&&u[d-1]==c[f-1];)d--,f--,n--,i--;return d&&f&&d=56320&&e<57344}function FV(e){return e>=55296&&e<56320}class sn{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let i=0;it&&i(a,o+l,s||null,r)!==!1&&a.content.size){let c=l+1;a.nodesBetween(Math.max(0,t-c),Math.min(a.content.size,n-c),i,o+c)}l=u}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,i,o){let s="",r=!0;return this.nodesBetween(t,n,(l,a)=>{let u=l.isText?l.text.slice(Math.max(t,a)-a,n-a):l.isLeaf?o?typeof o=="function"?o(l):o:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&u||l.isTextblock)&&i&&(r?r=!1:s+=i),s+=u},0),s}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,i=t.firstChild,o=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(i)&&(o[o.length-1]=n.withText(n.text+i.text),s=1);st)for(let s=0,r=0;rt&&((rn)&&(l.isText?l=l.cut(Math.max(0,t-r),Math.min(l.text.length,n-r)):l=l.cut(Math.max(0,t-r-1),Math.min(l.content.size,n-r-1))),i.push(l),o+=l.nodeSize),r=a}return new sn(i,o)}cutByIndex(t,n){return t==n?sn.empty:t==0&&n==this.content.length?this:new sn(this.content.slice(t,n))}replaceChild(t,n){let i=this.content[t];if(i==n)return this;let o=this.content.slice(),s=this.size+n.nodeSize-i.nodeSize;return o[t]=n,new sn(o,s)}addToStart(t){return new sn([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new sn(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;nthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,i=0;;n++){let o=this.child(n),s=i+o.nodeSize;if(s>=t)return s==t?Yy(n+1,s):Yy(n,i);i=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return sn.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return sn.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return sn.empty;let n,i=0;for(let o=0;othis.type.rank&&(n||(n=t.slice(0,o)),n.push(this),i=!0),n&&n.push(s)}}return n||(n=t.slice()),i||n.push(this),n}removeFromSet(t){for(let n=0;ni.type.rank-o.type.rank),n}}Fi.none=[];class zv extends Error{}class mn{constructor(t,n,i){this.content=t,this.openStart=n,this.openEnd=i}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let i=RV(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return i&&new mn(i,this.openStart,this.openEnd)}removeBetween(t,n){return new mn(DV(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return mn.empty;let i=n.openStart||0,o=n.openEnd||0;if(typeof i!="number"||typeof o!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new mn(sn.fromJSON(t,n.content),i,o)}static maxOpen(t,n=!0){let i=0,o=0;for(let s=t.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)i++;for(let s=t.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)o++;return new mn(t,i,o)}}mn.empty=new mn(sn.empty,0,0);function DV(e,t,n){let{index:i,offset:o}=e.findIndex(t),s=e.maybeChild(i),{index:r,offset:l}=e.findIndex(n);if(o==t||s.isText){if(l!=n&&!e.child(r).isText)throw new RangeError("Removing non-flat range");return e.cut(0,t).append(e.cut(n))}if(i!=r)throw new RangeError("Removing non-flat range");return e.replaceChild(i,s.copy(DV(s.content,t-o-1,n-o-1)))}function RV(e,t,n,i,o,s){let{index:r,offset:l}=e.findIndex(t),a=e.maybeChild(r);if(l==t||a.isText)return s&&i<=0&&o<=0&&!s.canReplace(r,r,n)?null:e.cut(0,t).append(n).append(e.cut(t));let u=RV(a.content,t-l-1,n,r==0?i-1:0,r==e.childCount-1?o-1:0,a);return u&&e.replaceChild(r,a.copy(u))}function oIe(e,t,n){if(n.openStart>e.depth)throw new zv("Inserted content deeper than insertion position");if(e.depth-n.openStart!=t.depth-n.openEnd)throw new zv("Inconsistent open depths");return OV(e,t,n,0)}function OV(e,t,n,i){let o=e.index(i),s=e.node(i);if(o==t.index(i)&&i=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function iv(e,t,n,i){let o=(t||e).node(n),s=0,r=t?t.index(n):o.childCount;e&&(s=e.index(n),e.depth>n?s++:e.textOffset&&(lp(e.nodeAfter,i),s++));for(let l=s;lo&&h6(e,t,o+1),r=i.depth>o&&h6(n,i,o+1),l=[];return iv(null,e,o,l),s&&r&&t.index(o)==n.index(o)?(PV(s,r),lp(ap(s,BV(e,t,n,i,o+1)),l)):(s&&lp(ap(s,Eb(e,t,o+1)),l),iv(t,n,o,l),r&&lp(ap(r,Eb(n,i,o+1)),l)),iv(i,null,o,l),new sn(l)}function Eb(e,t,n){let i=[];if(iv(null,e,n,i),e.depth>n){let o=h6(e,t,n+1);lp(ap(o,Eb(e,t,n+1)),i)}return iv(t,null,n,i),new sn(i)}function sIe(e,t){let n=t.depth-e.openStart,o=t.node(n).copy(e.content);for(let s=n-1;s>=0;s--)o=t.node(s).copy(sn.from(o));return{start:o.resolveNoCache(e.openStart+n),end:o.resolveNoCache(o.content.size-e.openEnd-n)}}class jv{constructor(t,n,i){this.pos=t,this.path=n,this.parentOffset=i,this.depth=n.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,n=this.index(this.depth);if(n==t.childCount)return null;let i=this.pos-this.path[this.path.length-1],o=t.child(n);return i?t.child(n).cut(i):o}get nodeBefore(){let t=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(t).cut(0,n):t==0?null:this.parent.child(t-1)}posAtIndex(t,n){n=this.resolveDepth(n);let i=this.path[n*3],o=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=t&&this.end(n)>=t)return n;return 0}blockRange(t=this,n){if(t.pos=0;i--)if(t.pos<=this.end(i)&&(!n||n(this.node(i))))return new aIe(this,t,i);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&n<=t.content.size))throw new RangeError("Position "+n+" out of range");let i=[],o=0,s=n;for(let r=t;;){let{index:l,offset:a}=r.content.findIndex(s),u=s-a;if(i.push(r,l,o+a),!u||(r=r.child(l),r.isText))break;s=u-1,o+=a+1}return new jv(n,i,s)}static resolveCached(t,n){let i=uR.get(t);if(i)for(let s=0;st&&this.nodesBetween(t,n,s=>(i.isInSet(s.marks)&&(o=!0),!o)),o}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),$V(this.marks,t)}contentMatchAt(t){let n=this.type.contentMatch.matchFragment(this.content,0,t);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(t,n,i=sn.empty,o=0,s=i.childCount){let r=this.contentMatchAt(t).matchFragment(i,o,s),l=r&&r.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let a=o;an.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(n=>n.toJSON())),t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let i;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");i=n.marks.map(t.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(n.text,i)}let o=sn.fromJSON(t,n.content),s=t.nodeType(n.type).create(n.attrs,o,i);return s.type.checkAttrs(s.attrs),s}};up.prototype.text=void 0;class Lb extends up{constructor(t,n,i,o){if(super(t,n,null,o),!i)throw new RangeError("Empty text nodes are not allowed");this.text=i}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):$V(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,n){return this.text.slice(t,n)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new Lb(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new Lb(this.type,this.attrs,t,this.marks)}cut(t=0,n=this.text.length){return t==0&&n==this.text.length?this:this.withText(this.text.slice(t,n))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function $V(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+"("+t+")";return t}class Cp{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let i=new cIe(t,n);if(i.next==null)return Cp.empty;let o=zV(i);i.next&&i.err("Unexpected trailing text");let s=vIe(gIe(o));return yIe(s,i),s}matchType(t){for(let n=0;nu.createAndFill()));for(let u=0;u=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function n(i){t.push(i);for(let o=0;o{let s=o+(i.validEnd?"*":" ")+" ";for(let r=0;r"+t.indexOf(i.next[r].next);return s}).join(` +`)}}Cp.empty=new Cp(!0);class cIe{constructor(t,n){this.string=t,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function zV(e){let t=[];do t.push(dIe(e));while(e.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function dIe(e){let t=[];do t.push(fIe(e));while(e.next&&e.next!=")"&&e.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function fIe(e){let t=mIe(e);for(;;)if(e.eat("+"))t={type:"plus",expr:t};else if(e.eat("*"))t={type:"star",expr:t};else if(e.eat("?"))t={type:"opt",expr:t};else if(e.eat("{"))t=hIe(e,t);else break;return t}function cR(e){/\D/.test(e.next)&&e.err("Expected number, got '"+e.next+"'");let t=Number(e.next);return e.pos++,t}function hIe(e,t){let n=cR(e),i=n;return e.eat(",")&&(e.next!="}"?i=cR(e):i=-1),e.eat("}")||e.err("Unclosed braced range"),{type:"range",min:n,max:i,expr:t}}function pIe(e,t){let n=e.nodeTypes,i=n[t];if(i)return[i];let o=[];for(let s in n){let r=n[s];r.isInGroup(t)&&o.push(r)}return o.length==0&&e.err("No node type or group '"+t+"' found"),o}function mIe(e){if(e.eat("(")){let t=zV(e);return e.eat(")")||e.err("Missing closing paren"),t}else if(/\W/.test(e.next))e.err("Unexpected token '"+e.next+"'");else{let t=pIe(e,e.next).map(n=>(e.inline==null?e.inline=n.isInline:e.inline!=n.isInline&&e.err("Mixing inline and block content"),{type:"name",value:n}));return e.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function gIe(e){let t=[[]];return o(s(e,0),n()),t;function n(){return t.push([])-1}function i(r,l,a){let u={term:a,to:l};return t[r].push(u),u}function o(r,l){r.forEach(a=>a.to=l)}function s(r,l){if(r.type=="choice")return r.exprs.reduce((a,u)=>a.concat(s(u,l)),[]);if(r.type=="seq")for(let a=0;;a++){let u=s(r.exprs[a],l);if(a==r.exprs.length-1)return u;o(u,l=n())}else if(r.type=="star"){let a=n();return i(l,a),o(s(r.expr,a),a),[i(a)]}else if(r.type=="plus"){let a=n();return o(s(r.expr,l),a),o(s(r.expr,a),a),[i(a)]}else{if(r.type=="opt")return[i(l)].concat(s(r.expr,l));if(r.type=="range"){let a=l;for(let u=0;u{e[r].forEach(({term:l,to:a})=>{if(!l)return;let u;for(let c=0;c{u||o.push([l,u=[]]),u.indexOf(c)==-1&&u.push(c)})})});let s=t[i.join(",")]=new Cp(i.indexOf(e.length-1)>-1);for(let r=0;r-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:WV(this.attrs,t)}create(t=null,n,i){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new up(this,this.computeAttrs(t),sn.from(n),Fi.setFrom(i))}createChecked(t=null,n,i){return n=sn.from(n),this.checkContent(n),new up(this,this.computeAttrs(t),n,Fi.setFrom(i))}createAndFill(t=null,n,i){if(t=this.computeAttrs(t),n=sn.from(n),n.size){let r=this.contentMatch.fillBefore(n);if(!r)return null;n=r.append(n)}let o=this.contentMatch.matchFragment(n),s=o&&o.fillBefore(sn.empty,!0);return s?new up(this,t,n.append(s),Fi.setFrom(i)):null}validContent(t){let n=this.contentMatch.matchFragment(t);if(!n||!n.validEnd)return!1;for(let i=0;i-1}allowsMarks(t){if(this.markSet==null)return!0;for(let n=0;ni[s]=new VV(s,n,r));let o=n.spec.topNode||"doc";if(!i[o])throw new RangeError("Schema is missing its top node type ('"+o+"')");if(!i.text)throw new RangeError("Every schema needs a 'text' type");for(let s in i.text.attrs)throw new RangeError("The text node type should not have attributes");return i}};function kIe(e,t,n){let i=n.split("|");return o=>{let s=o===null?"null":typeof o;if(i.indexOf(s)<0)throw new RangeError(`Expected value of type ${i} for attribute ${t} on type ${e}, got ${s}`)}}class bIe{constructor(t,n,i){this.hasDefault=Object.prototype.hasOwnProperty.call(i,"default"),this.default=i.default,this.validate=typeof i.validate=="string"?kIe(t,n,i.validate):i.validate}get isRequired(){return!this.hasDefault}}class aw{constructor(t,n,i,o){this.name=t,this.rank=n,this.schema=i,this.spec=o,this.attrs=UV(t,o.attrs),this.excluded=null;let s=HV(this.attrs);this.instance=s?new Fi(this,s):null}create(t=null){return!t&&this.instance?this.instance:new Fi(this,WV(this.attrs,t))}static compile(t,n){let i=Object.create(null),o=0;return t.forEach((s,r)=>i[s]=new aw(s,o++,n,r)),i}removeFromSet(t){for(var n=0;n-1}}class wIe{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let o in t)n[o]=t[o];n.nodes=tr.from(t.nodes),n.marks=tr.from(t.marks||{}),this.nodes=fR.compile(this.spec.nodes,this),this.marks=aw.compile(this.spec.marks,this);let i=Object.create(null);for(let o in this.nodes){if(o in this.marks)throw new RangeError(o+" can not be both a node and a mark");let s=this.nodes[o],r=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=i[r]||(i[r]=Cp.parse(r,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?hR(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let o in this.marks){let s=this.marks[o],r=s.spec.excludes;s.excluded=r==null?[s]:r==""?[]:hR(this,r.split(" "))}this.nodeFromJSON=o=>up.fromJSON(this,o),this.markFromJSON=o=>Fi.fromJSON(this,o),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,n=null,i,o){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof fR){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(n,i,o)}text(t,n){let i=this.nodes.text;return new Lb(i,i.defaultAttrs,t,Fi.setFrom(n))}mark(t,n){return typeof t=="string"&&(t=this.marks[t]),t.create(n)}nodeType(t){let n=this.nodes[t];if(!n)throw new RangeError("Unknown node type: "+t);return n}}function hR(e,t){let n=[];for(let i=0;i-1)&&n.push(r=a)}if(!r)throw new SyntaxError("Unknown mark type: '"+t[i]+"'")}return n}function CIe(e){return e.tag!=null}function AIe(e){return e.style!=null}let KV=class m6{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let i=this.matchedStyles=[];n.forEach(o=>{if(CIe(o))this.tags.push(o);else if(AIe(o)){let s=/[^=]*/.exec(o.style)[0];i.indexOf(s)<0&&i.push(s),this.styles.push(o)}}),this.normalizeLists=!this.tags.some(o=>{if(!/^(ul|ol)\b/.test(o.tag)||!o.node)return!1;let s=t.nodes[o.node];return s.contentMatch.matchType(s)})}parse(t,n={}){let i=new mR(this,n,!1);return i.addAll(t,Fi.none,n.from,n.to),i.finish()}parseSlice(t,n={}){let i=new mR(this,n,!0);return i.addAll(t,Fi.none,n.from,n.to),mn.maxOpen(i.finish())}matchTag(t,n,i){for(let o=i?this.tags.indexOf(i)+1:0;ot.length&&(l.charCodeAt(t.length)!=61||l.slice(t.length+1)!=n))){if(r.getAttrs){let a=r.getAttrs(n);if(a===!1)continue;r.attrs=a||void 0}return r}}}static schemaRules(t){let n=[];function i(o){let s=o.priority==null?50:o.priority,r=0;for(;r{i(r=gR(r)),r.mark||r.ignore||r.clearMark||(r.mark=o)})}for(let o in t.nodes){let s=t.nodes[o].spec.parseDOM;s&&s.forEach(r=>{i(r=gR(r)),r.node||r.ignore||r.mark||(r.node=o)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new m6(t,m6.schemaRules(t)))}};const ZV={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},xIe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},GV={ol:!0,ul:!0},Hv=1,g6=2,ov=4;function pR(e,t,n){return t!=null?(t?Hv:0)|(t==="full"?g6:0):e&&e.whitespace=="pre"?Hv|g6:n&~ov}class Jy{constructor(t,n,i,o,s,r){this.type=t,this.attrs=n,this.marks=i,this.solid=o,this.options=r,this.content=[],this.activeMarks=Fi.none,this.match=s||(r&ov?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(sn.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let i=this.type.contentMatch,o;return(o=i.findWrapping(t.type))?(this.match=i,o):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&Hv)){let i=this.content[this.content.length-1],o;if(i&&i.isText&&(o=/[ \t\r\n\u000c]+$/.exec(i.text))){let s=i;i.text.length==o[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-o[0].length))}}let n=sn.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(sn.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!ZV.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class mR{constructor(t,n,i){this.parser=t,this.options=n,this.isOpen=i,this.open=0,this.localPreserveWS=!1;let o=n.topNode,s,r=pR(null,n.preserveWhitespace,0)|(i?ov:0);o?s=new Jy(o.type,o.attrs,Fi.none,!0,n.topMatch||o.type.contentMatch,r):i?s=new Jy(null,null,Fi.none,!0,null,r):s=new Jy(t.schema.topNodeType,null,Fi.none,!0,null,r),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,n){t.nodeType==3?this.addTextNode(t,n):t.nodeType==1&&this.addElement(t,n)}addTextNode(t,n){let i=t.nodeValue,o=this.top,s=o.options&g6?"full":this.localPreserveWS||(o.options&Hv)>0,{schema:r}=this.parser;if(s==="full"||o.inlineContext(t)||/[^ \t\r\n\u000c]/.test(i)){if(s)if(s==="full")i=i.replace(/\r\n?/g,` +`);else if(r.linebreakReplacement&&/[\r\n]/.test(i)&&this.top.findWrapping(r.linebreakReplacement.create())){let l=i.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(u)):n=n.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return n}addElementByRule(t,n,i,o){let s,r;if(n.node)if(r=this.parser.schema.nodes[n.node],r.isLeaf)this.insertNode(r.create(n.attrs),i,t.nodeName=="BR")||this.leafFallback(t,i);else{let a=this.enter(r,n.attrs||null,i,n.preserveWhitespace);a&&(s=!0,i=a)}else{let a=this.parser.schema.marks[n.mark];i=i.concat(a.create(n.attrs))}let l=this.top;if(r&&r.isLeaf)this.findInside(t);else if(o)this.addElement(t,i,o);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(a=>this.insertNode(a,i,!1));else{let a=t;typeof n.contentElement=="string"?a=t.querySelector(n.contentElement):typeof n.contentElement=="function"?a=n.contentElement(t):n.contentElement&&(a=n.contentElement),this.findAround(t,a,!0),this.addAll(a,i),this.findAround(t,a,!1)}s&&this.sync(l)&&this.open--}addAll(t,n,i,o){let s=i||0;for(let r=i?t.childNodes[i]:t.firstChild,l=o==null?null:t.childNodes[o];r!=l;r=r.nextSibling,++s)this.findAtPoint(t,s),this.addDOM(r,n);this.findAtPoint(t,s)}findPlace(t,n,i){let o,s;for(let r=this.open,l=0;r>=0;r--){let a=this.nodes[r],u=a.findWrapping(t);if(u&&(!o||o.length>u.length+l)&&(o=u,s=a,!u.length))break;if(a.solid){if(i)break;l+=2}}if(!o)return null;this.sync(s);for(let r=0;r(r.type?r.type.allowsMarkType(u.type):vR(u.type,t))?(a=u.addToSet(a),!1):!0),this.nodes.push(new Jy(t,n,a,o,null,l)),this.open++,i}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let n=this.open;n>=0;n--){if(this.nodes[n]==t)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Hv)}return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let i=this.nodes[n].content;for(let o=i.length-1;o>=0;o--)t+=i[o].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let i=0;i-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),i=this.options.context,o=!this.isOpen&&(!i||i.parent.type==this.nodes[0].type),s=-(i?i.depth+1:0)+(o?0:1),r=(l,a)=>{for(;l>=0;l--){let u=n[l];if(u==""){if(l==n.length-1||l==0)continue;for(;a>=s;a--)if(r(l-1,a))return!0;return!1}else{let c=a>0||a==0&&o?this.nodes[a].type:i&&a>=s?i.node(a-s).type:null;if(!c||c.name!=u&&!c.isInGroup(u))return!1;a--}}return!0};return r(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let i=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(i&&i.isTextblock&&i.defaultAttrs)return i}for(let n in this.parser.schema.nodes){let i=this.parser.schema.nodes[n];if(i.isTextblock&&i.defaultAttrs)return i}}}function SIe(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let i=t.nodeType==1?t.nodeName.toLowerCase():null;i&&GV.hasOwnProperty(i)&&n?(n.appendChild(t),t=n):i=="li"?n=t:i&&(n=null)}}function _Ie(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function gR(e){let t={};for(let n in e)t[n]=e[n];return t}function vR(e,t){let n=t.schema.nodes;for(let i in n){let o=n[i];if(!o.allowsMarkType(e))continue;let s=[],r=l=>{s.push(l);for(let a=0;a{if(s.length||r.marks.length){let l=0,a=0;for(;l=0;o--){let s=this.serializeMark(t.marks[o],t.isInline,n);s&&((s.contentDOM||s.dom).appendChild(i),i=s.dom)}return i}serializeMark(t,n,i={}){let o=this.marks[t.type.name];return o&&Y9(Xy(i),o(t,n),null,t.attrs)}static renderSpec(t,n,i=null,o){return typeof n=="string"?{dom:t.createTextNode(n)}:Y9(t,n,i,o)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new uc(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=yR(t.nodes);return n.text||(n.text=i=>i.text),n}static marksFromSchema(t){return yR(t.marks)}}function yR(e){let t={};for(let n in e){let i=e[n].spec.toDOM;i&&(t[n]=i)}return t}function Xy(e){return e.document||window.document}const kR=new WeakMap;function IIe(e){let t=kR.get(e);return t===void 0&&kR.set(e,t=MIe(e)),t}function MIe(e){let t=null;function n(i){if(i&&typeof i=="object")if(Array.isArray(i))if(typeof i[0]=="string")t||(t=[]),t.push(i);else for(let o=0;o-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let r=o.indexOf(" ");r>0&&(n=o.slice(0,r),o=o.slice(r+1));let l,a=n?e.createElementNS(n,o):e.createElement(o),u=t[1],c=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){c=2;for(let d in u)if(u[d]!=null){let f=d.indexOf(" ");f>0?a.setAttributeNS(d.slice(0,f),d.slice(f+1),u[d]):d=="style"&&a.style?a.style.cssText=u[d]:a.setAttribute(d,u[d])}}for(let d=c;dc)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof f=="string")a.appendChild(e.createTextNode(f));else{let{dom:h,contentDOM:m}=Y9(e,f,n,i);if(a.appendChild(h),m){if(l)throw new RangeError("Multiple content holes");l=m}}}return{dom:a,contentDOM:l}}const ri=new wIe({nodes:{doc:{content:"block+"},paragraph:{group:"block",content:"inline*",toDOM:()=>["p",0],parseDOM:[{tag:"p"}]},text:{group:"inline"},mention:{group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{kind:{},name:{},path:{default:""}},leafText:e=>Rp(e.attrs),toDOM:e=>{const t=e.attrs;return["span",{class:`mention-pill mention-${t.kind}`,"data-mention-path":t.path},t.name]}},attachment:{group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{attId:{},name:{},kind:{}},leafText:e=>Nf(e.attrs),toDOM:e=>{const t=e.attrs;return["span",{class:`attachment-pill attachment-${t.kind}`,"data-attachment-id":t.attId,"data-attachment-kind":t.kind,"data-attachment-name":t.name},t.name]}},quote:{group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{text:{},comment:{default:""},source:{default:""}},leafText:e=>sw(e.attrs),toDOM:e=>{const t=e.attrs,n={class:"quote-pill","data-quote-text":t.text};return typeof t.comment=="string"&&t.comment.length>0&&(n["data-quote-comment"]=t.comment),typeof t.source=="string"&&t.source.length>0&&(n["data-quote-source"]=t.source),["span",n,Mm(t.text)]}}}});function QV(e){return ri.nodes.mention.create(e)}function YV(e){return ri.nodes.attachment.create(e)}function JV(e){return ri.nodes.quote.create(e)}function TIe(e,t){return e?_V(e,t).map(n=>n.type==="mention"?QV(n.attrs):n.type==="attachment"?YV(n.attrs):n.type==="quote"?JV(n.attrs):ri.text(n.value)):[]}function Wv(e,t){const n=e.split(` +`);return ri.node("doc",null,n.map(i=>i?ri.node("paragraph",null,t?.reviveMentions?TIe(i,t?.attachmentKindFor):ri.text(i)):ri.node("paragraph")))}function qv(e){return e.textBetween(0,e.content.size,` +`)}const XV=65535,eK=Math.pow(2,16);function EIe(e,t){return e+t*eK}function bR(e){return e&XV}function LIe(e){return(e-(e&XV))/eK}const tK=1,nK=2,J9=4,iK=8;class v6{constructor(t,n,i){this.pos=t,this.delInfo=n,this.recover=i}get deleted(){return(this.delInfo&iK)>0}get deletedBefore(){return(this.delInfo&(tK|J9))>0}get deletedAfter(){return(this.delInfo&(nK|J9))>0}get deletedAcross(){return(this.delInfo&J9)>0}}class ia{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&ia.empty)return ia.empty}recover(t){let n=0,i=bR(t);if(!this.inverted)for(let o=0;ot)break;let u=this.ranges[l+s],c=this.ranges[l+r],d=a+u;if(t<=d){let f=u?t==a?-1:t==d?1:n:n,h=a+o+(f<0?0:c);if(i)return h;let m=t==(n<0?a:d)?null:EIe(l/3,t-a),g=t==a?nK:t==d?tK:J9;return(n<0?t!=a:t!=d)&&(g|=iK),new v6(h,g,m)}o+=c-u}return i?t+o:new v6(t+o,0,null)}touches(t,n){let i=0,o=bR(n),s=this.inverted?2:1,r=this.inverted?1:2;for(let l=0;lt)break;let u=this.ranges[l+s],c=a+u;if(t<=c&&l==o*3)return!0;i+=this.ranges[l+r]-u}return!1}forEach(t){let n=this.inverted?2:1,i=this.inverted?1:2;for(let o=0,s=0;o=0;n--){let o=t.getMirror(n);this.appendMap(t._maps[n].invert(),o!=null&&o>n?i-o-1:void 0)}}invert(){let t=new Uv;return t.appendMappingInverted(this),t}map(t,n=1){if(this.mirror)return this._map(t,n,!0);for(let i=this.from;is&&a!r.isAtom||!l.type.allowsMarkType(this.mark.type)?r:r.mark(this.mark.addToSet(r.marks)),o),n.openStart,n.openEnd);return fs.fromReplace(t,this.from,this.to,s)}invert(){return new nc(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),i=t.mapResult(this.to,-1);return n.deleted&&i.deleted||n.pos>=i.pos?null:new nf(n.pos,i.pos,this.mark)}merge(t){return t instanceof nf&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new nf(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new nf(n.from,n.to,t.markFromJSON(n.mark))}}Nr.jsonID("addMark",nf);class nc extends Nr{constructor(t,n,i){super(),this.from=t,this.to=n,this.mark=i}apply(t){let n=t.slice(this.from,this.to),i=new mn(FS(n.content,o=>o.mark(this.mark.removeFromSet(o.marks)),t),n.openStart,n.openEnd);return fs.fromReplace(t,this.from,this.to,i)}invert(){return new nf(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),i=t.mapResult(this.to,-1);return n.deleted&&i.deleted||n.pos>=i.pos?null:new nc(n.pos,i.pos,this.mark)}merge(t){return t instanceof nc&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new nc(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new nc(n.from,n.to,t.markFromJSON(n.mark))}}Nr.jsonID("removeMark",nc);class of extends Nr{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return fs.fail("No node at mark step's position");let i=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return fs.fromReplace(t,this.pos,this.pos+1,new mn(sn.from(i),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let i=this.mark.addToSet(n.marks);if(i.length==n.marks.length){for(let o=0;oi.pos?null:new ca(n.pos,i.pos,o,s,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new ca(n.from,n.to,n.gapFrom,n.gapTo,mn.fromJSON(t,n.slice),n.insert,!!n.structure)}}Nr.jsonID("replaceAround",ca);function y6(e,t,n){let i=e.resolve(t),o=n-t,s=i.depth;for(;o>0&&s>0&&i.indexAfter(s)==i.node(s).childCount;)s--,o--;if(o>0){let r=i.node(s).maybeChild(i.indexAfter(s));for(;o>0;){if(!r||r.isLeaf)return!0;r=r.firstChild,o--}}return!1}function NIe(e,t,n,i){let o=[],s=[],r,l;e.doc.nodesBetween(t,n,(a,u,c)=>{if(!a.isInline)return;let d=a.marks;if(!i.isInSet(d)&&c.type.allowsMarkType(i.type)){let f=Math.max(u,t),h=Math.min(u+a.nodeSize,n),m=i.addToSet(d);for(let g=0;ge.step(a)),s.forEach(a=>e.step(a))}function FIe(e,t,n,i){let o=[],s=0;e.doc.nodesBetween(t,n,(r,l)=>{if(!r.isInline)return;s++;let a=null;if(i instanceof aw){let u=r.marks,c;for(;c=i.isInSet(u);)(a||(a=[])).push(c),u=c.removeFromSet(u)}else i?i.isInSet(r.marks)&&(a=[i]):a=r.marks;if(a&&a.length){let u=Math.min(l+r.nodeSize,n);for(let c=0;ce.step(new nc(r.from,r.to,r.style)))}function DS(e,t,n,i=n.contentMatch,o=!0){let s=e.doc.nodeAt(t),r=[],l=t+1;for(let a=0;a=0;a--)e.step(r[a])}function DIe(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function RS(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let i=e.depth,o=0,s=0;;--i){let r=e.$from.node(i),l=e.$from.index(i)+o,a=e.$to.indexAfter(i)-s;if(in;m--)g||i.index(m)>0?(g=!0,c=sn.from(i.node(m).copy(c)),d++):a--;let f=sn.empty,h=0;for(let m=s,g=!1;m>n;m--)g||o.after(m+1)=0;r--){if(i.size){let l=n[r].type.contentMatch.matchFragment(i);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}i=sn.from(n[r].type.create(n[r].attrs,i))}let o=t.start,s=t.end;e.step(new ca(o,s,o,s,new mn(i,0,0),n.length,!0))}function PIe(e,t,n,i,o){if(!i.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=e.steps.length;e.doc.nodesBetween(t,n,(r,l)=>{let a=typeof o=="function"?o(r):o;if(r.isTextblock&&!r.hasMarkup(i,a)&&BIe(e.doc,e.mapping.slice(s).map(l),i)){let u=null;if(i.schema.linebreakReplacement){let h=i.whitespace=="pre",m=!!i.contentMatch.matchType(i.schema.linebreakReplacement);h&&!m?u=!1:!h&&m&&(u=!0)}u===!1&&sK(e,r,l,s),DS(e,e.mapping.slice(s).map(l,1),i,void 0,u===null);let c=e.mapping.slice(s),d=c.map(l,1),f=c.map(l+r.nodeSize,1);return e.step(new ca(d,f,d+1,f-1,new mn(sn.from(i.create(a,null,r.marks)),0,0),1,!0)),u===!0&&oK(e,r,l,s),!1}})}function oK(e,t,n,i){t.forEach((o,s)=>{if(o.isText){let r,l=/\r?\n|\r/g;for(;r=l.exec(o.text);){let a=e.mapping.slice(i).map(n+1+s+r.index);e.replaceWith(a,a+1,t.type.schema.linebreakReplacement.create())}}})}function sK(e,t,n,i){t.forEach((o,s)=>{if(o.type==o.type.schema.linebreakReplacement){let r=e.mapping.slice(i).map(n+1+s);e.replaceWith(r,r+1,t.type.schema.text(` +`))}})}function BIe(e,t,n){let i=e.resolve(t),o=i.index();return i.parent.canReplaceWith(o,o+1,n)}function $Ie(e,t,n,i,o){let s=e.doc.nodeAt(t);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let r=n.create(i,null,o||s.marks);if(s.isLeaf)return e.replaceWith(t,t+s.nodeSize,r);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);e.step(new ca(t,t+s.nodeSize,t+1,t+s.nodeSize-1,new mn(sn.from(r),0,0),1,!0))}function X9(e,t,n=1,i){let o=e.resolve(t),s=o.depth-n,r=i&&i[i.length-1]||o.parent;if(s<0||o.parent.type.spec.isolating||!o.parent.canReplace(o.index(),o.parent.childCount)||!r.type.validContent(o.parent.content.cutByIndex(o.index(),o.parent.childCount)))return!1;for(let u=o.depth-1,c=n-2;u>s;u--,c--){let d=o.node(u),f=o.index(u);if(d.type.spec.isolating)return!1;let h=d.content.cutByIndex(f,d.childCount),m=i&&i[c+1];m&&(h=h.replaceChild(0,m.type.create(m.attrs)));let g=i&&i[c]||d;if(!d.canReplace(f+1,d.childCount)||!g.type.validContent(h))return!1}let l=o.indexAfter(s),a=i&&i[0];return o.node(s).canReplaceWith(l,l,a?a.type:o.node(s+1).type)}function zIe(e,t,n=1,i){let o=e.doc.resolve(t),s=sn.empty,r=sn.empty;for(let l=o.depth,a=o.depth-n,u=n-1;l>a;l--,u--){s=sn.from(o.node(l).copy(s));let c=i&&i[u];r=sn.from(c?c.type.create(c.attrs,r):o.node(l).copy(r))}e.step(new Gs(t,t,new mn(s.append(r),n,n),!0))}function rK(e,t){let n=e.resolve(t),i=n.index();return HIe(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(i,i+1)}function jIe(e,t){t.content.size||e.type.compatibleContent(t.type);let n=e.contentMatchAt(e.childCount),{linebreakReplacement:i}=e.type.schema;for(let o=0;o=0;o--){let s=i.index(o);if(i.node(o).canReplaceWith(s,s,n))return i.before(o+1);if(s>0)return null}if(i.parentOffset==i.parent.content.size)for(let o=i.depth-1;o>=0;o--){let s=i.indexAfter(o);if(i.node(o).canReplaceWith(s,s,n))return i.after(o+1);if(s=0;r--){let l=r==i.depth?0:i.pos<=(i.start(r+1)+i.end(r+1))/2?-1:1,a=i.index(r)+(l>0?1:0),u=i.node(r),c=!1;if(s==1)c=u.canReplace(a,a,o);else{let d=u.contentMatchAt(a).findWrapping(o.firstChild.type);c=d&&u.canReplaceWith(a,a,d[0])}if(c)return l==0?i.pos:l<0?i.before(r+1):i.after(r+1)}return null}function OS(e,t,n=t,i=mn.empty){if(t==n&&!i.size)return null;let o=e.resolve(t),s=e.resolve(n);return lK(o,s,i)?new Gs(t,n,i):new VIe(o,s,i).fit()}function lK(e,t,n){return!n.openStart&&!n.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),n.content)}class VIe{constructor(t,n,i){this.$from=t,this.$to=n,this.unplaced=i,this.frontier=[],this.placed=sn.empty;for(let o=0;o<=t.depth;o++){let s=t.node(o);this.frontier.push({type:s.type,match:s.contentMatchAt(t.indexAfter(o))})}for(let o=t.depth;o>0;o--)this.placed=sn.from(t.node(o).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let u=this.findFittable();u?this.placeNodes(u):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,i=this.$from,o=this.close(t<0?this.$to:i.doc.resolve(t));if(!o)return null;let s=this.placed,r=i.depth,l=o.depth;for(;r&&l&&s.childCount==1;)s=s.firstChild.content,r--,l--;let a=new mn(s,r,l);return t>-1?new ca(i.pos,t,this.$to.pos,this.$to.end(),a,n):a.size||i.pos!=this.$to.pos?new Gs(i.pos,o.pos,a):null}findFittable(){let t=this.unplaced.openStart;for(let n=this.unplaced.content,i=0,o=this.unplaced.openEnd;i1&&(o=0),s.type.spec.isolating&&o<=i){t=i;break}n=s.content}for(let n=1;n<=2;n++)for(let i=n==1?t:this.unplaced.openStart;i>=0;i--){let o,s=null;i?(s=V8(this.unplaced.content,i-1).firstChild,o=s.content):o=this.unplaced.content;let r=o.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:u}=this.frontier[l],c,d=null;if(n==1&&(r?u.matchType(r.type)||(d=u.fillBefore(sn.from(r),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:i,frontierDepth:l,parent:s,inject:d};if(n==2&&r&&(c=u.findWrapping(r.type)))return{sliceDepth:i,frontierDepth:l,parent:s,wrap:c};if(s&&u.matchType(s.type))break}}}openMore(){let{content:t,openStart:n,openEnd:i}=this.unplaced,o=V8(t,n);return!o.childCount||o.firstChild.isLeaf?!1:(this.unplaced=new mn(t,n+1,Math.max(i,o.size+n>=t.size-i?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:i}=this.unplaced,o=V8(t,n);if(o.childCount<=1&&n>0){let s=t.size-n<=n+o.size;this.unplaced=new mn(m0(t,n-1,1),n-1,s?n-1:i)}else this.unplaced=new mn(m0(t,n,1),n,i)}placeNodes({sliceDepth:t,frontierDepth:n,parent:i,inject:o,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let g=0;g1||a==0||g.content.size)&&(d=y,c.push(aK(g.mark(f.allowedMarks(g.marks)),u==1?a:0,u==l.childCount?h:-1)))}let m=u==l.childCount;m||(h=-1),this.placed=g0(this.placed,n,sn.from(c)),this.frontier[n].match=d,m&&h<0&&i&&i.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let g=0,y=l;g1&&o==this.$to.end(--i);)++o;return o}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:i,type:o}=this.frontier[n],s=n=0;l--){let{match:a,type:u}=this.frontier[l],c=K8(t,l,u,a,!0);if(!c||c.childCount)continue e}return{depth:n,fit:r,move:s?t.doc.resolve(t.after(n+1)):t}}}}close(t){let n=this.findCloseLevel(t);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=g0(this.placed,n.depth,n.fit)),t=n.move;for(let i=n.depth+1;i<=t.depth;i++){let o=t.node(i),s=o.type.contentMatch.fillBefore(o.content,!0,t.index(i));this.openFrontierNode(o.type,o.attrs,s)}return t}openFrontierNode(t,n=null,i){let o=this.frontier[this.depth];o.match=o.match.matchType(t),this.placed=g0(this.placed,this.depth,sn.from(t.create(n,i))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(sn.empty,!0);n.childCount&&(this.placed=g0(this.placed,this.frontier.length,n))}}function m0(e,t,n){return t==0?e.cutByIndex(n,e.childCount):e.replaceChild(0,e.firstChild.copy(m0(e.firstChild.content,t-1,n)))}function g0(e,t,n){return t==0?e.append(n):e.replaceChild(e.childCount-1,e.lastChild.copy(g0(e.lastChild.content,t-1,n)))}function V8(e,t){for(let n=0;n1&&(i=i.replaceChild(0,aK(i.firstChild,t-1,i.childCount==1?n-1:0))),t>0&&(i=e.type.contentMatch.fillBefore(i).append(i),n<=0&&(i=i.append(e.type.contentMatch.matchFragment(i).fillBefore(sn.empty,!0)))),e.copy(i)}function K8(e,t,n,i,o){let s=e.node(t),r=o?e.indexAfter(t):e.index(t);if(r==s.childCount&&!n.compatibleContent(s.type))return null;let l=i.fillBefore(s.content,!0,r);return l&&!KIe(n,s.content,r)?l:null}function KIe(e,t,n){for(let i=n;i0;f--,h--){let m=o.node(f).type.spec;if(m.defining||m.definingAsContext||m.isolating)break;r.indexOf(f)>-1?l=f:o.before(f)==h&&r.splice(1,0,-f)}let a=r.indexOf(l),u=[],c=i.openStart;for(let f=i.content,h=0;;h++){let m=f.firstChild;if(u.push(m),h==i.openStart)break;f=m.content}for(let f=c-1;f>=0;f--){let h=u[f],m=ZIe(h.type);if(m&&!h.sameMarkup(o.node(Math.abs(l)-1)))c=f;else if(m||!h.type.isTextblock)break}for(let f=i.openStart;f>=0;f--){let h=(f+c+1)%(i.openStart+1),m=u[h];if(m)for(let g=0;g=0&&(e.replace(t,n,i),!(e.steps.length>d));f--){let h=r[f];h<0||(t=o.before(h),n=s.after(h))}}function uK(e,t,n,i,o){if(ti){let s=o.contentMatchAt(0),r=s.fillBefore(e).append(e);e=r.append(s.matchFragment(r).fillBefore(sn.empty,!0))}return e}function QIe(e,t,n,i){if(!i.isInline&&t==n&&e.doc.resolve(t).parent.content.size){let o=qIe(e.doc,t,i.type);o!=null&&(t=n=o)}e.replaceRange(t,n,new mn(sn.from(i),0,0))}function YIe(e,t,n){let i=e.doc.resolve(t),o=e.doc.resolve(n);if(i.parent.isTextblock&&o.parent.isTextblock&&i.start()!=o.start()&&i.parentOffset==0&&o.parentOffset==0){let r=i.sharedDepth(n),l=!1;for(let a=i.depth;a>r;a--)i.node(a).type.spec.isolating&&(l=!0);for(let a=o.depth;a>r;a--)o.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);for(let a=o.depth;a>0&&n==o.start(a);a--)n=o.before(a);i=e.doc.resolve(t),o=e.doc.resolve(n)}}let s=cK(i,o);for(let r=0;r0&&(a||i.node(l-1).canReplace(i.index(l-1),o.indexAfter(l-1))))return e.delete(i.before(l),o.after(l))}for(let r=1;r<=i.depth&&r<=o.depth;r++)if(t-i.start(r)==i.depth-r&&n>i.end(r)&&o.end(r)-n!=o.depth-r&&i.start(r-1)==o.start(r-1)&&i.node(r-1).canReplace(i.index(r-1),o.index(r-1)))return e.delete(i.before(r),n);e.delete(t,n)}function cK(e,t){let n=[],i=Math.min(e.depth,t.depth);for(let o=i;o>=0;o--){let s=e.start(o);if(st.pos+(t.depth-o)||e.node(o).type.spec.isolating||t.node(o).type.spec.isolating)break;(s==t.start(o)||o==e.depth&&o==t.depth&&e.parent.inlineContent&&t.parent.inlineContent&&o&&t.start(o-1)==s-1)&&n.push(o)}return n}class dm extends Nr{constructor(t,n,i){super(),this.pos=t,this.attr=n,this.value=i}apply(t){let n=t.nodeAt(this.pos);if(!n)return fs.fail("No node at attribute step's position");let i=Object.create(null);for(let s in n.attrs)i[s]=n.attrs[s];i[this.attr]=this.value;let o=n.type.create(i,null,n.marks);return fs.fromReplace(t,this.pos,this.pos+1,new mn(sn.from(o),0,n.isLeaf?0:1))}getMap(){return ia.empty}invert(t){return new dm(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new dm(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new dm(n.pos,n.attr,n.value)}}Nr.jsonID("attr",dm);class Vv extends Nr{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let o in t.attrs)n[o]=t.attrs[o];n[this.attr]=this.value;let i=t.type.create(n,t.content,t.marks);return fs.ok(i)}getMap(){return ia.empty}invert(t){return new Vv(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Vv(n.attr,n.value)}}Nr.jsonID("docAttr",Vv);let Tm=class extends Error{};Tm=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n};Tm.prototype=Object.create(Error.prototype);Tm.prototype.constructor=Tm;Tm.prototype.name="TransformError";class JIe{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new Uv}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new Tm(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let i=0;i{t=Math.min(t,l),n=Math.max(n,a)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,i=mn.empty){let o=OS(this.doc,t,n,i);return o&&this.step(o),this}replaceWith(t,n,i){return this.replace(t,n,new mn(sn.from(i),0,0))}delete(t,n){return this.replace(t,n,mn.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,i){return GIe(this,t,n,i),this}replaceRangeWith(t,n,i){return QIe(this,t,n,i),this}deleteRange(t,n){return YIe(this,t,n),this}lift(t,n){return RIe(this,t,n),this}join(t,n=1){return WIe(this,t,n),this}wrap(t,n){return OIe(this,t,n),this}setBlockType(t,n=t,i,o=null){return PIe(this,t,n,i,o),this}setNodeMarkup(t,n,i=null,o){return $Ie(this,t,n,i,o),this}setNodeAttribute(t,n,i){return this.step(new dm(t,n,i)),this}setDocAttribute(t,n){return this.step(new Vv(t,n)),this}addNodeMark(t,n){return this.step(new of(t,n)),this}removeNodeMark(t,n){let i=this.doc.nodeAt(t);if(!i)throw new RangeError("No node at position "+t);if(n instanceof Fi)n.isInSet(i.marks)&&this.step(new Ap(t,n));else{let o=i.marks,s,r=[];for(;s=n.isInSet(o);)r.push(new Ap(t,s)),o=s.removeFromSet(o);for(let l=r.length-1;l>=0;l--)this.step(r[l])}return this}split(t,n=1,i){return zIe(this,t,n,i),this}addMark(t,n,i){return NIe(this,t,n,i),this}removeMark(t,n,i){return FIe(this,t,n,i),this}clearIncompatible(t,n,i){return DS(this,t,n,i),this}}const Z8=Object.create(null);class Bi{constructor(t,n,i){this.$anchor=t,this.$head=n,this.ranges=i||[new XIe(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n=0;s--){let r=n<0?I1(t.node(0),t.node(s),t.before(s+1),t.index(s),n,i):I1(t.node(0),t.node(s),t.after(s+1),t.index(s)+1,n,i);if(r)return r}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new da(t.node(0))}static atStart(t){return I1(t,t,0,0,1)||new da(t)}static atEnd(t){return I1(t,t,t.content.size,t.childCount,-1)||new da(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let i=Z8[n.type];if(!i)throw new RangeError(`No selection type ${n.type} defined`);return i.fromJSON(t,n)}static jsonID(t,n){if(t in Z8)throw new RangeError("Duplicate use of selection JSON ID "+t);return Z8[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Xn.between(this.$anchor,this.$head).getBookmark()}}Bi.prototype.visible=!0;class XIe{constructor(t,n){this.$from=t,this.$to=n}}let wR=!1;function CR(e){!wR&&!e.parent.inlineContent&&(wR=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+e.parent.type.name+")"))}class Xn extends Bi{constructor(t,n=t){CR(t),CR(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let i=t.resolve(n.map(this.head));if(!i.parent.inlineContent)return Bi.near(i);let o=t.resolve(n.map(this.anchor));return new Xn(o.parent.inlineContent?o:i,i)}replace(t,n=mn.empty){if(super.replace(t,n),n==mn.empty){let i=this.$from.marksAcross(this.$to);i&&t.ensureMarks(i)}}eq(t){return t instanceof Xn&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new uw(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Xn(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,i=n){let o=t.resolve(n);return new this(o,i==n?o:t.resolve(i))}static between(t,n,i){let o=t.pos-n.pos;if((!i||o)&&(i=o>=0?1:-1),!n.parent.inlineContent){let s=Bi.findFrom(n,i,!0)||Bi.findFrom(n,-i,!0);if(s)n=s.$head;else return Bi.near(n,i)}return t.parent.inlineContent||(o==0?t=n:(t=(Bi.findFrom(t,-i,!0)||Bi.findFrom(t,i,!0)).$anchor,t.pos0?0:1);o>0?r=0;r+=o){let l=t.child(r);if(l.isAtom){if(!s&&Kn.isSelectable(l))return Kn.create(e,n-(o<0?l.nodeSize:0))}else{let a=I1(e,l,n+o,o<0?l.childCount:0,o,s);if(a)return a}n+=l.nodeSize*o}return null}function AR(e,t,n){let i=e.steps.length-1;if(i{r==null&&(r=c)}),e.setSelection(Bi.near(e.doc.resolve(r),n))}const xR=1,e9=2,SR=4;class tMe extends JIe{constructor(t){super(t.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(t){return this.storedMarks=t,this.updated|=e9,this}ensureMarks(t){return Fi.sameSet(this.storedMarks||this.selection.$from.marks(),t)||this.setStoredMarks(t),this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&e9)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~e9,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,n=!0){let i=this.selection;return n&&(t=t.mark(this.storedMarks||(i.empty?i.$from.marks():i.$from.marksAcross(i.$to)||Fi.none))),i.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,n,i){let o=this.doc.type.schema;if(n==null)return t?this.replaceSelectionWith(o.text(t),!0):this.deleteSelection();{if(i==null&&(i=n),!t)return this.deleteRange(n,i);let s=this.storedMarks;if(!s){let r=this.doc.resolve(n);s=i==n?r.marks():r.marksAcross(this.doc.resolve(i))}return this.replaceRangeWith(n,i,o.text(t,s)),!this.selection.empty&&this.selection.to==n+t.length&&this.setSelection(Bi.near(this.selection.$to)),this}}setMeta(t,n){return this.meta[typeof t=="string"?t:t.key]=n,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=SR,this}get scrolledIntoView(){return(this.updated&SR)>0}}function _R(e,t){return!t||!e?e:e.bind(t)}class v0{constructor(t,n,i){this.name=t,this.init=_R(n.init,i),this.apply=_R(n.apply,i)}}const nMe=[new v0("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new v0("selection",{init(e,t){return e.selection||Bi.atStart(t.doc)},apply(e){return e.selection}}),new v0("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,i){return i.selection.$cursor?e.storedMarks:null}}),new v0("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}})];class G8{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=nMe.slice(),n&&n.forEach(i=>{if(this.pluginsByKey[i.key])throw new RangeError("Adding different instances of a keyed plugin ("+i.key+")");this.plugins.push(i),this.pluginsByKey[i.key]=i,i.spec.state&&this.fields.push(new v0(i.key,i.spec.state,i))})}}class Uh{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,n=-1){for(let i=0;ii.toJSON())),t&&typeof t=="object")for(let i in t){if(i=="doc"||i=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let o=t[i],s=o.spec.state;s&&s.toJSON&&(n[i]=s.toJSON.call(o,this[o.key]))}return n}static fromJSON(t,n,i){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let o=new G8(t.schema,t.plugins),s=new Uh(o);return o.fields.forEach(r=>{if(r.name=="doc")s.doc=up.fromJSON(t.schema,n.doc);else if(r.name=="selection")s.selection=Bi.fromJSON(s.doc,n.selection);else if(r.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(t.schema.markFromJSON));else{if(i)for(let l in i){let a=i[l],u=a.spec.state;if(a.key==r.name&&u&&u.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[r.name]=u.fromJSON.call(a,t,n[l],s);return}}s[r.name]=r.init(t,s)}}),s}}function dK(e,t,n){for(let i in e){let o=e[i];o instanceof Function?o=o.bind(t):i=="handleDOMEvents"&&(o=dK(o,t,{})),n[i]=o}return n}class b2{constructor(t){this.spec=t,this.props={},t.props&&dK(t.props,this,this.props),this.key=t.key?t.key.key:fK("plugin")}getState(t){return t[this.key]}}const Q8=Object.create(null);function fK(e){return e in Q8?e+"$"+ ++Q8[e]:(Q8[e]=0,e+"$")}class BS{constructor(t="key"){this.key=fK(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}function sv(e){return e.isText?e.text.length:e.type===ri.nodes.attachment?Nf(e.attrs).length:e.type===ri.nodes.quote?sw(e.attrs).length:Rp(e.attrs).length}function iMe(e,t){if(!t.parent.isTextblock)return ic(e,t.pos);if(t.textOffset>0)return ic(e,t.pos-t.textOffset);const n=t.nodeBefore;return n&&n.isText?ic(e,t.pos-n.nodeSize):ic(e,t.pos)}function nd(e,t){let n=Math.max(0,t),i=-1;return e.forEach((o,s)=>{if(i!==-1)return;let r=0;if(o.forEach(l=>{r+=sv(l)}),n>r){n-=r+1;return}o.forEach((l,a)=>{if(i!==-1)return;const u=s+1+a,c=sv(l);if(n<=c){l.isText?i=u+n:i=n===0?u:u+1;return}n-=c}),i===-1&&(i=s+1+o.content.size)}),i===-1?e.content.size-1:i}function ic(e,t){let n=0,i=-1;return e.forEach((o,s)=>{if(i!==-1)return;const r=s+o.nodeSize;if(t>r){o.forEach(a=>{n+=sv(a)}),n+=1;return}let l=0;o.forEach((a,u)=>{if(i!==-1)return;const c=s+1+u;if(a.isText){const d=c+a.nodeSize;if(t<=d){i=n+l+Math.max(0,t-c);return}l+=a.text.length}else{const d=c+1;if(t<=d){i=n+l+(t<=c?0:sv(a));return}l+=sv(a)}}),i===-1&&(i=n+l)}),i===-1?n:i}function oMe(e){const t=[];return e.forEach(n=>{n.forEach(i=>{!i.isText&&i.type===ri.nodes.mention&&i.attrs.kind==="skill"&&t.push({name:i.attrs.name})})}),t}function IR(e){return(t,n)=>{const i=t.selection.$head,o=e?i.start():i.end();return n&&n(t.tr.setSelection(Xn.create(t.doc,t.selection.$anchor.pos,o)).scrollIntoView()),!0}}var Nb=200,Ys=function(){};Ys.prototype.append=function(t){return t.length?(t=Ys.from(t),!this.length&&t||t.length=n?Ys.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Ys.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Ys.prototype.forEach=function(t,n,i){n===void 0&&(n=0),i===void 0&&(i=this.length),n<=i?this.forEachInner(t,n,i,0):this.forEachInvertedInner(t,n,i,0)};Ys.prototype.map=function(t,n,i){n===void 0&&(n=0),i===void 0&&(i=this.length);var o=[];return this.forEach(function(s,r){return o.push(t(s,r))},n,i),o};Ys.from=function(t){return t instanceof Ys?t:t&&t.length?new hK(t):Ys.empty};var hK=(function(e){function t(i){e.call(this),this.values=i}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(o,s){return o==0&&s==this.length?this:new t(this.values.slice(o,s))},t.prototype.getInner=function(o){return this.values[o]},t.prototype.forEachInner=function(o,s,r,l){for(var a=s;a=r;a--)if(o(this.values[a],l+a)===!1)return!1},t.prototype.leafAppend=function(o){if(this.length+o.length<=Nb)return new t(this.values.concat(o.flatten()))},t.prototype.leafPrepend=function(o){if(this.length+o.length<=Nb)return new t(o.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(t.prototype,n),t})(Ys);Ys.empty=new hK([]);var sMe=(function(e){function t(n,i){e.call(this),this.left=n,this.right=i,this.length=n.length+i.length,this.depth=Math.max(n.depth,i.depth)+1}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(i){return il&&this.right.forEachInner(i,Math.max(o-l,0),Math.min(this.length,s)-l,r+l)===!1)return!1},t.prototype.forEachInvertedInner=function(i,o,s,r){var l=this.left.length;if(o>l&&this.right.forEachInvertedInner(i,o-l,Math.max(s,l)-l,r+l)===!1||s=s?this.right.slice(i-s,o-s):this.left.slice(i,s).append(this.right.slice(0,o-s))},t.prototype.leafAppend=function(i){var o=this.right.leafAppend(i);if(o)return new t(this.left,o)},t.prototype.leafPrepend=function(i){var o=this.left.leafPrepend(i);if(o)return new t(o,this.right)},t.prototype.appendInner=function(i){return this.left.depth>=Math.max(this.right.depth,i.depth)+1?new t(this.left,new t(this.right,i)):new t(this,i)},t})(Ys);const rMe=500;class fu{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let i=this.items.length;for(;;i--)if(this.items.get(i-1).selection){--i;break}let o,s;n&&(o=this.remapping(i,this.items.length),s=o.maps.length);let r=t.tr,l,a,u=[],c=[];return this.items.forEach((d,f)=>{if(!d.step){o||(o=this.remapping(i,f+1),s=o.maps.length),s--,c.push(d);return}if(o){c.push(new qu(d.map));let h=d.step.map(o.slice(s)),m;h&&r.maybeStep(h).doc&&(m=r.mapping.maps[r.mapping.maps.length-1],u.push(new qu(m,void 0,void 0,u.length+c.length))),s--,m&&o.appendMap(m,s)}else r.maybeStep(d.step);if(d.selection)return l=o?d.selection.map(o.slice(s)):d.selection,a=new fu(this.items.slice(0,i).append(c.reverse().concat(u)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:r,selection:l}}addTransform(t,n,i,o){let s=[],r=this.eventCount,l=this.items,a=!o&&l.length?l.get(l.length-1):null;for(let c=0;caMe&&(l=lMe(l,u),r-=u),new fu(l.append(s),r)}remapping(t,n){let i=new Uv;return this.items.forEach((o,s)=>{let r=o.mirrorOffset!=null&&s-o.mirrorOffset>=t?i.maps.length-o.mirrorOffset:void 0;i.appendMap(o.map,r)},t,n),i}addMaps(t){return this.eventCount==0?this:new fu(this.items.append(t.map(n=>new qu(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let i=[],o=Math.max(0,this.items.length-n),s=t.mapping,r=t.steps.length,l=this.eventCount;this.items.forEach(f=>{f.selection&&l--},o);let a=n;this.items.forEach(f=>{let h=s.getMirror(--a);if(h==null)return;r=Math.min(r,h);let m=s.maps[h];if(f.step){let g=t.steps[h].invert(t.docs[h]),y=f.selection&&f.selection.map(s.slice(a+1,h));y&&l++,i.push(new qu(m,g,y))}else i.push(new qu(m))},o);let u=[];for(let f=n;frMe&&(d=d.compress(this.items.length-i.length)),d}emptyItemCount(){let t=0;return this.items.forEach(n=>{n.step||t++}),t}compress(t=this.items.length){let n=this.remapping(0,t),i=n.maps.length,o=[],s=0;return this.items.forEach((r,l)=>{if(l>=t)o.push(r),r.selection&&s++;else if(r.step){let a=r.step.map(n.slice(i)),u=a&&a.getMap();if(i--,u&&n.appendMap(u,i),a){let c=r.selection&&r.selection.map(n.slice(i));c&&s++;let d=new qu(u.invert(),a,c),f,h=o.length-1;(f=o.length&&o[h].merge(d))?o[h]=f:o.push(d)}}else r.map&&i--},this.items.length,0),new fu(Ys.from(o.reverse()),s)}}fu.empty=new fu(Ys.empty,0);function lMe(e,t){let n;return e.forEach((i,o)=>{if(i.selection&&t--==0)return n=o,!1}),e.slice(n)}class qu{constructor(t,n,i,o){this.map=t,this.step=n,this.selection=i,this.mirrorOffset=o}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new qu(n.getMap().invert(),n,this.selection)}}}class qd{constructor(t,n,i,o,s){this.done=t,this.undone=n,this.prevRanges=i,this.prevTime=o,this.prevComposition=s}}const aMe=20;function uMe(e,t,n,i){let o=n.getMeta(cp),s;if(o)return o.historyState;n.getMeta(mK)&&(e=new qd(e.done,e.undone,null,0,-1));let r=n.getMeta("appendedTransaction");if(n.steps.length==0)return e;if(r&&r.getMeta(cp))return r.getMeta(cp).redo?new qd(e.done.addTransform(n,void 0,i,ek(t)),e.undone,MR(n.mapping.maps),e.prevTime,e.prevComposition):new qd(e.done,e.undone.addTransform(n,void 0,i,ek(t)),null,e.prevTime,e.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(r&&r.getMeta("addToHistory")===!1)){let l=n.getMeta("composition"),a=e.prevTime==0||!r&&e.prevComposition!=l&&(e.prevTime<(n.time||0)-i.newGroupDelay||!cMe(n,e.prevRanges)),u=r?Y8(e.prevRanges,n.mapping):MR(n.mapping.maps);return new qd(e.done.addTransform(n,a?t.selection.getBookmark():void 0,i,ek(t)),fu.empty,u,n.time,l??e.prevComposition)}else return(s=n.getMeta("rebased"))?new qd(e.done.rebased(n,s),e.undone.rebased(n,s),Y8(e.prevRanges,n.mapping),e.prevTime,e.prevComposition):new qd(e.done.addMaps(n.mapping.maps),e.undone.addMaps(n.mapping.maps),Y8(e.prevRanges,n.mapping),e.prevTime,e.prevComposition)}function cMe(e,t){if(!t)return!1;if(!e.docChanged)return!0;let n=!1;return e.mapping.maps[0].forEach((i,o)=>{for(let s=0;s=t[s]&&(n=!0)}),n}function MR(e){let t=[];for(let n=e.length-1;n>=0&&t.length==0;n--)e[n].forEach((i,o,s,r)=>t.push(s,r));return t}function Y8(e,t){if(!e)return null;let n=[];for(let i=0;i{let o=cp.getState(n);if(!o||(e?o.undone:o.done).eventCount==0)return!1;if(i){let s=dMe(o,n,e);s&&i(t?s.scrollIntoView():s)}return!0}}const vK=gK(!1,!0),k6=gK(!0,!0);function hMe(e,t,n){const i=nd(e.doc,n.start),o=nd(e.doc,n.end),s=qv(e.doc),r=n.start>0?s.charAt(n.start-1):"",l=s.charAt(n.end),a=[];(r==="!"||r==="\\")&&a.push(ri.text(" ")),a.push(QV(t)),(l===""||!/\s/.test(l))&&a.push(ri.text(" "));const u=e.tr.replaceWith(i,o,a);return u.setSelection(Xn.create(u.doc,i+a.reduce((c,d)=>c+d.nodeSize,0))),u.scrollIntoView()}function pMe(e,t,n){const i=nd(e.doc,n.start),o=nd(e.doc,n.end),s=e.tr.insertText(t,i,o);return s.setSelection(Xn.create(s.doc,i+t.length)),pK(s.scrollIntoView())}function mMe(e,t,n){const i=n?n.start:ic(e.doc,e.selection.from),o=n?n.end:ic(e.doc,e.selection.to),s=nd(e.doc,i),r=nd(e.doc,o),l=qv(e.doc),a=i>0?l.charAt(i-1):"",u=l.charAt(o),c=[];(a==="!"||a==="\\")&&c.push(ri.text(" ")),c.push(YV(t)),(u===""||!/\s/.test(u))&&c.push(ri.text(" "));const d=e.tr.replaceWith(s,r,c);return d.setSelection(Xn.create(d.doc,s+c.reduce((f,h)=>f+h.nodeSize,0))),d.scrollIntoView()}function gMe(e,t,n){const i=e.selection.to,o=qv(e.doc),s=ic(e.doc,i),r=s>0?o.charAt(s-1):"",l=o.charAt(s),a=[];r!==""&&!/\s/.test(r)&&a.push(ri.text(" ")),a.push(JV(n!==void 0&&n.length>0?{...t,comment:n}:t)),(l===""||!/\s/.test(l))&&a.push(ri.text(" "));const u=e.tr.replaceWith(i,i,a);return u.setSelection(Xn.create(u.doc,i+a.reduce((c,d)=>c+d.nodeSize,0))),u.scrollIntoView()}function t9(e,t){return mn.maxOpen(Wv(e.replace(/\r\n?/g,` +`),t).content)}function ER(e){const t=typeof e.source=="string"&&e.source.length>0?`from: ${LS(e.source)} +`:"",n=typeof e.comment=="string"&&e.comment.length>0?` + +${e.comment}`:"";return`${t}${MV(e.text)}${n}`}function yK(e){const t=i=>i.isText?i.text??"":i.type===ri.nodes.mention?Rp(i.attrs):i.type===ri.nodes.attachment?i.attrs.name:i.type===ri.nodes.quote?ER(i.attrs):i.textBetween(0,i.content.size,""),n=[];return e.content.forEach(i=>{if(i.type===ri.nodes.mention||i.type===ri.nodes.attachment||i.type===ri.nodes.quote)n.push(t(i));else{let o="",s=!1;i.forEach(r=>{if(r.type===ri.nodes.quote){const a=ER(r.attrs);o=o.length>0?`${o.replace(/ +$/,"")} + +${a}`:a,s=!0;return}let l=t(r);s&&(l=l.replace(/^ /,""),o+=` + +`,s=!1),o+=l}),n.push(o)}}),n.join(` +`)}const b6=` + + + + +`,kK=` + + + + +`,bK='',wK=` + + + +`,CK=` + + +`,AK='',xK=` + + +`,SK=` + + +`,_K=` + + +`,vMe='',yMe='',kMe='',bMe='',wMe='',CMe={sm:14,md:16,lg:20},AMe={file:b6,folder:kK,skill:bK,copy:wK,check:CK,"external-link":AK,target:xK,"file-edit":SK,close:_K,attachment:vMe,image:yMe,video:kMe,fullscreen:bMe,quote:wMe};function tl(e,t="md"){const n=CMe[t];return AMe[e].replace(/]*>/,i=>i.replace(/\s(?:width|height)="[^"]*"/g,"")).replace(/^