@dmrlzz/davecode 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ChatApp-CJBICQGA.js → ChatApp-YMHKIAAH.js} +6 -6
- package/dist/{account-QWDPJWAA.js → account-5QFYCVYM.js} +3 -3
- package/dist/{accounts-IQMR72FC.js → accounts-756BMMAL.js} +5 -5
- package/dist/{budget-XANOUVWO.js → budget-PGSNCVVK.js} +4 -4
- package/dist/{chat-KDDRNC5V.js → chat-D3T4YG5D.js} +8 -8
- package/dist/{chunk-AZKACMME.js → chunk-6SHOBL2X.js} +2 -2
- package/dist/{chunk-WQ7MEWDF.js → chunk-6WUVR3R2.js} +10 -4
- package/dist/chunk-6WUVR3R2.js.map +1 -0
- package/dist/{chunk-HSBJDV3O.js → chunk-HENE4DA6.js} +240 -22
- package/dist/chunk-HENE4DA6.js.map +1 -0
- package/dist/{chunk-W7GPBEBZ.js → chunk-IOATP7KH.js} +2 -2
- package/dist/{chunk-FYPMA55O.js → chunk-JFWMLYV7.js} +111 -19
- package/dist/chunk-JFWMLYV7.js.map +1 -0
- package/dist/{chunk-44AFJL2X.js → chunk-JSRPO2AR.js} +6 -5
- package/dist/chunk-JSRPO2AR.js.map +1 -0
- package/dist/{chunk-JLATEHS7.js → chunk-K5AA65RS.js} +2 -2
- package/dist/{chunk-PGAJIGUF.js → chunk-ZNUNYYN6.js} +3 -3
- package/dist/{config-YTUPIYZT.js → config-TKGGYEN7.js} +3 -3
- package/dist/dashboard/assets/Accounts-DciFUg4y.js +1 -0
- package/dist/dashboard/assets/{Badge-Z4RBdO9j.js → Badge-DUGKlx3Z.js} +1 -1
- package/dist/dashboard/assets/{Callout-w8BTYh4k.js → Callout-WgXHDPg0.js} +1 -1
- package/dist/dashboard/assets/{Goals-Bw02to72.js → Goals-C6HL1PNE.js} +1 -1
- package/dist/dashboard/assets/{Library-DK7mlpRb.js → Library-DwpBYTbK.js} +1 -1
- package/dist/dashboard/assets/Markdown-CGgIydUh.js +71 -0
- package/dist/dashboard/assets/{Panes-_KTf8pbZ.js → Panes-DxFSwhb7.js} +1 -1
- package/dist/dashboard/assets/{RoutesPage-QV0oPRW9.js → RoutesPage-Cyo0MNd7.js} +1 -1
- package/dist/dashboard/assets/{Runner-CkHBLQl0.js → Runner-CIL7RxpN.js} +1 -1
- package/dist/dashboard/assets/{Settings-BLz2gTBR.js → Settings-B_PEB585.js} +1 -1
- package/dist/dashboard/assets/{Tasks-BiUQSTpt.js → Tasks-DEfPSaE6.js} +1 -1
- package/dist/dashboard/assets/{Traffic-BVfBuC70.js → Traffic-Dcz-WhsP.js} +1 -1
- package/dist/dashboard/assets/{Workspace-CJTgiiU5.js → Workspace-9UCw9q7C.js} +1 -1
- package/dist/dashboard/assets/{index-BDBa5cb0.js → index-CpztPbom.js} +3 -3
- package/dist/dashboard/assets/{task-errors-Daqwi0ue.js → task-errors-r-WYZ_S3.js} +1 -1
- package/dist/dashboard/index.html +2 -2
- package/dist/{dist-37VQSHHA.js → dist-F3NRJ5FK.js} +18 -2
- package/dist/{doctor-PYUQRRCB.js → doctor-V4XXVVGK.js} +3 -3
- package/dist/{goal-SXZUDUCL.js → goal-RUHYPVPA.js} +3 -3
- package/dist/index.js +31 -31
- package/dist/{init-Z2AFQEEP.js → init-54FKQZ2Z.js} +3 -3
- package/dist/{run-AOS7L3RT.js → run-4R25J2VN.js} +3 -3
- package/dist/runtime.js +2 -2
- package/dist/{start-CEPXKZUE.js → start-GRHW3TGE.js} +3 -3
- package/dist/{status-WNJ3GGKU.js → status-QR2HNPBK.js} +4 -4
- package/dist/{tasks-TFUTUMWB.js → tasks-BHWDV4JS.js} +4 -4
- package/package.json +6 -6
- package/dist/chunk-44AFJL2X.js.map +0 -1
- package/dist/chunk-FYPMA55O.js.map +0 -1
- package/dist/chunk-HSBJDV3O.js.map +0 -1
- package/dist/chunk-WQ7MEWDF.js.map +0 -1
- package/dist/dashboard/assets/Accounts-cq8RLMoI.js +0 -1
- package/dist/dashboard/assets/Markdown-DCZ4Awcc.js +0 -69
- /package/dist/{ChatApp-CJBICQGA.js.map → ChatApp-YMHKIAAH.js.map} +0 -0
- /package/dist/{account-QWDPJWAA.js.map → account-5QFYCVYM.js.map} +0 -0
- /package/dist/{accounts-IQMR72FC.js.map → accounts-756BMMAL.js.map} +0 -0
- /package/dist/{budget-XANOUVWO.js.map → budget-PGSNCVVK.js.map} +0 -0
- /package/dist/{chat-KDDRNC5V.js.map → chat-D3T4YG5D.js.map} +0 -0
- /package/dist/{chunk-AZKACMME.js.map → chunk-6SHOBL2X.js.map} +0 -0
- /package/dist/{chunk-W7GPBEBZ.js.map → chunk-IOATP7KH.js.map} +0 -0
- /package/dist/{chunk-JLATEHS7.js.map → chunk-K5AA65RS.js.map} +0 -0
- /package/dist/{chunk-PGAJIGUF.js.map → chunk-ZNUNYYN6.js.map} +0 -0
- /package/dist/{config-YTUPIYZT.js.map → config-TKGGYEN7.js.map} +0 -0
- /package/dist/{dist-37VQSHHA.js.map → dist-F3NRJ5FK.js.map} +0 -0
- /package/dist/{doctor-PYUQRRCB.js.map → doctor-V4XXVVGK.js.map} +0 -0
- /package/dist/{goal-SXZUDUCL.js.map → goal-RUHYPVPA.js.map} +0 -0
- /package/dist/{init-Z2AFQEEP.js.map → init-54FKQZ2Z.js.map} +0 -0
- /package/dist/{run-AOS7L3RT.js.map → run-4R25J2VN.js.map} +0 -0
- /package/dist/{start-CEPXKZUE.js.map → start-GRHW3TGE.js.map} +0 -0
- /package/dist/{status-WNJ3GGKU.js.map → status-QR2HNPBK.js.map} +0 -0
- /package/dist/{tasks-TFUTUMWB.js.map → tasks-BHWDV4JS.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/accounts.ts","../src/lib/account-flow.ts"],"sourcesContent":["import { createInterface } from 'node:readline';\nimport {\n type Account,\n type AccountConnection,\n CLI_LOGINS,\n cliBinaryFor,\n globalPaths,\n loginEnv,\n type ProviderKind,\n SandboxManager,\n type SubscriptionInfo,\n} from '@davecode/core';\nimport { type CliContext, printJson } from '../context';\nimport { CliError, EXIT } from '../errors';\nimport {\n type AddFlags,\n accountFromFlags,\n accountInteractively,\n accountPolicy,\n describeCreate,\n providerInfo,\n} from '../lib/account-flow';\nimport { type AccountsBackend, openAccounts, resolveAccount } from '../lib/accounts-backend';\nimport { type SpawnFn, spawnInteractive, which } from '../lib/proc';\nimport { PromptCancelledError, type Prompter } from '../lib/prompter';\nimport { detectProjectRoot } from '../runtime';\nimport { type Column, table, truncate } from '../ui/format';\nimport type { Theme } from '../ui/theme';\n\nexport interface AccountsDeps {\n /** Override the backend (tests). */\n backend?: AccountsBackend;\n prompter?: Prompter;\n readStdin?: () => Promise<string>;\n spawn?: SpawnFn;\n /** Used by `accounts login --hold` (tests). */\n waitForEnter?: () => Promise<void>;\n}\n\nexport interface BackendFlags {\n /** Write to state.db even if a gateway is running. */\n local?: boolean;\n}\n\nasync function backendFor(\n ctx: CliContext,\n flags: BackendFlags,\n deps: AccountsDeps,\n): Promise<AccountsBackend> {\n if (deps.backend) return deps.backend;\n const projectRoot = await detectProjectRoot(ctx.cwd, ctx.home);\n return openAccounts({\n home: ctx.home,\n env: ctx.env,\n ...(projectRoot ? { projectRoot } : {}),\n ...(flags.local ? { local: true } : {}),\n });\n}\n\nasync function withBackend<T>(\n ctx: CliContext,\n flags: BackendFlags,\n deps: AccountsDeps,\n fn: (backend: AccountsBackend) => Promise<T>,\n): Promise<T> {\n const backend = await backendFor(ctx, flags, deps);\n try {\n return await fn(backend);\n } finally {\n if (!deps.backend) backend.close();\n }\n}\n\nasync function prompterFor(ctx: CliContext, deps: AccountsDeps): Promise<Prompter> {\n if (deps.prompter) return deps.prompter;\n const { createInkPrompter } = await import('../tui/prompts');\n return createInkPrompter({ stdout: ctx.io.stdout, stdin: ctx.io.stdin, theme: ctx.theme });\n}\n\nfunction readAllStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk: string) => {\n data += chunk;\n });\n process.stdin.on('end', () => resolve(data));\n process.stdin.on('error', reject);\n });\n}\n\n// ---------------------------------------------------------------------------\n// list\n// ---------------------------------------------------------------------------\n\nfunction statusText(theme: Theme, account: Account): string {\n switch (account.status) {\n case 'active':\n return theme.ok('active');\n case 'cooldown':\n return theme.warn('cooldown');\n case 'error':\n return theme.error('error');\n default:\n return theme.dim('disabled');\n }\n}\n\nfunction detail(account: Account): string {\n const config = account.config;\n const parts: string[] = [];\n if (typeof config.baseUrl === 'string') parts.push(config.baseUrl);\n if (Array.isArray(config.models) && config.models.length > 0) {\n parts.push(config.models.slice(0, 3).join(', ') + (config.models.length > 3 ? ', …' : ''));\n }\n if (typeof config.binaryPath === 'string') parts.push(config.binaryPath);\n return parts.join(' · ');\n}\n\nexport function renderAccountList(theme: Theme, accounts: Account[], columns: number): string[] {\n const cols: Column[] = [\n { header: 'ID' },\n { header: 'LABEL' },\n { header: 'PROVIDER' },\n { header: 'STATUS' },\n { header: 'PRI', align: 'right', drop: 2 },\n { header: 'WEIGHT', align: 'right', drop: 3 },\n { header: 'DETAILS', drop: 4 },\n ];\n const rows = accounts.map((a) => [\n theme.accent(a.id),\n truncate(a.label, 28),\n a.provider,\n statusText(theme, a),\n String(a.priority),\n String(a.weight),\n theme.dim(truncate(detail(a), 40)),\n ]);\n return table(theme, cols, rows, columns);\n}\n\nexport async function accountsList(\n ctx: CliContext,\n flags: BackendFlags = {},\n deps: AccountsDeps = {},\n): Promise<number> {\n return withBackend(ctx, flags, deps, async (backend) => {\n const accounts = await backend.list();\n if (ctx.json) {\n printJson(ctx, { source: backend.kind, accounts });\n return EXIT.ok;\n }\n if (accounts.length === 0) {\n ctx.out(ctx.theme.dim('No accounts yet.'));\n ctx.out(`Add one with ${ctx.theme.accent('davecode accounts add')}.`);\n return EXIT.ok;\n }\n for (const line of renderAccountList(ctx.theme, accounts, ctx.columns)) ctx.out(line);\n ctx.out();\n ctx.out(\n ctx.theme.dim(backend.kind === 'gateway' ? 'source: running gateway' : 'source: local state'),\n );\n return EXIT.ok;\n });\n}\n\n// ---------------------------------------------------------------------------\n// add\n// ---------------------------------------------------------------------------\n\nexport interface AddCommandFlags extends AddFlags, BackendFlags {\n /** Never prompt; everything comes from flags. */\n yes?: boolean;\n /** commander's `--no-login`. */\n login?: boolean;\n}\n\nexport async function accountsAdd(\n ctx: CliContext,\n flags: AddCommandFlags,\n deps: AccountsDeps = {},\n): Promise<number> {\n // A custom binary can only be set by the machine's owner, never through the gateway's HTTP\n // API, so it is written straight to the local database.\n const backendFlags = flags.binaryPath ? { ...flags, local: true } : flags;\n return withBackend(ctx, backendFlags, deps, async (backend) => {\n const existing = await backend.list();\n const interactive = ctx.interactive && !flags.yes && !flags.secretStdin;\n const { theme, errTheme } = ctx;\n\n let create: Awaited<ReturnType<typeof accountFromFlags>> | undefined;\n if (interactive) {\n try {\n create = await accountInteractively(flags, {\n prompter: await prompterFor(ctx, deps),\n config: backend.config,\n existing,\n say: (line) => ctx.out(line),\n warn: theme.warn,\n });\n } catch (err) {\n if (err instanceof PromptCancelledError) {\n ctx.err(errTheme.dim('Cancelled.'));\n return EXIT.failure;\n }\n throw err;\n }\n if (!create) {\n ctx.err(errTheme.dim('Nothing added.'));\n return EXIT.failure;\n }\n } else {\n create = await accountFromFlags(flags, {\n env: ctx.env,\n readStdin: deps.readStdin ?? readAllStdin,\n });\n const policy = accountPolicy(create.provider, backend.config, existing);\n if (policy.blocked) {\n throw new CliError(policy.blocked.message, { hint: policy.blocked.hint });\n }\n for (const warning of policy.warnings) {\n ctx.err(errTheme.warn(`${errTheme.glyph.warn} ${warning}`));\n }\n if (flags.secret !== undefined) {\n ctx.err(\n errTheme.dim(\n 'Note: --secret is visible in shell history and process lists; prefer --secret-env or --secret-stdin.',\n ),\n );\n }\n }\n\n const account = await backend.create(create);\n if (ctx.json) {\n printJson(ctx, { account });\n return EXIT.ok;\n }\n ctx.out(\n `${theme.ok(theme.glyph.ok)} Added ${theme.bold(account.label)} ${theme.dim(`(${account.id}, ${account.provider})`)}`,\n );\n if (!interactive) {\n for (const line of describeCreate(create)) ctx.out(theme.dim(` ${line}`));\n }\n\n const info = providerInfo(account.provider);\n if (info?.auth === 'cli-login') {\n const loginNow =\n interactive &&\n flags.login !== false &&\n (await (\n await prompterFor(ctx, deps)\n ).confirm(`Log in to ${info.binary} for this account now?`, true));\n if (loginNow) return accountsLogin(ctx, account.id, [], flags, { ...deps, backend });\n ctx.out(\n theme.dim(`Next: log in with ${theme.accent(`davecode accounts login ${account.id}`)}`),\n );\n }\n return EXIT.ok;\n });\n}\n\n// ---------------------------------------------------------------------------\n// remove / enable / disable\n// ---------------------------------------------------------------------------\n\nexport async function accountsRemove(\n ctx: CliContext,\n ref: string,\n flags: BackendFlags & { yes?: boolean },\n deps: AccountsDeps = {},\n): Promise<number> {\n return withBackend(ctx, flags, deps, async (backend) => {\n const account = await resolveAccount(backend, ref);\n if (!flags.yes) {\n if (!ctx.interactive) {\n throw new CliError(`Refusing to remove ${account.id} without confirmation`, {\n hint: 'Pass --yes to remove it non-interactively.',\n });\n }\n const ok = await (await prompterFor(ctx, deps))\n .confirm(`Remove ${account.label} (${account.id}) and its sandbox?`, false)\n .catch((err: unknown) => {\n if (err instanceof PromptCancelledError) return false;\n throw err;\n });\n if (!ok) {\n ctx.err(ctx.errTheme.dim('Nothing removed.'));\n return EXIT.failure;\n }\n }\n await backend.remove(account.id);\n if (ctx.json) printJson(ctx, { removed: account.id });\n else ctx.out(`${ctx.theme.ok(ctx.theme.glyph.ok)} Removed ${account.label} (${account.id})`);\n return EXIT.ok;\n });\n}\n\nexport async function accountsSetEnabled(\n ctx: CliContext,\n ref: string,\n enabled: boolean,\n flags: BackendFlags = {},\n deps: AccountsDeps = {},\n): Promise<number> {\n return withBackend(ctx, flags, deps, async (backend) => {\n const account = await resolveAccount(backend, ref);\n const updated = await backend.update(account.id, { enabled });\n if (ctx.json) printJson(ctx, { account: updated });\n else {\n ctx.out(\n `${ctx.theme.ok(ctx.theme.glyph.ok)} ${updated.label} is now ${enabled ? 'enabled' : 'disabled'} ${ctx.theme.dim(`(${updated.status})`)}`,\n );\n }\n return EXIT.ok;\n });\n}\n\n// ---------------------------------------------------------------------------\n// plan (subscription details)\n// ---------------------------------------------------------------------------\n\nexport interface PlanFlags extends BackendFlags {\n plan?: string;\n paid?: string;\n renews?: string;\n price?: string;\n currency?: string;\n period?: string;\n notes?: string;\n clear?: boolean;\n}\n\nexport function describeSubscription(subscription: SubscriptionInfo | undefined): string {\n if (!subscription) return 'no plan recorded';\n const parts: string[] = [];\n if (subscription.plan) parts.push(subscription.plan);\n if (subscription.price) {\n const { amount, currency, period } = subscription.price;\n parts.push(`${amount} ${currency}/${period}`);\n }\n if (subscription.paidAt) parts.push(`paid ${subscription.paidAt}`);\n if (subscription.renewsAt) parts.push(`renews ${subscription.renewsAt}`);\n if (subscription.notes) parts.push(subscription.notes);\n return parts.length > 0 ? parts.join(' · ') : 'no plan recorded';\n}\n\n/** Merge plan flags into the existing subscription details (validated by the backend). */\nexport function subscriptionFromFlags(\n existing: SubscriptionInfo | undefined,\n flags: PlanFlags,\n): SubscriptionInfo {\n const next: SubscriptionInfo = { ...existing };\n if (flags.plan !== undefined) next.plan = flags.plan;\n if (flags.paid !== undefined) next.paidAt = flags.paid;\n if (flags.renews !== undefined) next.renewsAt = flags.renews;\n if (flags.notes !== undefined) next.notes = flags.notes;\n if (flags.price !== undefined || flags.currency !== undefined || flags.period !== undefined) {\n const amount = flags.price !== undefined ? Number(flags.price) : existing?.price?.amount;\n if (amount === undefined || !Number.isFinite(amount)) {\n throw new CliError('--price needs a number, e.g. --price 20', {\n hint: 'Set the amount with --price, and optionally --currency USD --period month.',\n });\n }\n const period = flags.period ?? existing?.price?.period ?? 'month';\n if (period !== 'month' && period !== 'year') {\n throw new CliError('--period must be \"month\" or \"year\"');\n }\n next.price = { amount, currency: flags.currency ?? existing?.price?.currency ?? 'USD', period };\n }\n return next;\n}\n\nexport async function accountsPlan(\n ctx: CliContext,\n ref: string,\n flags: PlanFlags = {},\n deps: AccountsDeps = {},\n): Promise<number> {\n return withBackend(ctx, flags, deps, async (backend) => {\n const account = await resolveAccount(backend, ref);\n const { theme } = ctx;\n const changes = ['plan', 'paid', 'renews', 'price', 'currency', 'period', 'notes'] as const;\n const editing = flags.clear || changes.some((key) => flags[key] !== undefined);\n if (!editing) {\n if (ctx.json)\n printJson(ctx, { account: account.id, subscription: account.subscription ?? null });\n else ctx.out(`${theme.bold(account.label)}: ${describeSubscription(account.subscription)}`);\n return EXIT.ok;\n }\n const subscription = flags.clear ? null : subscriptionFromFlags(account.subscription, flags);\n const updated = await backend.update(account.id, { subscription });\n if (ctx.json) printJson(ctx, { account: updated });\n else {\n ctx.out(\n `${theme.ok(theme.glyph.ok)} ${updated.label}: ${describeSubscription(updated.subscription)}`,\n );\n }\n return EXIT.ok;\n });\n}\n\n// ---------------------------------------------------------------------------\n// login\n// ---------------------------------------------------------------------------\n\n/** Arguments that start each CLI's own official login flow. */\nexport function loginArgs(provider: ProviderKind): string[] {\n return CLI_LOGINS[provider]?.loginArgs ?? [];\n}\n\nexport interface LoginFlags extends BackendFlags {\n /** Wait for Enter before exiting (used when the dashboard opened this in a new window). */\n hold?: boolean;\n}\n\nfunction waitForEnter(): Promise<void> {\n return new Promise((resolve) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question('Press Enter to close this window.', () => {\n rl.close();\n resolve();\n });\n rl.once('close', resolve);\n });\n}\n\nexport function describeConnection(theme: Theme, connection: AccountConnection): string {\n const label: Record<AccountConnection['status'], string> = {\n connected: theme.ok(`${theme.glyph.ok} connected`),\n not_connected: theme.warn(`${theme.glyph.warn} not connected`),\n unknown: theme.dim('? unknown'),\n };\n return `${label[connection.status]}${connection.detail ? theme.dim(` — ${connection.detail}`) : ''}`;\n}\n\nexport async function accountsLogin(\n ctx: CliContext,\n ref: string,\n extraArgs: string[] = [],\n flags: LoginFlags = {},\n deps: AccountsDeps = {},\n): Promise<number> {\n if (!flags.hold) return runLogin(ctx, ref, extraArgs, flags, deps);\n try {\n return await runLogin(ctx, ref, extraArgs, flags, deps);\n } catch (err) {\n ctx.err(ctx.errTheme.warn(err instanceof Error ? err.message : String(err)));\n return EXIT.failure;\n } finally {\n await (deps.waitForEnter ?? waitForEnter)();\n }\n}\n\nfunction runLogin(\n ctx: CliContext,\n ref: string,\n extraArgs: string[],\n flags: LoginFlags,\n deps: AccountsDeps,\n): Promise<number> {\n return withBackend(ctx, flags, deps, async (backend) => {\n const account = await resolveAccount(backend, ref);\n const spec = CLI_LOGINS[account.provider];\n if (!spec) {\n const info = providerInfo(account.provider);\n throw new CliError(`${account.provider} accounts do not use a CLI login`, {\n hint:\n info?.auth === 'api-key' || info?.auth === 'optional-key'\n ? `Rotate the key with: davecode accounts add … or PATCH /api/accounts/${account.id}`\n : undefined,\n });\n }\n const binary = cliBinaryFor(account) ?? spec.binary;\n const resolved = which(binary, ctx.env);\n if (!resolved) {\n throw new CliError(`Cannot find \\`${binary}\\` on PATH`, { hint: spec.installHint });\n }\n\n const sandboxes = new SandboxManager(globalPaths(ctx.home).sandboxes);\n const dir = sandboxes.prepare(account);\n const isolation = loginEnv(account, sandboxes);\n const env = { ...ctx.env, ...isolation };\n const [variable] = Object.keys(isolation);\n const { theme } = ctx;\n\n ctx.out(\n `${theme.accent(theme.glyph.arrow)} Logging in ${theme.bold(account.label)} ${theme.dim(`(${account.id})`)}`,\n );\n ctx.out(theme.dim(` ${variable}=${dir}`));\n ctx.out(theme.dim(` ${spec.instructions}`));\n ctx.out(theme.dim(' DaveCode never sees your password; the vendor CLI keeps the login.'));\n ctx.out();\n\n const args = extraArgs.length > 0 ? extraArgs : spec.loginArgs;\n const exit = await spawnInteractive(resolved, args, {\n env,\n cwd: dir,\n ...(deps.spawn ? { spawn: deps.spawn } : {}),\n });\n ctx.out();\n if (exit !== 0) {\n ctx.err(ctx.errTheme.warn(`${binary} exited with code ${exit}`));\n return exit;\n }\n if (account.status === 'error' && account.enabled) {\n // A fresh login fixes auth errors; reset the account so the router tries it again.\n await backend.update(account.id, { enabled: true });\n }\n const connection = await backend.connection(account.id).catch(() => undefined);\n if (connection) ctx.out(` ${describeConnection(theme, connection)}`);\n ctx.out(\n `${theme.ok(theme.glyph.ok)} ${account.label} is ready. Its login lives only in ${dir}`,\n );\n return EXIT.ok;\n });\n}\n\nexport interface ConnectFlags extends BackendFlags {\n /** Only report the connection state. */\n check?: boolean;\n}\n\n/**\n * \"Connect subscription\" from the terminal: show the account's connection state and, for\n * CLI-login accounts that are not connected, run the vendor's official login.\n */\nexport async function accountsConnect(\n ctx: CliContext,\n ref: string,\n flags: ConnectFlags = {},\n deps: AccountsDeps = {},\n): Promise<number> {\n const { account, connection } = await withBackend(ctx, flags, deps, async (backend) => {\n const account = await resolveAccount(backend, ref);\n return { account, connection: await backend.connection(account.id) };\n });\n if (ctx.json) {\n printJson(ctx, { connection });\n return connection.status === 'connected' || flags.check ? EXIT.ok : EXIT.failure;\n }\n const { theme } = ctx;\n ctx.out(`${theme.bold(account.label)} ${theme.dim(`(${account.id}, ${account.provider})`)}`);\n ctx.out(` ${describeConnection(theme, connection)}`);\n if (flags.check || connection.status === 'connected') return EXIT.ok;\n if (connection.method === 'api-key') {\n ctx.out(\n theme.dim(\n ` Store a key in the dashboard (Accounts → ${account.label}) or re-add the account with --secret-env.`,\n ),\n );\n return EXIT.failure;\n }\n if (connection.method !== 'cli-login') return EXIT.failure;\n ctx.out();\n return accountsLogin(ctx, account.id, [], flags, deps);\n}\n","import {\n type Account,\n type DaveConfig,\n EXPERIMENTAL_PROVIDER_KINDS,\n type ProviderKind,\n type QuotaLimits,\n SUBSCRIPTION_PROVIDER_KINDS,\n} from '@davecode/core';\nimport { CliError } from '../errors';\nimport type { AccountCreate } from './accounts-backend';\nimport type { Prompter } from './prompter';\n\n// ---------------------------------------------------------------------------\n// Provider catalogue\n// ---------------------------------------------------------------------------\n\nexport type AuthKind = 'api-key' | 'optional-key' | 'cli-login' | 'browser';\n\nexport interface ProviderInfo {\n kind: ProviderKind;\n name: string;\n auth: AuthKind;\n defaultLabel: string;\n /** Default CLI binary for `cli-login` providers. */\n binary?: string;\n}\n\nexport const PROVIDERS: readonly ProviderInfo[] = [\n { kind: 'anthropic', name: 'Anthropic API', auth: 'api-key', defaultLabel: 'Anthropic' },\n { kind: 'openai', name: 'OpenAI API', auth: 'api-key', defaultLabel: 'OpenAI' },\n { kind: 'gemini', name: 'Google Gemini API', auth: 'api-key', defaultLabel: 'Gemini' },\n {\n kind: 'openai-compatible',\n name: 'OpenRouter or another OpenAI-compatible provider',\n auth: 'optional-key',\n defaultLabel: 'OpenRouter',\n },\n {\n kind: 'claude-cli',\n name: 'Claude Code CLI (your Claude login)',\n auth: 'cli-login',\n defaultLabel: 'Claude Code',\n binary: 'claude',\n },\n {\n kind: 'codex-cli',\n name: 'Codex CLI (your ChatGPT/OpenAI login)',\n auth: 'cli-login',\n defaultLabel: 'Codex',\n binary: 'codex',\n },\n {\n kind: 'antigravity-cli',\n name: 'Antigravity CLI (your Google sign-in in agy)',\n auth: 'cli-login',\n defaultLabel: 'Antigravity',\n binary: 'agy',\n },\n {\n kind: 'gemini-cli',\n name: 'Gemini CLI (your Google login)',\n auth: 'cli-login',\n defaultLabel: 'Gemini CLI',\n binary: 'gemini',\n },\n {\n kind: 'gemini-web',\n name: 'Gemini web session (experimental)',\n auth: 'browser',\n defaultLabel: 'Gemini web',\n },\n];\n\nexport function providerInfo(kind: string): ProviderInfo | undefined {\n return PROVIDERS.find((p) => p.kind === kind);\n}\n\nexport const DEFAULT_COMPATIBLE_URL = 'https://openrouter.ai/api/v1';\n\n// ---------------------------------------------------------------------------\n// Terms-of-Service policy\n// ---------------------------------------------------------------------------\n\nexport const GEMINI_WEB_TOS =\n 'gemini-web automates the consumer Gemini web app through a browser profile. This likely ' +\n 'violates Google’s Terms of Service and your account can be rate-limited or suspended.';\n\nexport const ROTATION_TOS =\n 'Rotating several subscription logins of the same provider to get around per-account limits ' +\n 'may violate the provider’s consumer terms; accounts can be rate-limited or suspended.';\n\nexport interface Policy {\n /** The account cannot be added with the current flags. */\n blocked?: { message: string; hint: string };\n /** Shown (and, interactively, confirmed) before adding. */\n warnings: string[];\n}\n\n/** Experimental-flag rules for adding an account of `provider`. */\nexport function accountPolicy(\n provider: ProviderKind,\n config: Pick<DaveConfig, 'experimental'>,\n existing: Pick<Account, 'provider'>[],\n): Policy {\n const warnings: string[] = [];\n if (EXPERIMENTAL_PROVIDER_KINDS.includes(provider)) {\n if (!config.experimental.geminiWeb) {\n return {\n warnings,\n blocked: {\n message: `${provider} is experimental and disabled. ${GEMINI_WEB_TOS}`,\n hint: 'If you accept the risk, set \"experimental\": { \"geminiWeb\": true } in ~/.davecode/config.json (or DAVECODE_EXPERIMENTAL_GEMINI_WEB=1).',\n },\n };\n }\n warnings.push(GEMINI_WEB_TOS);\n }\n const sameProvider = existing.filter((a) => a.provider === provider).length;\n if (SUBSCRIPTION_PROVIDER_KINDS.includes(provider) && sameProvider > 0) {\n if (!config.experimental.multiAccountRotation) {\n return {\n warnings,\n blocked: {\n message: `You already have a ${provider} account. ${ROTATION_TOS}`,\n hint: 'If you accept the risk, set \"experimental\": { \"multiAccountRotation\": true } in ~/.davecode/config.json (or DAVECODE_EXPERIMENTAL_MULTI_ACCOUNT_ROTATION=1).',\n },\n };\n }\n warnings.push(ROTATION_TOS);\n }\n return { warnings };\n}\n\n// ---------------------------------------------------------------------------\n// Flags → AccountCreate\n// ---------------------------------------------------------------------------\n\nexport interface AddFlags {\n provider?: string;\n label?: string;\n priority?: number;\n weight?: number;\n /** Discouraged: visible in shell history and process listings. */\n secret?: string;\n /** Read the secret from this environment variable. */\n secretEnv?: string;\n /** Read the secret from stdin. */\n secretStdin?: boolean;\n baseUrl?: string;\n model?: string[];\n defaultModel?: string;\n binaryPath?: string;\n /** `key=value` quota limits, e.g. `tokens5h=500000`. */\n limit?: string[];\n /** commander's `--disabled`. */\n disabled?: boolean;\n}\n\nconst LIMIT_KEYS = [\n 'tpm',\n 'rpm',\n 'tokens5h',\n 'requests5h',\n 'tokensDaily',\n 'requestsDaily',\n] as const;\n\nexport function parseLimits(pairs: string[] = []): QuotaLimits {\n const limits: QuotaLimits = {};\n for (const pair of pairs) {\n const [rawKey, rawValue] = pair.split('=', 2);\n const key = LIMIT_KEYS.find((k) => k.toLowerCase() === rawKey?.trim().toLowerCase());\n const value = Number(rawValue);\n if (!key) {\n throw new CliError(`Unknown limit ${JSON.stringify(rawKey)}`, {\n hint: `Use one of: ${LIMIT_KEYS.join(', ')} (e.g. --limit tokens5h=500000)`,\n });\n }\n if (!Number.isInteger(value) || value <= 0) {\n throw new CliError(\n `Limit ${key} must be a positive integer, got ${JSON.stringify(rawValue)}`,\n );\n }\n limits[key] = value;\n }\n return limits;\n}\n\nexport function validateUrl(value: string): string | undefined {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:'\n ? undefined\n : 'must be an http(s) URL';\n } catch {\n return 'must be a valid URL, e.g. http://localhost:11434/v1';\n }\n}\n\nfunction requireProvider(value: string | undefined): ProviderInfo {\n if (!value) {\n throw new CliError('Missing --provider', {\n hint: `One of: ${PROVIDERS.map((p) => p.kind).join(', ')}`,\n });\n }\n const info = providerInfo(value);\n if (!info) {\n throw new CliError(`Unknown provider ${JSON.stringify(value)}`, {\n hint: `One of: ${PROVIDERS.map((p) => p.kind).join(', ')}`,\n });\n }\n return info;\n}\n\nexport interface SecretSources {\n env: NodeJS.ProcessEnv;\n readStdin: () => Promise<string>;\n}\n\nasync function secretFromFlags(\n flags: AddFlags,\n sources: SecretSources,\n): Promise<string | undefined> {\n const chosen = [flags.secret !== undefined, !!flags.secretEnv, !!flags.secretStdin].filter(\n Boolean,\n );\n if (chosen.length > 1) {\n throw new CliError('Use only one of --secret, --secret-env and --secret-stdin');\n }\n if (flags.secretStdin) {\n const value = (await sources.readStdin()).trim();\n if (!value) throw new CliError('No secret received on stdin');\n return value;\n }\n if (flags.secretEnv) {\n const value = sources.env[flags.secretEnv]?.trim();\n if (!value) throw new CliError(`Environment variable ${flags.secretEnv} is empty or unset`);\n return value;\n }\n const value = flags.secret?.trim();\n return value ? value : undefined;\n}\n\nfunction providerConfig(\n info: ProviderInfo,\n values: { baseUrl?: string; models?: string[]; defaultModel?: string; binaryPath?: string },\n): Record<string, unknown> {\n const config: Record<string, unknown> = {};\n if (values.baseUrl) config.baseUrl = values.baseUrl.replace(/\\/+$/, '');\n if (values.models && values.models.length > 0) config.models = [...new Set(values.models)];\n if (values.defaultModel) config.defaultModel = values.defaultModel;\n if (values.binaryPath && info.auth === 'cli-login') config.binaryPath = values.binaryPath;\n return config;\n}\n\n/** Build an account from flags only (scripts, CI). Never prompts. */\nexport async function accountFromFlags(\n flags: AddFlags,\n sources: SecretSources,\n): Promise<AccountCreate> {\n const info = requireProvider(flags.provider);\n const secret = await secretFromFlags(flags, sources);\n if (info.auth === 'api-key' && !secret) {\n throw new CliError(`${info.name} needs an API key`, {\n hint: 'Pass it with --secret-env <VAR> or pipe it with --secret-stdin.',\n });\n }\n if (secret && (info.auth === 'cli-login' || info.auth === 'browser')) {\n throw new CliError(`${info.kind} accounts do not take a secret`, {\n hint:\n info.auth === 'cli-login'\n ? 'Log in with `davecode accounts login <id>` after adding the account.'\n : 'The browser profile holds the session.',\n });\n }\n if (info.kind === 'openai-compatible') {\n if (!flags.baseUrl) {\n throw new CliError('openai-compatible accounts need --base-url', {\n hint: `e.g. --base-url ${DEFAULT_COMPATIBLE_URL} for OpenRouter`,\n });\n }\n }\n if (flags.baseUrl) {\n const problem = validateUrl(flags.baseUrl);\n if (problem) throw new CliError(`--base-url ${problem}`);\n }\n const create: AccountCreate = {\n provider: info.kind,\n label: flags.label?.trim() || info.defaultLabel,\n config: providerConfig(info, {\n ...(flags.baseUrl ? { baseUrl: flags.baseUrl } : {}),\n ...(flags.model ? { models: flags.model } : {}),\n ...(flags.defaultModel ? { defaultModel: flags.defaultModel } : {}),\n ...(flags.binaryPath ? { binaryPath: flags.binaryPath } : {}),\n }),\n };\n if (flags.priority !== undefined) create.priority = flags.priority;\n if (flags.weight !== undefined) create.weight = flags.weight;\n const limits = parseLimits(flags.limit);\n if (Object.keys(limits).length > 0) create.limits = limits;\n if (flags.disabled) create.enabled = false;\n if (secret) create.secret = secret;\n return create;\n}\n\n// ---------------------------------------------------------------------------\n// Interactive flow\n// ---------------------------------------------------------------------------\n\nexport interface InteractiveDeps {\n prompter: Prompter;\n config: Pick<DaveConfig, 'experimental'>;\n existing: Pick<Account, 'provider' | 'label'>[];\n /** Print a line (warnings, summary). */\n say: (line: string) => void;\n /** Style ToS warnings. */\n warn?: (text: string) => string;\n}\n\nfunction uniqueLabel(base: string, existing: Pick<Account, 'label'>[]): string {\n const taken = new Set(existing.map((a) => a.label.toLowerCase()));\n if (!taken.has(base.toLowerCase())) return base;\n for (let n = 2; ; n++) {\n const candidate = `${base} ${n}`;\n if (!taken.has(candidate.toLowerCase())) return candidate;\n }\n}\n\n/**\n * Ask for whatever the flags did not provide. Returns `undefined` when the user declines a\n * Terms-of-Service warning or the final confirmation.\n */\nexport async function accountInteractively(\n flags: AddFlags,\n deps: InteractiveDeps,\n): Promise<AccountCreate | undefined> {\n const { prompter, say } = deps;\n const warn = deps.warn ?? ((t: string) => t);\n\n const kind = flags.provider\n ? requireProvider(flags.provider).kind\n : await prompter.select(\n 'Provider',\n PROVIDERS.map((p) => ({ value: p.kind, label: p.name, hint: authHint(p.auth) })),\n 'anthropic',\n );\n const info = requireProvider(kind);\n\n const policy = accountPolicy(info.kind, deps.config, deps.existing);\n if (policy.blocked) throw new CliError(policy.blocked.message, { hint: policy.blocked.hint });\n for (const warning of policy.warnings) {\n say(warn(`! ${warning}`));\n if (!(await prompter.confirm('I understand the risk. Continue?', false))) return undefined;\n }\n\n const label =\n flags.label?.trim() ||\n (await prompter.text('Label', {\n initial: uniqueLabel(info.defaultLabel, deps.existing),\n validate: (v) => (v.trim() ? undefined : 'a label is required'),\n }));\n\n const priority =\n flags.priority ??\n Number(\n await prompter.text('Priority (lower is tried first)', {\n initial: '100',\n validate: (v) => (/^\\d+$/.test(v.trim()) ? undefined : 'enter a non-negative integer'),\n }),\n );\n\n let baseUrl = flags.baseUrl;\n let models = flags.model;\n if (info.kind === 'openai-compatible') {\n baseUrl ??= await prompter.text('Base URL', {\n initial: DEFAULT_COMPATIBLE_URL,\n validate: validateUrl,\n });\n if (!models) {\n const answer = await prompter.text('Models (comma-separated, empty to discover)', {\n initial: '',\n });\n models = answer\n .split(',')\n .map((m) => m.trim())\n .filter(Boolean);\n }\n }\n\n let secret: string | undefined;\n if (info.auth === 'api-key' || info.auth === 'optional-key') {\n const optional = info.auth === 'optional-key';\n const answer = await prompter.secret(\n optional ? 'API key (optional, input hidden)' : `${info.name} key (input hidden)`,\n { optional },\n );\n secret = answer.trim() || undefined;\n if (!secret && !optional) throw new CliError(`${info.name} needs an API key`);\n }\n\n const create: AccountCreate = {\n provider: info.kind,\n label: label.trim(),\n priority,\n config: providerConfig(info, {\n ...(baseUrl ? { baseUrl } : {}),\n ...(models ? { models } : {}),\n ...(flags.defaultModel ? { defaultModel: flags.defaultModel } : {}),\n ...(flags.binaryPath ? { binaryPath: flags.binaryPath } : {}),\n }),\n };\n if (flags.weight !== undefined) create.weight = flags.weight;\n const limits = parseLimits(flags.limit);\n if (Object.keys(limits).length > 0) create.limits = limits;\n if (flags.disabled) create.enabled = false;\n if (secret) create.secret = secret;\n\n say('');\n for (const line of describeCreate(create)) say(` ${line}`);\n say('');\n if (!(await prompter.confirm('Add this account?', true))) return undefined;\n return create;\n}\n\nfunction authHint(auth: AuthKind): string {\n switch (auth) {\n case 'api-key':\n return 'API key';\n case 'optional-key':\n return 'base URL, optional key';\n case 'cli-login':\n return 'local CLI login, isolated per account';\n default:\n return 'experimental, ToS risk';\n }\n}\n\n/** Summary lines for an account about to be created. Secrets are shown only as \"set\". */\nexport function describeCreate(create: AccountCreate): string[] {\n const lines = [\n `provider ${create.provider}`,\n `label ${create.label}`,\n `priority ${create.priority ?? 100}`,\n ];\n const config = create.config ?? {};\n if (typeof config.baseUrl === 'string') lines.push(`base URL ${config.baseUrl}`);\n if (Array.isArray(config.models) && config.models.length > 0) {\n lines.push(`models ${config.models.join(', ')}`);\n }\n if (create.limits && Object.keys(create.limits).length > 0) {\n lines.push(\n `limits ${Object.entries(create.limits)\n .map(([k, v]) => `${k}=${v}`)\n .join(' ')}`,\n );\n }\n if (create.secret !== undefined) lines.push('secret set (stored encrypted)');\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,uBAAuB;;;AC2BzB,IAAM,YAAqC;AAAA,EAChD,EAAE,MAAM,aAAa,MAAM,iBAAiB,MAAM,WAAW,cAAc,YAAY;AAAA,EACvF,EAAE,MAAM,UAAU,MAAM,cAAc,MAAM,WAAW,cAAc,SAAS;AAAA,EAC9E,EAAE,MAAM,UAAU,MAAM,qBAAqB,MAAM,WAAW,cAAc,SAAS;AAAA,EACrF;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,cAAc;AAAA,EAChB;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,cAAc;AAAA,IACd,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,cAAc;AAAA,IACd,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,cAAc;AAAA,IACd,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,cAAc;AAAA,IACd,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,MAAM;AAAA,I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I,IAAI,QAAQ,EAAE,KAAK,QAAQ,QAAQ,GAAG,CAAC,EAAE;AAC3F,MAAI,IAAI,KAAK,mBAAmB,OAAO,UAAU,CAAC,EAAE;AACpD,MAAI,MAAM,SAAS,WAAW,WAAW,YAAa,QAAO,KAAK;AAClE,MAAI,WAAW,WAAW,WAAW;AACnC,QAAI;AAAA,MACF,MAAM;AAAA,QACJ,mDAA8C,QAAQ,KAAK;AAAA,MAC7D;AAAA,IACF;AACA,WAAO,KAAK;AAAA,EACd;AACA,MAAI,WAAW,WAAW,YAAa,QAAO,KAAK;AACnD,MAAI,IAAI;AACR,SAAO,cAAc,KAAK,QAAQ,IAAI,CAAC,GAAG,OAAO,IAAI;AACvD;","names":["value","account"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
brandLogo
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-HENE4DA6.js";
|
|
4
4
|
|
|
5
5
|
// src/ui/banner.ts
|
|
6
6
|
function brandBanner(theme, text, columns = 80, minColumns = 56) {
|
|
@@ -17,4 +17,4 @@ function brandBanner(theme, text, columns = 80, minColumns = 56) {
|
|
|
17
17
|
export {
|
|
18
18
|
brandBanner
|
|
19
19
|
};
|
|
20
|
-
//# sourceMappingURL=chunk-
|
|
20
|
+
//# sourceMappingURL=chunk-K5AA65RS.js.map
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
detectProjectRoot,
|
|
15
15
|
findGateway,
|
|
16
16
|
targetFor
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-JFWMLYV7.js";
|
|
18
18
|
import {
|
|
19
19
|
EXIT
|
|
20
20
|
} from "./chunk-7XVXEO7U.js";
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
QUOTA_WINDOWS,
|
|
23
23
|
createEngine,
|
|
24
24
|
loadConfig
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-HENE4DA6.js";
|
|
26
26
|
|
|
27
27
|
// src/commands/status.ts
|
|
28
28
|
function emptyUsage(accountId) {
|
|
@@ -210,4 +210,4 @@ export {
|
|
|
210
210
|
renderStatus,
|
|
211
211
|
statusCommand
|
|
212
212
|
};
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
213
|
+
//# sourceMappingURL=chunk-ZNUNYYN6.js.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-QA3O6RA2.js";
|
|
7
7
|
import {
|
|
8
8
|
detectProjectRoot
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-JFWMLYV7.js";
|
|
10
10
|
import {
|
|
11
11
|
CliError,
|
|
12
12
|
EXIT
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
globalPaths,
|
|
16
16
|
loadConfig,
|
|
17
17
|
projectPaths
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-HENE4DA6.js";
|
|
19
19
|
import "./chunk-MC7RIPL7.js";
|
|
20
20
|
|
|
21
21
|
// src/commands/config.ts
|
|
@@ -155,4 +155,4 @@ export {
|
|
|
155
155
|
configPath,
|
|
156
156
|
configShow
|
|
157
157
|
};
|
|
158
|
-
//# sourceMappingURL=config-
|
|
158
|
+
//# sourceMappingURL=config-TKGGYEN7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,n as t,o as n,r,t as i}from"./cn-BwE4cei0.js";import{E as a,F as o,R as s,_ as c,d as l,ft as u,h as d,ot as f,p,pt as m,st as h,t as g,u as _,v,x as y,y as b}from"./Badge-DUGKlx3Z.js";import{n as x,t as S}from"./Switch-DPYlLseH.js";import{a as C,c as w,i as ee,l as T,n as te,o as ne,r as re,s as ie,t as ae}from"./forms-DVIUAxAc.js";import{t as E}from"./Callout-WgXHDPg0.js";import{t as D}from"./trash-BTuDcSaQ.js";import{C as O,I as k,J as A,O as j,R as M,_ as N,a as P,d as F,f as I,g as L,i as R,j as z,k as B,m as V,n as H,o as U,p as W,r as G,s as K,t as oe,u as q,w as J,z as se}from"./index-CpztPbom.js";import{n as Y,t as X}from"./Field-Cmpgg_1z.js";var Z={name:`log-in`,size:24,node:[[`path`,{d:`m10 17 5-5-5-5`,key:`1bsop3`}],[`path`,{d:`M15 12H3`,key:`6jk70r`}],[`path`,{d:`M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4`,key:`u53s6r`}]]};Z.node;var ce=t(Z),le={name:`shield-alert`,size:24,node:[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M12 16h.01`,key:`1drbdi`}]]};le.node;var ue=t(le),Q=n(e(),1),$=r(),de=3e5,fe={connected:{tone:`ok`,label:`Connected`},not_connected:{tone:`warn`,label:`Not connected`},unknown:{tone:`neutral`,label:`Unknown`}};function pe({status:e}){let{tone:t,label:n}=fe[e];return(0,$.jsx)(g,{tone:t,dot:!0,children:n})}function me({account:e}){let[t,n]=(0,Q.useState)(null),r=v(e.id,t!==null),i=c(),a=r.data,o=a?.status===`connected`;return(0,Q.useEffect)(()=>{if(!t)return;if(o){n(null),O({tone:`ok`,title:`Subscription connected`,description:e.label});return}let r=window.setTimeout(()=>n(null),de);return()=>window.clearTimeout(r)},[t,o,e.label]),(0,$.jsxs)(`section`,{"aria-label":`Connection`,className:`flex flex-col gap-2.5 rounded-md border border-line bg-raised p-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`text-[12px] font-medium text-fg-2`,children:`Connection`}),a?(0,$.jsx)(pe,{status:a.status}):r.isError?(0,$.jsx)(g,{tone:`err`,children:`Check failed`}):(0,$.jsx)(g,{children:`Checking…`}),(0,$.jsx)(J,{variant:`ghost`,size:`sm`,icon:M,iconOnly:!0,"aria-label":`Check again`,className:`ml-auto`,loading:r.isFetching&&!t,onClick:()=>r.refetch()})]}),a?.detail&&(0,$.jsx)(`p`,{className:`text-2xs leading-5 text-muted`,children:a.detail}),r.isError&&(0,$.jsx)(`p`,{className:`text-2xs leading-5 text-err`,children:u(r.error)}),a?.method===`cli-login`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(J,{variant:o?`secondary`:`primary`,size:`sm`,icon:ce,loading:i.isPending,onClick:async()=>{try{n(await i.mutateAsync(e.id))}catch(e){O({tone:`err`,title:`Could not start the sign-in`,description:u(e)})}},children:o?`Sign in again`:`Connect subscription`}),(0,$.jsx)(`span`,{className:`text-2xs text-muted`,children:`Opens the vendor’s official sign-in. DaveCode never sees your password.`})]}),t&&(0,$.jsxs)(E,{tone:`info`,title:t.launched?`Waiting for the sign-in…`:`Run the sign-in on the gateway machine`,children:[(0,$.jsx)(`p`,{children:t.message}),!t.launched&&(0,$.jsx)(W,{command:t.command,className:`mt-2`})]}),!t&&!o&&a.loginCommand&&(0,$.jsx)(W,{command:a.loginCommand})]})]})}function he({account:e,usage:t,onClose:n}){return(0,$.jsx)(I,{open:!!e,onClose:n,title:e?.label??`Account`,description:e&&(0,$.jsx)(`span`,{className:`font-mono`,children:e.id}),width:`w-[min(560px,100vw)]`,children:e&&(0,$.jsx)(ge,{account:e,usage:t,onDone:n},e.id)})}function ge({account:e,usage:t,onDone:n}){let r=o(),i=y(),a=h(e.provider),s=Array.isArray(e.config.models)?e.config.models.join(`, `):``,[c,d]=(0,Q.useState)(e.label),[f,p]=(0,Q.useState)(String(e.priority)),[m,g]=(0,Q.useState)(String(e.weight)),[_,v]=(0,Q.useState)(C(e.limits)),[b,x]=(0,Q.useState)(T(e.subscription)),[S,k]=(0,Q.useState)({}),[A,j]=(0,Q.useState)(typeof e.config.baseUrl==`string`?e.config.baseUrl:``),[M,I]=(0,Q.useState)(s),[R,z]=(0,Q.useState)(``),[B,V]=(0,Q.useState)({}),[H,W]=(0,Q.useState)({}),[G,K]=(0,Q.useState)(null),[oe,q]=(0,Q.useState)(!1);return(0,$.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault(),K(null);let i={};c.trim()||(i.label=`Label cannot be empty.`);let a=Number(f);(!Number.isInteger(a)||a<0)&&(i.priority=`Whole number, 0 or more.`);let o=Number(m);(!Number.isFinite(o)||o<=0)&&(i.weight=`Number above 0.`),e.provider===`openai-compatible`&&!ee(A.trim())&&(i.baseUrl=`Enter an http(s) URL.`),e.provider===`openai-compatible`&&e.hasSecret&&!R.trim()&&A.trim().replace(/\/+$/,``)!==(typeof e.config.baseUrl==`string`?e.config.baseUrl:``).replace(/\/+$/,``)&&(i.secret=`Enter the API key again to point this account at a different URL.`);let s=ne(_),l=w(b);if(V(i),W(s.errors),k(l.errors),Object.values(i).some(Boolean)||Object.keys(s.errors).length||Object.keys(l.errors).length)return;let d={};if(c.trim()!==e.label&&(d.label=c.trim()),a!==e.priority&&(d.priority=a),o!==e.weight&&(d.weight=o),JSON.stringify(s.limits)!==JSON.stringify(e.limits)&&(d.limits=s.limits),JSON.stringify(l.subscription??null)!==JSON.stringify(e.subscription??null)&&(d.subscription=l.subscription??null),e.provider===`openai-compatible`){let t=ie(M),n={...e.config,baseUrl:A.trim(),models:t.length?t:void 0};JSON.stringify(n)!==JSON.stringify(e.config)&&(d.config=n)}if(R.trim()&&(d.secret=R.trim()),Object.keys(d).length===0)n();else try{await r.mutateAsync({id:e.id,patch:d}),z(``),O({tone:`ok`,title:`Account updated`,description:e.label}),n()}catch(e){z(``),K(u(e))}},noValidate:!0,className:`flex flex-col gap-5`,children:[(0,$.jsxs)(`section`,{"aria-label":`Summary`,className:`flex flex-col gap-3 rounded-md border border-line bg-raised p-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,$.jsx)(N,{provider:e.provider,size:`lg`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`text-[13px] font-medium text-fg`,children:a.label}),(0,$.jsxs)(`p`,{className:`font-mono text-2xs text-muted`,children:[e.provider,` · updated `,l(Date.parse(e.updatedAt))]})]}),(0,$.jsx)(L,{account:e})]}),e.lastError&&e.status!==`active`&&(0,$.jsx)(`p`,{className:`rounded border border-line bg-panel px-2 py-1.5 font-mono text-2xs text-fg-2`,children:e.lastError}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(U,{label:`1m`,usage:t?.windows[`1m`]}),(0,$.jsx)(U,{label:`5h`,usage:t?.windows[`5h`]}),(0,$.jsx)(U,{label:`24h`,usage:t?.windows[`24h`]}),(0,$.jsx)(P,{className:`pl-9`})]})]}),(0,$.jsx)(me,{account:e}),(0,$.jsx)(X,{label:`Label`,required:!0,error:B.label,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,value:c,onChange:e=>d(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0})}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,$.jsx)(X,{label:`Priority`,error:B.priority,hint:`Lower is tried first.`,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,inputMode:`numeric`,value:f,onChange:e=>p(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0,className:`tnum font-mono`})}),(0,$.jsx)(X,{label:`Weight`,error:B.weight,hint:`Share among equal priorities.`,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,inputMode:`decimal`,value:m,onChange:e=>g(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0,className:`tnum font-mono`})})]}),e.provider===`openai-compatible`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{label:`Base URL`,required:!0,error:B.baseUrl,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,type:`url`,value:A,onChange:e=>j(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0,className:`font-mono`})}),(0,$.jsx)(X,{label:`Models`,hint:`Comma-separated allow-list.`,children:({id:e,describedBy:t})=>(0,$.jsx)(Y,{id:e,value:M,onChange:e=>I(e.target.value),"aria-describedby":t,className:`font-mono`})})]}),(a.auth===`api-key`||a.auth===`optional-key`)&&(0,$.jsx)(X,{label:`Replace ${(a.secretLabel??`secret`).replace(` (optional)`,``)}`,error:B.secret,hint:e.hasSecret===!1?`No secret stored yet. Write-only: it is encrypted at rest and never displayed.`:`A secret is stored. Write-only: leave empty to keep it; it is never displayed.`,children:({id:e,describedBy:t})=>(0,$.jsx)(te,{id:e,value:R,onChange:z,placeholder:`••••••••••••`,describedBy:t})}),(0,$.jsxs)(`fieldset`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`legend`,{className:`mb-2 text-[12px] font-medium text-fg-2`,children:`Quota limits`}),(0,$.jsx)(ae,{value:_,onChange:v,errors:H})]}),(0,$.jsxs)(`fieldset`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`legend`,{className:`mb-1 text-[12px] font-medium text-fg-2`,children:`Subscription`}),(0,$.jsx)(`p`,{className:`mb-1 text-2xs text-muted`,children:`What you pay for this account. Entered by hand; DaveCode never reads billing pages. Agents see the plan, renewal and remaining budget, never secrets.`}),(0,$.jsx)(re,{value:b,onChange:x,errors:S})]}),Object.keys(e.config).length>0&&e.provider!==`openai-compatible`&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,$.jsx)(`p`,{className:`text-[12px] font-medium text-fg-2`,children:`Provider config`}),(0,$.jsx)(`pre`,{className:`overflow-x-auto rounded-md border border-line bg-raised p-2.5 font-mono text-2xs leading-5 text-fg-2`,children:JSON.stringify(e.config,null,2)})]}),G&&(0,$.jsx)(E,{tone:`err`,title:`Request failed`,children:G}),(0,$.jsxs)(`div`,{className:`sticky -bottom-4 -mx-5 -mb-4 flex items-center gap-2 border-t border-line bg-panel px-5 py-3`,children:[(0,$.jsx)(J,{variant:`danger`,icon:D,onClick:()=>q(!0),children:`Delete`}),(0,$.jsxs)(`div`,{className:`ml-auto flex gap-2`,children:[(0,$.jsx)(J,{variant:`ghost`,onClick:n,children:`Cancel`}),(0,$.jsx)(J,{type:`submit`,variant:`primary`,loading:r.isPending,children:`Save changes`})]})]}),(0,$.jsx)(F,{open:oe,onClose:()=>q(!1),title:`Delete ${e.label}?`,description:`The account and its encrypted secret are removed from the gateway. Requests already served stay in the usage history.`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(J,{variant:`ghost`,onClick:()=>q(!1),children:`Keep account`}),(0,$.jsx)(J,{variant:`danger`,icon:D,loading:i.isPending,onClick:async()=>{try{await i.mutateAsync(e.id),O({tone:`ok`,title:`Account removed`,description:e.label}),q(!1),n()}catch(e){q(!1),K(u(e))}},children:`Delete account`})]}),children:(0,$.jsx)(`p`,{className:`font-mono text-[12px] text-muted`,children:e.id})})]})}var _e={"claude-cli":{binary:`claude`,env:`CLAUDE_CONFIG_DIR`},"codex-cli":{binary:`codex`,env:`CODEX_HOME`},"gemini-cli":{binary:`gemini`,env:`GEMINI_CLI_HOME`}};function ve({open:e,onClose:t}){return(0,$.jsx)(I,{open:e,onClose:t,title:`Add account`,description:`Secrets are encrypted at rest with AES-256-GCM and are never shown again after saving.`,width:`w-[min(560px,100vw)]`,children:e&&(0,$.jsx)(ye,{onDone:t})})}function ye({onDone:e}){let t=a(),n=p(),r=b(),o=t.data?.experimental.geminiWeb??!1,s=t.data?.experimental.multiAccountRotation??!1,[c,l]=(0,Q.useState)(`anthropic`),[d,g]=(0,Q.useState)(``),[_,v]=(0,Q.useState)(``),[y,x]=(0,Q.useState)(``),[S,w]=(0,Q.useState)(``),[T,re]=(0,Q.useState)(`100`),[D,k]=(0,Q.useState)(`1`),[A,j]=(0,Q.useState)(C()),[M,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)({}),[L,R]=(0,Q.useState)(null),z=h(c),B=(n.data??[]).filter(e=>e.provider===c),V=z.subscription&&B.length>0&&!s,H=c===`gemini-web`&&!o;return(0,$.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault(),R(null);let n={};d.trim()||(n.label=`Give the account a name you will recognise in logs.`),z.auth===`api-key`&&!_.trim()&&(n.secret=`${z.secretLabel??`Secret`} is required.`),c===`openai-compatible`&&!ee(y.trim())&&(n.baseUrl=`Enter an http(s) URL ending in the /v1 base, e.g. http://127.0.0.1:11434/v1`);let i=Number(T);(!Number.isInteger(i)||i<0)&&(n.priority=`Whole number, 0 or more.`);let a=Number(D);(!Number.isFinite(a)||a<=0)&&(n.weight=`Number above 0.`),c===`gemini-web`&&!M&&(n.ack=`Confirm that you accept the risk.`);let o=ne(A);if(Object.keys(o.errors).length&&(n.limits=o.errors),I(n),Object.keys(n).length||H)return;let s={};if(c===`openai-compatible`){s.baseUrl=y.trim();let e=ie(S);e.length&&(s.models=e)}let l={provider:c,label:d.trim(),priority:i,weight:a,...Object.keys(o.limits).length&&{limits:o.limits},...Object.keys(s).length&&{config:s},..._.trim()&&{secret:_.trim()}};try{let t=await r.mutateAsync(l);v(``),O({tone:`ok`,title:`Account added`,description:`${t.label} (${t.id})`}),e()}catch(e){v(``),R(m(e)&&e.code===`experimental_disabled`?`The gateway refused this provider: experimental.geminiWeb is off in config.json.`:u(e))}},noValidate:!0,className:`flex flex-col gap-5`,children:[(0,$.jsxs)(`fieldset`,{children:[(0,$.jsx)(`legend`,{className:`mb-2 text-[12px] font-medium text-fg-2`,children:`Provider`}),(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:f.map(e=>{let t=h(e),n=e===`gemini-web`&&!o,r=c===e;return(0,$.jsxs)(`label`,{className:i(`relative flex cursor-pointer items-start gap-2.5 rounded-md border p-2.5 transition-colors duration-150`,`has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-accent`,r?`border-accent/60 bg-accent-soft`:`border-line hover:border-line-strong hover:bg-hover`,n&&!r&&`opacity-60`),children:[(0,$.jsx)(`input`,{type:`radio`,name:`provider`,value:e,checked:r,onChange:()=>{l(e),I({}),R(null)},className:`sr-only`}),(0,$.jsx)(N,{provider:e}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-1.5 text-[13px] font-medium text-fg`,children:[t.label,t.experimental&&(0,$.jsx)(`span`,{className:`rounded border border-warn/30 px-1 text-2xs font-medium text-warn`,children:n?`off`:`experimental`})]}),(0,$.jsx)(`span`,{className:`block font-mono text-2xs text-muted`,children:e})]})]},e)})}),(0,$.jsx)(`p`,{className:`mt-2 text-[12px] text-muted`,children:z.blurb})]}),c===`gemini-web`&&(0,$.jsxs)(E,{tone:`warn`,title:`Terms of Service risk`,children:[(0,$.jsx)(`p`,{children:`This provider automates a consumer Gemini web session through Chromium. That likely violates Google's Terms of Service and the account can be rate-limited or suspended.`}),o?(0,$.jsxs)(`label`,{className:`mt-2 flex items-start gap-2 text-fg`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>P(e.target.checked),className:`mt-0.5 accent-accent`,"aria-describedby":F.ack?`ack-error`:void 0}),`I understand the risk and want to add this account anyway.`]}):(0,$.jsxs)(`p`,{className:`mt-1.5`,children:[`It is disabled on this gateway. To opt in, set`,` `,(0,$.jsxs)(`code`,{className:`font-mono text-fg`,children:[`"experimental": `,`{ "geminiWeb": true }`]}),` `,`in `,(0,$.jsx)(`code`,{className:`font-mono text-fg`,children:`~/.davecode/config.json`}),` and restart.`]}),F.ack&&(0,$.jsx)(`p`,{id:`ack-error`,role:`alert`,className:`mt-1 text-err`,children:F.ack})]}),V&&(0,$.jsxs)(E,{tone:`info`,title:`Multi-account rotation is off`,children:[`You already have a `,z.label,` account. Without`,` `,(0,$.jsx)(`code`,{className:`font-mono text-fg`,children:`experimental.multiAccountRotation`}),` the router uses only one subscription login per provider; the others act as manual fallbacks.`]}),!H&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{label:`Label`,required:!0,error:F.label,hint:`Shown in the dashboard, logs and events.`,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,value:d,placeholder:c===`openai-compatible`?`OpenRouter`:`${z.label} — work`,onChange:e=>g(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0,"aria-required":!0})}),c===`openai-compatible`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{label:`Base URL`,required:!0,error:F.baseUrl,hint:`The OpenAI-compatible root, including /v1.`,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,type:`url`,value:y,placeholder:`http://127.0.0.1:11434/v1`,onChange:e=>x(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0,className:`font-mono`})}),(0,$.jsx)(X,{label:`Models`,hint:`Comma-separated allow-list. Leave empty to discover via /v1/models.`,children:({id:e,describedBy:t})=>(0,$.jsx)(Y,{id:e,value:S,placeholder:`Provider model IDs`,onChange:e=>w(e.target.value),"aria-describedby":t,className:`font-mono`})})]}),z.auth===`cli`?(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`p`,{className:`text-[12px] text-muted`,children:[`DaveCode runs the`,` `,(0,$.jsx)(`span`,{className:`font-mono text-fg`,children:_e[c]?.binary}),` found on your PATH. To use another binary, add the account from a terminal with`,` `,(0,$.jsx)(`span`,{className:`font-mono text-fg`,children:`--binary-path`}),`. No secret is needed here. After adding, open the account and press`,` `,(0,$.jsx)(`span`,{className:`text-fg-2`,children:`Connect subscription`}),`: it runs the vendor’s official sign-in inside the account’s own sandbox (`,_e[c]?.env,`). DaveCode never sees your password. From a terminal:`]}),(0,$.jsx)(W,{command:`davecode add-account --provider ${c}`})]}):z.auth===`browser`?null:(0,$.jsx)(X,{label:z.secretLabel??`Secret`,required:z.auth===`api-key`,error:F.secret,hint:`Write-only. Encrypted at rest; no endpoint ever returns it.`,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(te,{id:e,value:_,onChange:v,placeholder:z.secretPlaceholder,describedBy:t,invalid:n})}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,$.jsx)(X,{label:`Priority`,error:F.priority,hint:`Lower is tried first.`,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,inputMode:`numeric`,value:T,onChange:e=>re(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0,className:`tnum font-mono`})}),(0,$.jsx)(X,{label:`Weight`,error:F.weight,hint:`Share among equal priorities.`,children:({id:e,describedBy:t,invalid:n})=>(0,$.jsx)(Y,{id:e,inputMode:`decimal`,value:D,onChange:e=>k(e.target.value),"aria-describedby":t,"aria-invalid":n||void 0,className:`tnum font-mono`})})]}),(0,$.jsxs)(`details`,{className:`group rounded-md border border-line`,children:[(0,$.jsxs)(`summary`,{className:`flex items-center justify-between px-3 py-2 text-[12px] font-medium text-fg-2 select-none hover:text-fg`,children:[`Quota limits`,(0,$.jsx)(`span`,{className:`text-2xs font-normal text-muted group-open:hidden`,children:`optional · unlimited by default`})]}),(0,$.jsx)(`div`,{className:`border-t border-line p-3`,children:(0,$.jsx)(ae,{value:A,onChange:j,errors:F.limits??{}})})]})]}),L&&(0,$.jsx)(E,{tone:`err`,title:`Could not add the account`,children:L}),(0,$.jsxs)(`div`,{className:`sticky -bottom-4 -mx-5 -mb-4 flex items-center justify-end gap-2 border-t border-line bg-panel px-5 py-3`,children:[(0,$.jsx)(J,{variant:`ghost`,onClick:e,children:`Cancel`}),(0,$.jsx)(J,{type:`submit`,variant:`primary`,loading:r.isPending,disabled:H,icon:H?ue:void 0,children:H?`Disabled by config`:`Add account`})]})]})}function be(e){if(!e)return;let t=e.price?`${e.price.amount} ${e.price.currency}/${e.price.period===`month`?`mo`:`yr`}`:void 0;return[e.plan,t].filter(Boolean).join(` · `)||void 0}function xe({days:e}){return e===void 0?(0,$.jsx)(`span`,{className:`text-faint`,children:`—`}):e<0?(0,$.jsxs)(g,{tone:`err`,children:[`overdue `,-e,`d`]}):(0,$.jsx)(g,{tone:e<=3?`warn`:`neutral`,mono:!0,children:e===0?`today`:`in ${e}d`})}function Se({budget:e}){if(e.remaining===null)return(0,$.jsx)(`span`,{className:`text-2xs text-faint`,children:`no limit known`});let t=e.remaining,n=t<=.1?`bg-err`:t<=.15?`bg-warn`:`bg-meter`;return(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(`div`,{role:`meter`,"aria-label":`${e.label} remaining budget`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(t*100),className:`relative h-1.5 min-w-16 flex-1 rounded-full bg-track`,children:(0,$.jsx)(`div`,{className:i(`absolute inset-y-0 left-0 rounded-full transition-[width] duration-500 ease-snappy`,n),style:{width:`${Math.min(100,t*100)}%`}})}),(0,$.jsx)(`span`,{className:`tnum w-9 shrink-0 text-right font-mono text-2xs text-fg-2`,children:_(t)}),(0,$.jsx)(`span`,{className:`w-14 shrink-0 font-mono text-2xs text-muted`,children:e.tightestWindow??`provider`})]})}function Ce(){let e=d(),[t,n]=(0,Q.useState)(!1),r=e.data?.accounts??[],a=r.filter(e=>e.enabled),o=a.filter(e=>e.available).length;return(0,$.jsxs)(G,{"aria-labelledby":`budget-title`,children:[(0,$.jsx)(R,{id:`budget-title`,title:`Budget`,meta:e.data?`${o} of ${a.length} enabled accounts available · plans are entered by hand`:void 0,actions:(0,$.jsx)(J,{size:`sm`,variant:`ghost`,icon:A,"aria-expanded":t,onClick:()=>n(e=>!e),children:`What agents see`})}),e.isPending?(0,$.jsx)(q,{rows:3}):e.isError?(0,$.jsx)(`p`,{className:`px-3.5 py-3 text-[12px] text-err`,children:u(e.error)}):(0,$.jsxs)($.Fragment,{children:[t&&(0,$.jsxs)(`div`,{className:`relative border-b border-line bg-raised px-3.5 py-3`,children:[(0,$.jsx)(V,{value:e.data.context,label:`Copy agent budget context`,className:`absolute top-2 right-2`}),(0,$.jsx)(`pre`,{className:`overflow-x-auto pr-8 font-mono text-2xs leading-5 whitespace-pre-wrap text-fg-2`,children:e.data.context||`No enabled accounts: agents get no budget context.`})]}),(0,$.jsx)(`ul`,{className:`divide-y divide-line`,children:r.map(e=>(0,$.jsx)(`li`,{children:(0,$.jsxs)(`button`,{type:`button`,onClick:()=>j(`account`,e.accountId),className:i(`grid w-full grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_auto] items-center gap-x-4 gap-y-1.5 px-3.5 py-2.5 text-left transition-colors duration-150 hover:bg-hover/60 md:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_5.5rem_minmax(0,1.2fr)_minmax(0,1fr)]`,!e.enabled&&`text-muted`),children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(N,{provider:e.provider}),(0,$.jsx)(`span`,{className:`truncate text-[13px] font-medium`,children:e.label})]}),(0,$.jsx)(`span`,{className:`truncate text-[12px] text-fg-2`,children:be(e.subscription)??(0,$.jsx)(`span`,{className:`text-faint`,children:`no plan`})}),(0,$.jsx)(`span`,{className:`justify-self-end md:justify-self-start`,children:(0,$.jsx)(xe,{days:e.renewsInDays})}),(0,$.jsx)(`span`,{className:`col-span-2 md:col-span-1`,children:(0,$.jsx)(Se,{budget:e})}),(0,$.jsx)(`span`,{className:`truncate text-[12px] md:text-right`,children:e.available?(0,$.jsx)(g,{tone:`ok`,dot:!0,children:`available`}):(0,$.jsx)(`span`,{className:`text-warn`,title:e.unavailableReason,children:e.unavailableReason??`unavailable`})})]})},e.accountId))})]})]})}function we(){let e=p(),t=s(),n=o(),{params:r}=B(),[a,c]=(0,Q.useState)(``),[l,d]=(0,Q.useState)(`all`),f=r.get(`account`),m=r.get(`new`)===`1`,g=(0,Q.useMemo)(()=>new Map((t.data??[]).map(e=>[e.accountId,e])),[t.data]),_=(0,Q.useMemo)(()=>[...e.data??[]].sort((e,t)=>e.priority-t.priority||e.label.localeCompare(t.label)),[e.data]),v=(0,Q.useMemo)(()=>{let e={all:_.length,active:0,cooldown:0,disabled:0,error:0};for(let t of _)e[t.status]+=1;return e},[_]),y=a.trim().toLowerCase(),b=_.filter(e=>(l===`all`||e.status===l)&&(!y||e.label.toLowerCase().includes(y)||e.id.toLowerCase().includes(y)||e.provider.includes(y))),C=_.find(e=>e.id===f),w=(e,t)=>{n.mutate({id:e.id,patch:{enabled:t}},{onError:n=>O({tone:`err`,title:`Could not ${t?`enable`:`disable`} ${e.label}`,description:u(n)})})};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsx)(H,{title:`Accounts`,description:`Provider accounts the router balances across. Lower priority numbers are tried first.`,actions:(0,$.jsx)(J,{variant:`primary`,icon:se,onClick:()=>j(`new`,`1`),children:`Add account`})}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative w-full sm:w-64`,children:[(0,$.jsx)(k,{"aria-hidden":!0,className:`pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted`,strokeWidth:1.75}),(0,$.jsx)(Y,{type:`search`,"aria-label":`Filter accounts`,placeholder:`Filter by label, id or provider`,value:a,onChange:e=>c(e.target.value),className:`pl-8`,"data-filter-input":!0})]}),(0,$.jsx)(oe,{label:`Status`,value:l,onChange:d,options:[{value:`all`,label:`All`,count:v.all},{value:`active`,label:`Active`,count:v.active},{value:`cooldown`,label:`Cooldown`,count:v.cooldown},{value:`disabled`,label:`Disabled`,count:v.disabled},{value:`error`,label:`Error`,count:v.error}]}),(0,$.jsx)(P,{className:`ml-auto hidden lg:flex`})]}),e.isError&&(0,$.jsx)(E,{tone:`err`,title:`Could not load accounts`,children:u(e.error)}),(0,$.jsx)(G,{children:e.isPending?(0,$.jsx)(q,{rows:5}):_.length===0?(0,$.jsx)(K,{icon:z,title:`No accounts yet`,description:`Add an API key, a local OpenAI-compatible server or a CLI login. The router starts using it immediately.`,command:`davecode add-account`,action:(0,$.jsx)(J,{variant:`primary`,icon:se,onClick:()=>j(`new`,`1`),children:`Add account`})}):b.length===0?(0,$.jsx)(K,{icon:k,title:`No matching accounts`,description:`Try a different filter.`}):(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[880px] text-[13px]`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Accounts`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-line text-left text-[12px] text-muted`,children:[(0,$.jsx)(`th`,{scope:`col`,className:`w-[32%] px-3.5 py-2 font-medium`,children:`Account`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-medium`,children:`Status`}),(0,$.jsx)(`th`,{scope:`col`,className:`w-20 px-3 py-2 text-right font-medium`,children:`Priority`}),(0,$.jsx)(`th`,{scope:`col`,className:`w-20 px-3 py-2 text-right font-medium`,children:`Weight`}),(0,$.jsx)(`th`,{scope:`col`,className:`w-[30%] px-3 py-2 font-medium`,children:`Quota`}),(0,$.jsx)(`th`,{scope:`col`,className:`w-20 px-3 py-2 font-medium`,children:`Enabled`}),(0,$.jsx)(`th`,{scope:`col`,className:`w-10 px-2 py-2`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Details`})})]})}),(0,$.jsx)(`tbody`,{children:b.map(e=>{let t=g.get(e.id),n=h(e.provider);return(0,$.jsxs)(`tr`,{onClick:()=>j(`account`,e.id),className:i(`group cursor-pointer border-b border-line transition-colors duration-150 last:border-b-0 hover:bg-hover/60`,f===e.id&&`bg-hover/60`,!e.enabled&&`text-muted`),children:[(0,$.jsx)(`td`,{className:`max-w-0 px-3.5 py-2.5`,children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2.5`,children:[(0,$.jsx)(N,{provider:e.provider}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),j(`account`,e.id)},className:`block max-w-full truncate text-left font-medium text-fg hover:underline focus-visible:underline`,children:e.label}),(0,$.jsxs)(`p`,{className:`truncate font-mono text-2xs text-muted`,children:[e.id,` · `,n.label,n.experimental&&(0,$.jsx)(`span`,{className:`text-warn`,children:` · experimental`})]})]})]})}),(0,$.jsx)(`td`,{className:`px-3 py-2.5`,children:(0,$.jsx)(L,{account:e})}),(0,$.jsx)(`td`,{className:`tnum px-3 py-2.5 text-right font-mono`,children:e.priority}),(0,$.jsx)(`td`,{className:`tnum px-3 py-2.5 text-right font-mono`,children:e.weight}),(0,$.jsx)(`td`,{className:`px-3 py-2`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(U,{label:`1m`,usage:t?.windows[`1m`]}),(0,$.jsx)(U,{label:`5h`,usage:t?.windows[`5h`]}),(0,$.jsx)(U,{label:`24h`,usage:t?.windows[`24h`]})]})}),(0,$.jsx)(`td`,{className:`px-3 py-2.5`,children:(0,$.jsx)(S,{checked:e.enabled,onChange:t=>w(e,t),label:`${e.enabled?`Disable`:`Enable`} ${e.label}`})}),(0,$.jsx)(`td`,{className:`px-2 py-2.5 text-muted`,children:(0,$.jsx)(x,{"aria-hidden":!0,className:`size-4 transition-transform duration-150 group-hover:translate-x-0.5`,strokeWidth:1.75})})]},e.id)})})]})})}),_.length>0&&(0,$.jsx)(Ce,{}),(0,$.jsx)(ve,{open:m,onClose:()=>j(`new`,null)}),(0,$.jsx)(he,{account:C,usage:C?g.get(C.id):void 0,onClose:()=>j(`account`,null)})]})}export{we as Accounts};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,o as n,r,t as i}from"./cn-BwE4cei0.js";var a=n(e(),1),o=r(),s=a.createContext(void 0),c=e=>{let t=a.useContext(s);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},l=({client:e,children:t})=>(a.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,o.jsx)(s.Provider,{value:e,children:t})),u={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},d=new class{#e=u;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function f(e){setTimeout(e,0)}var p=typeof window>`u`||`Deno`in globalThis;function m(){}function h(e,t){return typeof e==`function`?e(t):e}function g(e){return typeof e==`number`&&e>=0&&e!==1/0}function _(e,t){return Math.max(e+(t||0)-Date.now(),0)}function v(e,t){return typeof e==`function`?e(t):e}function y(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==x(o,t.options))return!1}else if(!C(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function b(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(S(t.options.mutationKey)!==S(a))return!1}else if(!C(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function x(e,t){return(t?.queryKeyHashFn||S)(e)}function S(e){return JSON.stringify(e,(e,t)=>T(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function C(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!C(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!C(e[r],t[r]))return!1;return!0}return!1}var ee=Object.prototype.hasOwnProperty;function te(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ne(e)&&ne(t);if(!r&&!(T(e)&&T(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:ee.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=te(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function w(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function ne(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function T(e){if(!re(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!re(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function re(e){return Object.prototype.toString.call(e)===`[object Object]`}function ie(e){return new Promise(t=>{d.setTimeout(t,e)})}function E(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:te(e,t)}function ae(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function oe(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var D=Symbol();function se(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===D?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ce(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var ue=()=>p,de=()=>ue(),O=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},fe=new class extends O{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},pe=f;function me(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=pe,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var k=me(),he=new class extends O{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function ge(e){return Math.min(1e3*2**e,3e4)}function _e(e){return(e??`online`)!==`online`||he.isOnline()}var ve=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function ye(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(m);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new ve(t);g(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>fe.isFocused()&&(e.networkMode===`always`||he.isOnline())&&e.canRun(),p=()=>_e(e.networkMode)&&e.canRun(),h=e=>{c()||(r?.(),i=`resolved`,a(e))},g=e=>{c()||(r?.(),i=`rejected`,o(e))},_=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),v=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(h).catch(r=>{if(c())return;let i=e.retry??(de()?0:3),a=e.retryDelay??ge,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?g(r):(n++,e.onFail?.(n,r),ie(o).then(()=>f()?void 0:_(f)).then(()=>{t?g(r):v()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?v():_(p).then(v),s)}}var be=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),g(this.gcTime)&&(this.#e=d.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(de()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(d.clearTimeout(this.#e),this.#e=void 0)}};function xe(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{le(e,()=>t.signal,()=>n=!0)},u=se(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?oe:ae;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ce:Se,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:Se(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Se(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Ce(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var we=class extends be{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=De(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=De(this.options);e.data!==void 0&&(this.setState(Ee(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=E(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(m).catch(m):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>v(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===D||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>v(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!_(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=se(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?xe(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=ye({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ve&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ve){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Te(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ee(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),k.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Te(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_e(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ee(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function De(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Oe=class extends O{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ae(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return A(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return A(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof v(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!w(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&je(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||v(this.options.staleTime,this.#t)!==v(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return w(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(m)),t}#h(e){return!de()&&v(this.options.enabled,this.#t)!==!1&&g(e)}#g(){this.#b();let e=v(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=_(this.#r.dataUpdatedAt,e)+1;this.#u=d.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return v(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=d.setInterval(()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(d.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(d.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Ae(e,t),o=i&&je(e,n,t,r);(a||o)&&(l={...l,...Te(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=E(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=E(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,y=m===`error`,b=_&&g,x=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:y,isInitialLoading:b,isLoading:b,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:y&&!x,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:y&&x,isStale:j(e,t),refetch:this.refetch,isEnabled:v(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),w(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();k.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function ke(e,t){return v(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||v(t.retryOnMount,e)!==!1)}function Ae(e,t){return ke(e,t)||e.state.data!==void 0&&A(e,t,t.refetchOnMount)}function A(e,t,n){if(v(t.enabled,e)!==!1&&v(t.staleTime,e)!==`static`){let r=v(n,e);return r===`always`||r!==!1&&j(e,t)}return!1}function je(e,t,n,r){return(e!==t||v(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&j(e,n)}function j(e,t){return v(t.enabled,e)!==!1&&e.isStaleByTime(v(t.staleTime,e))}var Me=class extends be{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Ne(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=ye({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),k.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Ne(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Pe=class extends O{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),w(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&S(t.mutationKey)!==S(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Ne();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){k.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Fe=a.createContext(!1),Ie=()=>a.useContext(Fe);Fe.Provider;function Le(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Re=a.createContext(Le()),ze=()=>a.useContext(Re),Be=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?ce(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ve=e=>{a.useEffect(()=>{e.clearReset()},[e])},He=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ce(n,[e.error,r])),Ue=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},We=(e,t)=>e?.suspense&&t.isPending,Ge=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ke(e,t,n){let r=Ie(),i=ze(),o=c(n),s=o.defaultQueryOptions(e),l=o.getQueryCache().get(s.queryHash),u=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:u?`optimistic`:void 0,Ue(s),Be(s,i,l),Ve(i);let[d]=a.useState(()=>new t(o,s)),f=d.getOptimisticResult(s),p=!r&&u;if(a.useSyncExternalStore(a.useCallback(e=>{let t=p?d.subscribe(k.batchCalls(e)):m;return d.updateResult(),t},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),a.useEffect(()=>{d.setOptions(s)},[s,d]),We(s,f))throw Ge(s,d,i);if(He({result:f,errorResetBoundary:i,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw f.error;return s.notifyOnChangeProps?f:d.trackResult(f)}function M(e,t){return Ke(e,Oe,t)}function N(e,t){let n=c(t),[r]=a.useState(()=>new Pe(n,e));a.useEffect(()=>{r.setOptions(e)},[r,e]);let i=a.useSyncExternalStore(a.useCallback(e=>r.subscribe(k.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=a.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(m)},[r]);if(i.error&&ce(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}var qe={name:`asterisk`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m18.065 8.496-12.125 7`,key:`1h26g9`}],[`path`,{d:`m5.94 8.504 12.125 7`,key:`k77sdm`}]]};qe.node;var Je=t(qe),Ye={name:`globe`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20`,key:`13o1zl`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}]]};Ye.node;var Xe=t(Ye),Ze={name:`hexagon`,size:24,node:[[`path`,{d:`M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z`,key:`yt0hxn`}]]};Ze.node;var Qe=t(Ze),$e={name:`server`,size:24,node:[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]};$e.node;var et=t($e),tt={name:`sparkle`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}]]};tt.node;var nt=t(tt),rt={name:`sparkles`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]],aliases:[`stars`]};rt.node;var it=t(rt),at={name:`square-terminal`,size:24,node:[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]],aliases:[`terminal-square`]};at.node;var ot=t(at),P={gatewayUrl:`davecode.gatewayUrl`,token:`davecode.token`,theme:`davecode.theme`,dataMode:`davecode.dataMode`,sidebarCollapsed:`davecode.sidebarCollapsed`};function F(e){try{return window.localStorage.getItem(e)}catch{return null}}function I(e,t){try{t===``?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{}}function st(){let e=F(P.theme),t=F(P.dataMode);return{gatewayUrl:F(P.gatewayUrl)??``,token:F(P.token)??``,theme:e===`light`||e===`system`?e:`dark`,dataMode:t===`live`||t===`mock`?t:`auto`,sidebarCollapsed:F(P.sidebarCollapsed)===`1`}}var L=typeof window>`u`?ct():st(),R=new Set;function ct(){return{gatewayUrl:``,token:``,theme:`dark`,dataMode:`auto`,sidebarCollapsed:!1}}function z(){return L}function lt(e){L={...L,...e};for(let[t,n]of Object.entries(e)){let e=P[t];t===`sidebarCollapsed`?I(e,n?`1`:``):t===`theme`?I(e,String(n)):I(e,String(n??``))}for(let e of R)e()}function ut(e){return R.add(e),()=>R.delete(e)}function dt(){return(0,a.useSyncExternalStore)(ut,z,z)}function ft(){if(typeof window>`u`)return!1;let e=new URLSearchParams(window.location.search).get(`mock`),t=window.location.hash.split(`?`)[1]??``,n=new URLSearchParams(t).get(`mock`);return e===`1`||n===`1`}function pt(e){return e===`system`?window.matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`:e}function mt(e){let t=()=>{document.documentElement.dataset.theme=pt(e)};if(t(),e!==`system`)return()=>{};let n=window.matchMedia(`(prefers-color-scheme: light)`);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)}var ht=[`request.started`,`request.completed`,`request.failed`,`router.failover`,`account.updated`,`account.removed`,`quota.updated`,`task.updated`,`task.removed`,`runner.status`,`runner.log`,`goal.updated`,`goal.log`,`log`];function gt(e,t=Math.random){let n=Math.min(3e4,1e3*2**Math.max(0,e-1)),r=n*.2*(t()*2-1);return Math.round(n+r)}function _t(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.type==`string`)return t}catch{}return null}function vt(e,t){let n=null,r,i=0,a=!1,o,s=e=>t.onStatus?.({...e,attempt:i,lastEventAt:o}),c=e=>{let n=_t(e.data);n&&(o=Date.now(),t.onEvent(n))},l=()=>{if(!a){s({state:i===0?`connecting`:`reconnecting`}),n=new EventSource(e),n.onopen=()=>{i=0,o=Date.now(),s({state:`open`})},n.onmessage=c;for(let e of ht)n.addEventListener(e,c);n.onerror=()=>{if(n?.close(),n=null,a)return;i+=1;let e=gt(i);s({state:`reconnecting`,retryAt:Date.now()+e}),r=window.setTimeout(l,e)}}};return l(),()=>{a=!0,window.clearTimeout(r),n?.close(),n=null}}var B=class extends Error{status;code;cycle;dependents;constructor(e,t,n,r={}){super(n),this.name=`ApiError`,this.status=e,this.code=t,r.cycle&&(this.cycle=r.cycle),r.dependents&&(this.dependents=r.dependents)}get reachable(){return this.status>0&&!yt.has(this.code)}},yt=new Set([`network`,`bad_response`,`gateway_unreachable`]);function bt(e){return e instanceof B}function xt(e,t){return`${e.replace(/\/+$/,``)}${t}`}function St({baseUrl:e,token:t}){async function n(n,r,i){let a={Accept:`application/json`};t&&(a.Authorization=`Bearer ${t}`),i!==void 0&&(a[`Content-Type`]=`application/json`);let o;try{o=await fetch(xt(e,r),{method:n,headers:a,body:i===void 0?void 0:JSON.stringify(i)})}catch(e){throw new B(0,`network`,`Gateway unreachable: ${e.message}`)}if(o.status===204)return;let s=await o.text(),c;try{c=s?JSON.parse(s):void 0}catch{throw new B(o.ok?0:o.status,`bad_response`,`Unexpected non-JSON response from ${r}`)}if(!o.ok){let e=c?.error;throw!e&&o.status>=502&&o.status<=504?new B(o.status,`gateway_unreachable`,`Gateway unreachable (proxy answered ${o.status})`):new B(o.status,e?.code??`http_${o.status}`,e?.message??`${n} ${r} failed with ${o.status}`,{...e?.cycle&&{cycle:e.cycle},...e?.dependents&&{dependents:e.dependents}})}return c}let r=e=>n(`GET`,e);return{mode:`live`,health:()=>r(`/api/health`),listAccounts:async()=>(await r(`/api/accounts`)).accounts,createAccount:async e=>(await n(`POST`,`/api/accounts`,e)).account,updateAccount:async(e,t)=>(await n(`PATCH`,`/api/accounts/${encodeURIComponent(e)}`,t)).account,deleteAccount:e=>n(`DELETE`,`/api/accounts/${encodeURIComponent(e)}`),usage:async()=>(await r(`/api/usage`)).usage,budget:async()=>(await r(`/api/budget`)).budget,connection:async e=>(await r(`/api/accounts/${encodeURIComponent(e)}/connection`)).connection,connect:async e=>(await n(`POST`,`/api/accounts/${encodeURIComponent(e)}/connect`,{})).connect,timeseries:async(e=60,t=60)=>(await r(`/api/usage/timeseries?minutes=${e}&bucketSec=${t}`)).buckets,requests:async(e=100)=>(await r(`/api/requests?limit=${e}`)).requests,routes:()=>r(`/api/routes`),updateRoutes:e=>n(`PUT`,`/api/routes`,e),tasks:()=>r(`/api/tasks`),createTask:async e=>(await n(`POST`,`/api/tasks`,e)).task,updateTask:async(e,t)=>(await n(`PATCH`,`/api/tasks/${encodeURIComponent(e)}`,t)).task,deleteTask:e=>n(`DELETE`,`/api/tasks/${encodeURIComponent(e)}`),brain:()=>r(`/api/brain`),runner:async()=>(await r(`/api/runner`)).status,runnerAction:async(e,t)=>(await n(`POST`,`/api/runner/${e}`,e===`start`&&t?.taskId?{taskId:t.taskId}:void 0)).status,logs:async(e=200)=>(await r(`/api/logs?limit=${e}`)).events,goals:async()=>(await r(`/api/goals`)).goals,startGoal:async e=>(await n(`POST`,`/api/goals`,e)).goal,executeGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/execute`)).goal,goalArtifact:async(e,t)=>(await r(`/api/goals/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`)).artifact,cancelGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/cancel`)).goal,models:async()=>(await r(`/v1/models`)).data,subscribe:n=>vt(xt(e,`/api/events${t?`?token=${encodeURIComponent(t)}`:``}`),n)}}function Ct(e){return bt(e)?e.status===401?`Unauthorized: set the gateway token in Settings.`:e.message:e instanceof Error?e.message:String(e)}function wt(e){return e.type===`request.started`||e.type===`request.completed`||e.type===`request.failed`||e.type===`router.failover`}function Tt(e,t,n=``){return{requestId:e,model:n,startedTs:t,updatedTs:t,attempts:[],outcome:`pending`,failovers:0,exhausted:!1}}function Et(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&r.accountId===t&&r.outcome===`pending`)return n}return-1}var Dt=2e3;function Ot(e,t,n,r,i){for(let a=e.length-1;a>=0;a--){let o=e[a];if(!o||o.accountId!==t||i&&o.outcome!==i)continue;let s=o[r];if(s!==void 0&&Math.abs(s-n)<=Dt)return a}return-1}function kt(e){let t=e.attempts[e.attempts.length-1];return t?t.outcome===`success`?`success`:t.outcome===`pending`?`pending`:e.exhausted?`failed`:e.failovers>=e.attempts.length?`pending`:`failed`:`pending`}function At(e,t){let n=e??Tt(t.requestId,t.ts),r={...n,attempts:n.attempts.map(e=>({...e})),startedTs:Math.min(n.startedTs,t.ts),updatedTs:Math.max(n.updatedTs,t.ts)};switch(t.type){case`request.started`:r.model||=t.model,Et(r.attempts,t.accountId)===-1&&Ot(r.attempts,t.accountId,t.ts,`startedTs`)===-1&&r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`});break;case`request.completed`:{r.model||=t.model;let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`success`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts-t.latencyMs,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];n&&(n.outcome=`success`,n.endedTs=t.ts,n.latencyMs=t.latencyMs,n.promptTokens=t.promptTokens,n.completionTokens=t.completionTokens),r.startedTs=Math.min(r.startedTs,t.ts-t.latencyMs);break}case`request.failed`:{let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`failed`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];if(n){let e=n.outcome===`pending`;n.outcome=`failed`,n.endedTs=e?t.ts:n.endedTs??t.ts,n.latencyMs=n.latencyMs??t.ts-n.startedTs,n.errorKind=t.error.kind,n.errorStatus=t.error.status,n.errorMessage=t.error.message}break}case`router.failover`:{t.toAccountId===null&&(r.exhausted=!0);let e=!1;for(let n=r.attempts.length-1;n>=0;n--){let i=r.attempts[n];if(i&&i.accountId===t.fromAccountId){e=!0,i.failedOver||(i.failedOver=!0,r.failovers+=1),i.errorKind??=t.reason,i.outcome===`pending`&&(i.outcome=`failed`,i.endedTs=t.ts);break}}e||(r.failovers+=1);break}}return r.outcome=kt(r),r}function jt(e){let t=new Map;for(let n of e){let e=t.get(n.requestId);e?e.push(n):t.set(n.requestId,[n])}let n=[];for(let[e,r]of t){r.sort((e,t)=>e.ts-t.ts);let t=r[0];if(!t)continue;let i=r.map((e,t)=>({accountId:e.accountId,provider:e.provider,startedTs:e.ts-e.latencyMs,endedTs:e.ts,outcome:e.status===`success`?`success`:`failed`,latencyMs:e.latencyMs,promptTokens:e.promptTokens,completionTokens:e.completionTokens,errorKind:e.errorKind??(e.status===`rate_limited`?`rate_limit`:void 0),errorStatus:e.status===`rate_limited`?429:void 0,failedOver:t<r.length-1})),a=i[i.length-1];n.push({requestId:e,model:t.model,startedTs:i[0]?.startedTs??t.ts,updatedTs:a?.endedTs??t.ts,attempts:i,outcome:a?.outcome===`success`?`success`:`failed`,failovers:Math.max(0,i.length-1),exhausted:a?.outcome!==`success`})}return n.sort((e,t)=>t.startedTs-e.startedTs)}function Mt(e){let t=0,n=0;for(let r of e.attempts)t+=r.promptTokens??0,n+=r.completionTokens??0;return{prompt:t,completion:n}}function Nt(e){let t=e.attempts[e.attempts.length-1];if(t?.endedTs)return t.endedTs-e.startedTs}function Pt(e){if(e.errorStatus)return String(e.errorStatus);switch(e.errorKind){case`rate_limit`:return`429`;case`quota_exhausted`:return`quota`;case`unavailable`:return`503`;case`timeout`:return`timeout`;case`network`:return`network`;case`auth`:return`401`;case`context_length`:return`ctx`;case`bad_request`:return`400`;default:return`error`}}var Ft=600,It=400,Lt=3e3,Rt=4e3;function zt(e){return Math.floor(e/6e4)*6e4}function Bt(e){return JSON.stringify(e)}var Vt=class{flushMs;state={events:[],chains:[],logs:[],minutes:[],failoverTs:[]};chainIndex=new Map;seen=new Set;seenOrder=[];listeners=new Set;dirty=!1;flushTimer;pending=[];failovers=new Map;logSeq=0;constructor(e=200){this.flushMs=e}getState=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));ingest(e){let t=Bt(e);if(this.seen.has(t))return!1;if(this.seen.add(t),this.seenOrder.push(t),this.seenOrder.length>Rt){let e=this.seenOrder.shift();e&&this.seen.delete(e)}return this.pending.push(e),this.schedule(),!0}seedRecords(e){for(let t of jt(e))this.chainIndex.has(t.requestId)||this.chainIndex.set(t.requestId,t),t.attempts.slice(0,-1).forEach(e=>{this.failovers.set(`${t.requestId}:${e.accountId}`,e.endedTs??t.startedTs)});this.dirty=!0,this.schedule()}flush(){if(this.flushTimer!==void 0&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.pending.length===0&&!this.dirty)return;let e=this.pending;this.pending=[],this.dirty=!1;let t=this.state.events.concat(e),n=this.state.logs.slice(),r=new Map(this.state.minutes.map(e=>[e.ts,{...e}]));for(let t of e)if(wt(t)&&this.chainIndex.set(t.requestId,At(this.chainIndex.get(t.requestId),t)),t.type===`request.completed`){let e=zt(t.ts),n=r.get(e)??{ts:e,tokens:0,requests:0};n.tokens+=t.promptTokens+t.completionTokens,n.requests+=1,r.set(e,n)}else t.type===`router.failover`?this.failovers.set(`${t.requestId}:${t.fromAccountId}`,t.ts):t.type===`runner.log`?n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`runner`,taskId:t.taskId}):t.type===`log`&&n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`gateway`,scope:t.scope});let i=[...this.chainIndex.values()].sort((e,t)=>t.startedTs-e.startedTs);if(i.length>It){for(let e of i.slice(It))this.chainIndex.delete(e.requestId);i=i.slice(0,It)}n.sort((e,t)=>e.ts-t.ts);let a=Date.now()-36e5;for(let[e,t]of this.failovers)t<a&&this.failovers.delete(e);this.state={events:t.length>Ft?t.slice(-600):t,chains:i,logs:n.length>Lt?n.slice(-3e3):n,minutes:[...r.values()].sort((e,t)=>e.ts-t.ts).slice(-90),failoverTs:[...this.failovers.values()].sort((e,t)=>e-t)};for(let e of this.listeners)e()}clearLogs(){this.state={...this.state,logs:[]};for(let e of this.listeners)e()}dispose(){this.flushTimer!==void 0&&clearTimeout(this.flushTimer),this.flushTimer=void 0}schedule(){this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},this.flushMs))}},Ht=864e5,Ut=[`1m`,`5h`,`24h`],Wt={acc_claude_pro:{info:{plan:`Claude Pro`,price:{amount:20,currency:`USD`,period:`month`}},paidDaysAgo:21,renewsInDays:9},acc_anthropic_work:{info:{plan:`API — Build tier 2`,price:{amount:250,currency:`USD`,period:`month`},notes:`Prepaid credits, topped up monthly`},paidDaysAgo:12,renewsInDays:18},acc_openai_team:{info:{plan:`ChatGPT Team`,price:{amount:300,currency:`USD`,period:`year`}},paidDaysAgo:340,renewsInDays:2}},Gt=e=>new Date(e).toISOString().slice(0,10);function Kt(e,t){let n=Wt[e];if(n)return{...n.info,paidAt:Gt(t-n.paidDaysAgo*Ht),renewsAt:Gt(t+n.renewsInDays*Ht)}}function qt(e,t,n){let r=null,i;for(let e of Ut){let n=t.windows[e];if(n.tokenLimit===void 0&&n.requestLimit===void 0)continue;let a=Math.max(0,1-n.utilization);(r===null||a<r)&&(r=a,i=e)}let a={accountId:e.id,label:e.label,provider:e.provider,enabled:e.enabled,remaining:r,usage:t,available:e.enabled&&e.status===`active`&&(r??1)>0};if(i&&(a.tightestWindow=i),e.subscription){a.subscription=e.subscription;let t=e.subscription.renewsAt?Date.parse(e.subscription.renewsAt):NaN;Number.isNaN(t)||(a.renewsInDays=Math.ceil((t-n)/Ht))}return a.available||(a.unavailableReason=e.enabled?e.status===`cooldown`?`cooling down`:e.status===`error`?`credentials rejected (fix the account)`:`local quota limit reached`:`disabled`),a}function Jt(e,t){let n=e.filter(e=>e.enabled);if(n.length===0)return``;let r=[`ACCOUNT BUDGET (${`${new Date(t).toISOString().slice(0,16).replace(`T`,` `)} UTC`}; ${n.filter(e=>e.available).length} of ${n.length} accounts available).`,`The router already avoids exhausted accounts. When budget is scarce, keep prompts and outputs short and prefer fewer, larger steps.`];for(let e of n){let t=[];e.subscription?.plan&&t.push(e.subscription.plan);let n=e.subscription?.price;n&&t.push(`${n.amount} ${n.currency}/${n.period}`),e.renewsInDays!==void 0&&t.push(`renews in ${e.renewsInDays}d`);let i=`- ${e.label} [${e.provider}]${t.length?` (${t.join(`, `)})`:``}`,a=e.available?e.remaining===null?`no known limit`:`${Math.round(e.remaining*100)}% left (${e.tightestWindow} window)`:`unavailable: ${e.unavailableReason}`;r.push(`${i}: ${a}`)}return r.join(`
|
|
1
|
+
import{i as e,n as t,o as n,r,t as i}from"./cn-BwE4cei0.js";var a=n(e(),1),o=r(),s=a.createContext(void 0),c=e=>{let t=a.useContext(s);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},l=({client:e,children:t})=>(a.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,o.jsx)(s.Provider,{value:e,children:t})),u={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},d=new class{#e=u;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function f(e){setTimeout(e,0)}var p=typeof window>`u`||`Deno`in globalThis;function m(){}function h(e,t){return typeof e==`function`?e(t):e}function g(e){return typeof e==`number`&&e>=0&&e!==1/0}function _(e,t){return Math.max(e+(t||0)-Date.now(),0)}function v(e,t){return typeof e==`function`?e(t):e}function y(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==x(o,t.options))return!1}else if(!C(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function b(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(S(t.options.mutationKey)!==S(a))return!1}else if(!C(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function x(e,t){return(t?.queryKeyHashFn||S)(e)}function S(e){return JSON.stringify(e,(e,t)=>T(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function C(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!C(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!C(e[r],t[r]))return!1;return!0}return!1}var ee=Object.prototype.hasOwnProperty;function te(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ne(e)&&ne(t);if(!r&&!(T(e)&&T(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:ee.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=te(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function w(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function ne(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function T(e){if(!re(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!re(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function re(e){return Object.prototype.toString.call(e)===`[object Object]`}function ie(e){return new Promise(t=>{d.setTimeout(t,e)})}function E(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:te(e,t)}function ae(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function oe(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var D=Symbol();function se(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===D?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ce(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var ue=()=>p,de=()=>ue(),O=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},fe=new class extends O{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},pe=f;function me(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=pe,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var k=me(),he=new class extends O{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function ge(e){return Math.min(1e3*2**e,3e4)}function _e(e){return(e??`online`)!==`online`||he.isOnline()}var ve=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function ye(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(m);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new ve(t);g(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>fe.isFocused()&&(e.networkMode===`always`||he.isOnline())&&e.canRun(),p=()=>_e(e.networkMode)&&e.canRun(),h=e=>{c()||(r?.(),i=`resolved`,a(e))},g=e=>{c()||(r?.(),i=`rejected`,o(e))},_=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),v=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(h).catch(r=>{if(c())return;let i=e.retry??(de()?0:3),a=e.retryDelay??ge,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?g(r):(n++,e.onFail?.(n,r),ie(o).then(()=>f()?void 0:_(f)).then(()=>{t?g(r):v()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?v():_(p).then(v),s)}}var be=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),g(this.gcTime)&&(this.#e=d.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(de()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(d.clearTimeout(this.#e),this.#e=void 0)}};function xe(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{le(e,()=>t.signal,()=>n=!0)},u=se(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?oe:ae;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ce:Se,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:Se(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Se(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Ce(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var we=class extends be{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=De(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=De(this.options);e.data!==void 0&&(this.setState(Ee(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=E(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(m).catch(m):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>v(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===D||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>v(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!_(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=se(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?xe(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=ye({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ve&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ve){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Te(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ee(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),k.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Te(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_e(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ee(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function De(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Oe=class extends O{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ae(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return A(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return A(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof v(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!w(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&je(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||v(this.options.staleTime,this.#t)!==v(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||v(this.options.enabled,this.#t)!==v(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return w(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(m)),t}#h(e){return!de()&&v(this.options.enabled,this.#t)!==!1&&g(e)}#g(){this.#b();let e=v(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=_(this.#r.dataUpdatedAt,e)+1;this.#u=d.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return v(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=d.setInterval(()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(d.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(d.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Ae(e,t),o=i&&je(e,n,t,r);(a||o)&&(l={...l,...Te(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=E(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=E(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,y=m===`error`,b=_&&g,x=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:y,isInitialLoading:b,isLoading:b,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:y&&!x,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:y&&x,isStale:j(e,t),refetch:this.refetch,isEnabled:v(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),w(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size||this.options.throwOnError&&this.#r.error!==e.error)return!0;for(let t of n??this.#p)if(this.#r[t]!==e[t])return!0;return!1})();k.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function ke(e,t){return v(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||v(t.retryOnMount,e)!==!1)}function Ae(e,t){return ke(e,t)||e.state.data!==void 0&&A(e,t,t.refetchOnMount)}function A(e,t,n){if(v(t.enabled,e)!==!1&&v(t.staleTime,e)!==`static`){let r=v(n,e);return r===`always`||r!==!1&&j(e,t)}return!1}function je(e,t,n,r){return(e!==t||v(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&j(e,n)}function j(e,t){return v(t.enabled,e)!==!1&&e.isStaleByTime(v(t.staleTime,e))}var Me=class extends be{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Ne(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=ye({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),k.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Ne(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Pe=class extends O{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),w(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&S(t.mutationKey)!==S(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Ne();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){k.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Fe=a.createContext(!1),Ie=()=>a.useContext(Fe);Fe.Provider;function Le(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Re=a.createContext(Le()),ze=()=>a.useContext(Re),Be=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?ce(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ve=e=>{a.useEffect(()=>{e.clearReset()},[e])},He=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ce(n,[e.error,r])),Ue=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},We=(e,t)=>e?.suspense&&t.isPending,Ge=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ke(e,t,n){let r=Ie(),i=ze(),o=c(n),s=o.defaultQueryOptions(e),l=o.getQueryCache().get(s.queryHash),u=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:u?`optimistic`:void 0,Ue(s),Be(s,i,l),Ve(i);let[d]=a.useState(()=>new t(o,s)),f=d.getOptimisticResult(s),p=!r&&u;if(a.useSyncExternalStore(a.useCallback(e=>{let t=p?d.subscribe(k.batchCalls(e)):m;return d.updateResult(),t},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),a.useEffect(()=>{d.setOptions(s)},[s,d]),We(s,f))throw Ge(s,d,i);if(He({result:f,errorResetBoundary:i,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw f.error;return s.notifyOnChangeProps?f:d.trackResult(f)}function M(e,t){return Ke(e,Oe,t)}function N(e,t){let n=c(t),[r]=a.useState(()=>new Pe(n,e));a.useEffect(()=>{r.setOptions(e)},[r,e]);let i=a.useSyncExternalStore(a.useCallback(e=>r.subscribe(k.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=a.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(m)},[r]);if(i.error&&ce(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}var qe={name:`asterisk`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m18.065 8.496-12.125 7`,key:`1h26g9`}],[`path`,{d:`m5.94 8.504 12.125 7`,key:`k77sdm`}]]};qe.node;var Je=t(qe),Ye={name:`globe`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20`,key:`13o1zl`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}]]};Ye.node;var Xe=t(Ye),Ze={name:`hexagon`,size:24,node:[[`path`,{d:`M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z`,key:`yt0hxn`}]]};Ze.node;var Qe=t(Ze),$e={name:`server`,size:24,node:[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]};$e.node;var et=t($e),tt={name:`sparkle`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}]]};tt.node;var nt=t(tt),rt={name:`sparkles`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]],aliases:[`stars`]};rt.node;var it=t(rt),at={name:`square-terminal`,size:24,node:[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]],aliases:[`terminal-square`]};at.node;var ot=t(at),P={gatewayUrl:`davecode.gatewayUrl`,token:`davecode.token`,theme:`davecode.theme`,dataMode:`davecode.dataMode`,sidebarCollapsed:`davecode.sidebarCollapsed`};function F(e){try{return window.localStorage.getItem(e)}catch{return null}}function I(e,t){try{t===``?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{}}function st(){let e=F(P.theme),t=F(P.dataMode);return{gatewayUrl:F(P.gatewayUrl)??``,token:F(P.token)??``,theme:e===`light`||e===`system`?e:`dark`,dataMode:t===`live`||t===`mock`?t:`auto`,sidebarCollapsed:F(P.sidebarCollapsed)===`1`}}var L=typeof window>`u`?ct():st(),R=new Set;function ct(){return{gatewayUrl:``,token:``,theme:`dark`,dataMode:`auto`,sidebarCollapsed:!1}}function z(){return L}function lt(e){L={...L,...e};for(let[t,n]of Object.entries(e)){let e=P[t];t===`sidebarCollapsed`?I(e,n?`1`:``):t===`theme`?I(e,String(n)):I(e,String(n??``))}for(let e of R)e()}function ut(e){return R.add(e),()=>R.delete(e)}function dt(){return(0,a.useSyncExternalStore)(ut,z,z)}function ft(){if(typeof window>`u`)return!1;let e=new URLSearchParams(window.location.search).get(`mock`),t=window.location.hash.split(`?`)[1]??``,n=new URLSearchParams(t).get(`mock`);return e===`1`||n===`1`}function pt(e){return e===`system`?window.matchMedia(`(prefers-color-scheme: light)`).matches?`light`:`dark`:e}function mt(e){let t=()=>{document.documentElement.dataset.theme=pt(e)};if(t(),e!==`system`)return()=>{};let n=window.matchMedia(`(prefers-color-scheme: light)`);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)}var ht=[`request.started`,`request.completed`,`request.failed`,`router.failover`,`account.updated`,`account.removed`,`quota.updated`,`task.updated`,`task.removed`,`runner.status`,`runner.log`,`goal.updated`,`goal.log`,`log`];function gt(e,t=Math.random){let n=Math.min(3e4,1e3*2**Math.max(0,e-1)),r=n*.2*(t()*2-1);return Math.round(n+r)}function _t(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.type==`string`)return t}catch{}return null}function vt(e,t){let n=null,r,i=0,a=!1,o,s=e=>t.onStatus?.({...e,attempt:i,lastEventAt:o}),c=e=>{let n=_t(e.data);n&&(o=Date.now(),t.onEvent(n))},l=()=>{if(!a){s({state:i===0?`connecting`:`reconnecting`}),n=new EventSource(e),n.onopen=()=>{i=0,o=Date.now(),s({state:`open`})},n.onmessage=c;for(let e of ht)n.addEventListener(e,c);n.onerror=()=>{if(n?.close(),n=null,a)return;i+=1;let e=gt(i);s({state:`reconnecting`,retryAt:Date.now()+e}),r=window.setTimeout(l,e)}}};return l(),()=>{a=!0,window.clearTimeout(r),n?.close(),n=null}}var B=class extends Error{status;code;cycle;dependents;constructor(e,t,n,r={}){super(n),this.name=`ApiError`,this.status=e,this.code=t,r.cycle&&(this.cycle=r.cycle),r.dependents&&(this.dependents=r.dependents)}get reachable(){return this.status>0&&!yt.has(this.code)}},yt=new Set([`network`,`bad_response`,`gateway_unreachable`]);function bt(e){return e instanceof B}function xt(e,t){return`${e.replace(/\/+$/,``)}${t}`}function St({baseUrl:e,token:t}){async function n(n,r,i){let a={Accept:`application/json`};t&&(a.Authorization=`Bearer ${t}`),(i!==void 0||n!==`GET`)&&(a[`Content-Type`]=`application/json`);let o;try{o=await fetch(xt(e,r),{method:n,headers:a,body:i===void 0?void 0:JSON.stringify(i)})}catch(e){throw new B(0,`network`,`Gateway unreachable: ${e.message}`)}if(o.status===204)return;let s=await o.text(),c;try{c=s?JSON.parse(s):void 0}catch{throw new B(o.ok?0:o.status,`bad_response`,`Unexpected non-JSON response from ${r}`)}if(!o.ok){let e=c?.error;throw!e&&o.status>=502&&o.status<=504?new B(o.status,`gateway_unreachable`,`Gateway unreachable (proxy answered ${o.status})`):new B(o.status,e?.code??`http_${o.status}`,e?.message??`${n} ${r} failed with ${o.status}`,{...e?.cycle&&{cycle:e.cycle},...e?.dependents&&{dependents:e.dependents}})}return c}let r=e=>n(`GET`,e);return{mode:`live`,health:()=>r(`/api/health`),listAccounts:async()=>(await r(`/api/accounts`)).accounts,createAccount:async e=>(await n(`POST`,`/api/accounts`,e)).account,updateAccount:async(e,t)=>(await n(`PATCH`,`/api/accounts/${encodeURIComponent(e)}`,t)).account,deleteAccount:e=>n(`DELETE`,`/api/accounts/${encodeURIComponent(e)}`),usage:async()=>(await r(`/api/usage`)).usage,budget:async()=>(await r(`/api/budget`)).budget,connection:async e=>(await r(`/api/accounts/${encodeURIComponent(e)}/connection`)).connection,connect:async e=>(await n(`POST`,`/api/accounts/${encodeURIComponent(e)}/connect`,{})).connect,timeseries:async(e=60,t=60)=>(await r(`/api/usage/timeseries?minutes=${e}&bucketSec=${t}`)).buckets,requests:async(e=100)=>(await r(`/api/requests?limit=${e}`)).requests,routes:()=>r(`/api/routes`),updateRoutes:e=>n(`PUT`,`/api/routes`,e),tasks:()=>r(`/api/tasks`),createTask:async e=>(await n(`POST`,`/api/tasks`,e)).task,updateTask:async(e,t)=>(await n(`PATCH`,`/api/tasks/${encodeURIComponent(e)}`,t)).task,deleteTask:e=>n(`DELETE`,`/api/tasks/${encodeURIComponent(e)}`),brain:()=>r(`/api/brain`),runner:async()=>(await r(`/api/runner`)).status,runnerAction:async(e,t)=>(await n(`POST`,`/api/runner/${e}`,e===`start`&&t?.taskId?{taskId:t.taskId}:void 0)).status,logs:async(e=200)=>(await r(`/api/logs?limit=${e}`)).events,goals:async()=>(await r(`/api/goals`)).goals,startGoal:async e=>(await n(`POST`,`/api/goals`,e)).goal,executeGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/execute`)).goal,goalArtifact:async(e,t)=>(await r(`/api/goals/${encodeURIComponent(e)}/artifacts/${encodeURIComponent(t)}`)).artifact,cancelGoal:async e=>(await n(`POST`,`/api/goals/${encodeURIComponent(e)}/cancel`)).goal,models:async()=>(await r(`/v1/models`)).data,subscribe:n=>vt(xt(e,`/api/events${t?`?token=${encodeURIComponent(t)}`:``}`),n)}}function Ct(e){return bt(e)?e.status===401?`Unauthorized: set the gateway token in Settings.`:e.message:e instanceof Error?e.message:String(e)}function wt(e){return e.type===`request.started`||e.type===`request.completed`||e.type===`request.failed`||e.type===`router.failover`}function Tt(e,t,n=``){return{requestId:e,model:n,startedTs:t,updatedTs:t,attempts:[],outcome:`pending`,failovers:0,exhausted:!1}}function Et(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&r.accountId===t&&r.outcome===`pending`)return n}return-1}var Dt=2e3;function Ot(e,t,n,r,i){for(let a=e.length-1;a>=0;a--){let o=e[a];if(!o||o.accountId!==t||i&&o.outcome!==i)continue;let s=o[r];if(s!==void 0&&Math.abs(s-n)<=Dt)return a}return-1}function kt(e){let t=e.attempts[e.attempts.length-1];return t?t.outcome===`success`?`success`:t.outcome===`pending`?`pending`:e.exhausted?`failed`:e.failovers>=e.attempts.length?`pending`:`failed`:`pending`}function At(e,t){let n=e??Tt(t.requestId,t.ts),r={...n,attempts:n.attempts.map(e=>({...e})),startedTs:Math.min(n.startedTs,t.ts),updatedTs:Math.max(n.updatedTs,t.ts)};switch(t.type){case`request.started`:r.model||=t.model,Et(r.attempts,t.accountId)===-1&&Ot(r.attempts,t.accountId,t.ts,`startedTs`)===-1&&r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`});break;case`request.completed`:{r.model||=t.model;let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`success`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts-t.latencyMs,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];n&&(n.outcome=`success`,n.endedTs=t.ts,n.latencyMs=t.latencyMs,n.promptTokens=t.promptTokens,n.completionTokens=t.completionTokens),r.startedTs=Math.min(r.startedTs,t.ts-t.latencyMs);break}case`request.failed`:{let e=Et(r.attempts,t.accountId);e===-1&&(e=Ot(r.attempts,t.accountId,t.ts,`endedTs`,`failed`)),e===-1&&(r.attempts.push({accountId:t.accountId,provider:t.provider,startedTs:t.ts,outcome:`pending`}),e=r.attempts.length-1);let n=r.attempts[e];if(n){let e=n.outcome===`pending`;n.outcome=`failed`,n.endedTs=e?t.ts:n.endedTs??t.ts,n.latencyMs=n.latencyMs??t.ts-n.startedTs,n.errorKind=t.error.kind,n.errorStatus=t.error.status,n.errorMessage=t.error.message}break}case`router.failover`:{t.toAccountId===null&&(r.exhausted=!0);let e=!1;for(let n=r.attempts.length-1;n>=0;n--){let i=r.attempts[n];if(i&&i.accountId===t.fromAccountId){e=!0,i.failedOver||(i.failedOver=!0,r.failovers+=1),i.errorKind??=t.reason,i.outcome===`pending`&&(i.outcome=`failed`,i.endedTs=t.ts);break}}e||(r.failovers+=1);break}}return r.outcome=kt(r),r}function jt(e){let t=new Map;for(let n of e){let e=t.get(n.requestId);e?e.push(n):t.set(n.requestId,[n])}let n=[];for(let[e,r]of t){r.sort((e,t)=>e.ts-t.ts);let t=r[0];if(!t)continue;let i=r.map((e,t)=>({accountId:e.accountId,provider:e.provider,startedTs:e.ts-e.latencyMs,endedTs:e.ts,outcome:e.status===`success`?`success`:`failed`,latencyMs:e.latencyMs,promptTokens:e.promptTokens,completionTokens:e.completionTokens,errorKind:e.errorKind??(e.status===`rate_limited`?`rate_limit`:void 0),errorStatus:e.status===`rate_limited`?429:void 0,failedOver:t<r.length-1})),a=i[i.length-1];n.push({requestId:e,model:t.model,startedTs:i[0]?.startedTs??t.ts,updatedTs:a?.endedTs??t.ts,attempts:i,outcome:a?.outcome===`success`?`success`:`failed`,failovers:Math.max(0,i.length-1),exhausted:a?.outcome!==`success`})}return n.sort((e,t)=>t.startedTs-e.startedTs)}function Mt(e){let t=0,n=0;for(let r of e.attempts)t+=r.promptTokens??0,n+=r.completionTokens??0;return{prompt:t,completion:n}}function Nt(e){let t=e.attempts[e.attempts.length-1];if(t?.endedTs)return t.endedTs-e.startedTs}function Pt(e){if(e.errorStatus)return String(e.errorStatus);switch(e.errorKind){case`rate_limit`:return`429`;case`quota_exhausted`:return`quota`;case`unavailable`:return`503`;case`timeout`:return`timeout`;case`network`:return`network`;case`auth`:return`401`;case`context_length`:return`ctx`;case`bad_request`:return`400`;default:return`error`}}var Ft=600,It=400,Lt=3e3,Rt=4e3;function zt(e){return Math.floor(e/6e4)*6e4}function Bt(e){return JSON.stringify(e)}var Vt=class{flushMs;state={events:[],chains:[],logs:[],minutes:[],failoverTs:[]};chainIndex=new Map;seen=new Set;seenOrder=[];listeners=new Set;dirty=!1;flushTimer;pending=[];failovers=new Map;logSeq=0;constructor(e=200){this.flushMs=e}getState=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));ingest(e){let t=Bt(e);if(this.seen.has(t))return!1;if(this.seen.add(t),this.seenOrder.push(t),this.seenOrder.length>Rt){let e=this.seenOrder.shift();e&&this.seen.delete(e)}return this.pending.push(e),this.schedule(),!0}seedRecords(e){for(let t of jt(e))this.chainIndex.has(t.requestId)||this.chainIndex.set(t.requestId,t),t.attempts.slice(0,-1).forEach(e=>{this.failovers.set(`${t.requestId}:${e.accountId}`,e.endedTs??t.startedTs)});this.dirty=!0,this.schedule()}flush(){if(this.flushTimer!==void 0&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.pending.length===0&&!this.dirty)return;let e=this.pending;this.pending=[],this.dirty=!1;let t=this.state.events.concat(e),n=this.state.logs.slice(),r=new Map(this.state.minutes.map(e=>[e.ts,{...e}]));for(let t of e)if(wt(t)&&this.chainIndex.set(t.requestId,At(this.chainIndex.get(t.requestId),t)),t.type===`request.completed`){let e=zt(t.ts),n=r.get(e)??{ts:e,tokens:0,requests:0};n.tokens+=t.promptTokens+t.completionTokens,n.requests+=1,r.set(e,n)}else t.type===`router.failover`?this.failovers.set(`${t.requestId}:${t.fromAccountId}`,t.ts):t.type===`runner.log`?n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`runner`,taskId:t.taskId}):t.type===`log`&&n.push({key:`l${this.logSeq++}`,ts:t.ts,level:t.level,message:t.message,source:`gateway`,scope:t.scope});let i=[...this.chainIndex.values()].sort((e,t)=>t.startedTs-e.startedTs);if(i.length>It){for(let e of i.slice(It))this.chainIndex.delete(e.requestId);i=i.slice(0,It)}n.sort((e,t)=>e.ts-t.ts);let a=Date.now()-36e5;for(let[e,t]of this.failovers)t<a&&this.failovers.delete(e);this.state={events:t.length>Ft?t.slice(-600):t,chains:i,logs:n.length>Lt?n.slice(-3e3):n,minutes:[...r.values()].sort((e,t)=>e.ts-t.ts).slice(-90),failoverTs:[...this.failovers.values()].sort((e,t)=>e-t)};for(let e of this.listeners)e()}clearLogs(){this.state={...this.state,logs:[]};for(let e of this.listeners)e()}dispose(){this.flushTimer!==void 0&&clearTimeout(this.flushTimer),this.flushTimer=void 0}schedule(){this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},this.flushMs))}},Ht=864e5,Ut=[`1m`,`5h`,`24h`],Wt={acc_claude_pro:{info:{plan:`Claude Pro`,price:{amount:20,currency:`USD`,period:`month`}},paidDaysAgo:21,renewsInDays:9},acc_anthropic_work:{info:{plan:`API — Build tier 2`,price:{amount:250,currency:`USD`,period:`month`},notes:`Prepaid credits, topped up monthly`},paidDaysAgo:12,renewsInDays:18},acc_openai_team:{info:{plan:`ChatGPT Team`,price:{amount:300,currency:`USD`,period:`year`}},paidDaysAgo:340,renewsInDays:2}},Gt=e=>new Date(e).toISOString().slice(0,10);function Kt(e,t){let n=Wt[e];if(n)return{...n.info,paidAt:Gt(t-n.paidDaysAgo*Ht),renewsAt:Gt(t+n.renewsInDays*Ht)}}function qt(e,t,n){let r=null,i;for(let e of Ut){let n=t.windows[e];if(n.tokenLimit===void 0&&n.requestLimit===void 0)continue;let a=Math.max(0,1-n.utilization);(r===null||a<r)&&(r=a,i=e)}let a={accountId:e.id,label:e.label,provider:e.provider,enabled:e.enabled,remaining:r,usage:t,available:e.enabled&&e.status===`active`&&(r??1)>0};if(i&&(a.tightestWindow=i),e.subscription){a.subscription=e.subscription;let t=e.subscription.renewsAt?Date.parse(e.subscription.renewsAt):NaN;Number.isNaN(t)||(a.renewsInDays=Math.ceil((t-n)/Ht))}return a.available||(a.unavailableReason=e.enabled?e.status===`cooldown`?`cooling down`:e.status===`error`?`credentials rejected (fix the account)`:`local quota limit reached`:`disabled`),a}function Jt(e,t){let n=e.filter(e=>e.enabled);if(n.length===0)return``;let r=[`ACCOUNT BUDGET (${`${new Date(t).toISOString().slice(0,16).replace(`T`,` `)} UTC`}; ${n.filter(e=>e.available).length} of ${n.length} accounts available).`,`The router already avoids exhausted accounts. When budget is scarce, keep prompts and outputs short and prefer fewer, larger steps.`];for(let e of n){let t=[];e.subscription?.plan&&t.push(e.subscription.plan);let n=e.subscription?.price;n&&t.push(`${n.amount} ${n.currency}/${n.period}`),e.renewsInDays!==void 0&&t.push(`renews in ${e.renewsInDays}d`);let i=`- ${e.label} [${e.provider}]${t.length?` (${t.join(`, `)})`:``}`,a=e.available?e.remaining===null?`no known limit`:`${Math.round(e.remaining*100)}% left (${e.tightestWindow} window)`:`unavailable: ${e.unavailableReason}`;r.push(`${i}: ${a}`)}return r.join(`
|
|
2
2
|
`)}function Yt(e,t,n){let r=e.map(e=>qt(e,t(e),n));return{generatedAt:new Date(n).toISOString(),accounts:r,context:Jt(r,n)}}var Xt={anthropic:{kind:`anthropic`,label:`Anthropic API`,icon:Je,auth:`api-key`,blurb:`Claude models through the Messages API with an API key.`,secretLabel:`API key`,secretPlaceholder:`sk-ant-…`},openai:{kind:`openai`,label:`OpenAI API`,icon:Qe,auth:`api-key`,blurb:`GPT models with an OpenAI API key.`,secretLabel:`API key`,secretPlaceholder:`sk-…`},gemini:{kind:`gemini`,label:`Gemini API`,icon:nt,auth:`api-key`,blurb:`Google Gemini through AI Studio or Vertex with an API key.`,secretLabel:`API key`,secretPlaceholder:`AIza…`},"openai-compatible":{kind:`openai-compatible`,label:`OpenAI-compatible`,icon:et,auth:`optional-key`,blurb:`OpenRouter and other providers using the OpenAI-compatible API.`,secretLabel:`API key (optional)`,secretPlaceholder:`Leave empty for local servers`},"claude-cli":{kind:`claude-cli`,label:`Claude Code CLI`,icon:ot,auth:`cli`,blurb:`Your Claude login, isolated in its own CLAUDE_CONFIG_DIR sandbox.`,subscription:!0},"codex-cli":{kind:`codex-cli`,label:`Codex CLI`,icon:ot,auth:`cli`,blurb:`Your ChatGPT/OpenAI login, isolated in its own CODEX_HOME sandbox.`,subscription:!0},"gemini-cli":{kind:`gemini-cli`,label:`Gemini CLI`,icon:it,auth:`cli`,blurb:`Your Google login (Login with Google), isolated in its own GEMINI_CLI_HOME sandbox.`,subscription:!0},"antigravity-cli":{kind:`antigravity-cli`,label:`Antigravity`,icon:it,auth:`cli`,blurb:`Your Google sign-in in the Antigravity CLI (agy), shared by this machine.`,subscription:!0},"gemini-web":{kind:`gemini-web`,label:`Gemini web`,icon:Xe,auth:`browser`,blurb:`Drives a Gemini web session through a dedicated Chromium profile.`,experimental:!0,subscription:!0}},Zt=[`anthropic`,`openai`,`gemini`,`openai-compatible`,`claude-cli`,`codex-cli`,`antigravity-cli`,`gemini-cli`,`gemini-web`];function Qt(e){return Xt[e]??{...Xt[`openai-compatible`],kind:e,label:e}}var $t=new Set([`acc_claude_pro`]),en=6e3;function tn(e){let{auth:t}=Qt(e.provider);return t===`cli`?`cli-login`:t===`browser`?`browser`:`api-key`}function nn(e,t,n){let r=tn(e),i={accountId:e.id,provider:e.provider,method:r,checkedAt:new Date(n).toISOString()};return r===`browser`?{...i,status:`unknown`,detail:`Signed in through its own Chromium profile; checking would mean opening the browser.`}:r===`api-key`?e.hasSecret===!1&&e.provider!==`openai-compatible`?{...i,status:`not_connected`,detail:`No API key stored. Add one to connect this account.`}:{...i,status:`connected`,detail:`API key stored in the encrypted keyring.`}:{...i,loginCommand:`davecode accounts login ${e.id}`,...t?{status:`connected`,detail:`The vendor CLI reports a login for this account.`}:{status:`not_connected`,detail:`No login in this account’s sandbox yet.`}}}var V=e=>e,rn=[{account:{id:`acc_claude_pro`,provider:`claude-cli`,label:`Claude Pro — personal`,enabled:!0,priority:10,weight:3,limits:V({tpm:6e4,tokens5h:3e6,requests5h:900,tokensDaily:9e6}),config:{binary:`claude`,sandbox:`~/.davecode/sandboxes/acc_claude_pro`}},curve5h:{from:.79,to:.935},curve24h:{from:.54,to:.63},latency:[900,11],failRate:.02},{account:{id:`acc_anthropic_work`,provider:`anthropic`,label:`Anthropic API — work`,enabled:!0,priority:20,weight:2,limits:V({tpm:12e4,rpm:50,tokens5h:6e6,tokensDaily:2e7}),config:{models:[`claude-sonnet-5-5`,`claude-opus-5-5`,`claude-haiku-5`]}},curve5h:{from:.48,to:.64},curve24h:{from:.36,to:.44},latency:[650,9],failRate:.015},{account:{id:`acc_openai_team`,provider:`openai`,label:`OpenAI — team`,enabled:!0,priority:30,weight:1,limits:V({tpm:9e4,rpm:60,tokens5h:5e6,tokensDaily:15e6}),config:{models:[`gpt-5.5`,`gpt-5.5-mini`,`gpt-5.5-pro`]}},curve5h:{from:.27,to:.36},curve24h:{from:.2,to:.26},latency:[520,8],failRate:.012},{account:{id:`acc_openrouter`,provider:`openai-compatible`,label:`OpenRouter`,enabled:!0,priority:50,weight:1,limits:{},config:{baseUrl:`https://openrouter.ai/api/v1`,models:[`openrouter/auto`]}},curve5h:{from:0,to:0},curve24h:{from:0,to:0},latency:[380,22],failRate:.01},{account:{id:`acc_gemini_web`,provider:`gemini-web`,label:`Gemini web — experimental`,enabled:!1,status:`disabled`,priority:90,weight:1,limits:V({requestsDaily:100}),config:{profile:`~/.davecode/profiles/acc_gemini_web`}},curve5h:{from:0,to:0},curve24h:{from:0,to:0},latency:[2400,14],failRate:.05}],an=[{name:`auto`,description:`Subscription first, then API keys, then the local model.`,targets:[{provider:`claude-cli`,model:`claude-sonnet-5-5`,accountId:`acc_claude_pro`},{provider:`anthropic`,model:`claude-sonnet-5-5`},{provider:`openai`,model:`gpt-5.5`},{provider:`openai-compatible`,model:`openrouter/auto`}]},{name:`fast`,description:`Low-latency completions for autocomplete and quick edits.`,targets:[{provider:`openai`,model:`gpt-5.5-mini`},{provider:`anthropic`,model:`claude-haiku-5`},{provider:`openai-compatible`,model:`llama4:scout`}]},{name:`reasoning`,description:`Planning and hard debugging. Expensive; used by the runner for repairs.`,targets:[{provider:`anthropic`,model:`claude-opus-5-5`},{provider:`openai`,model:`gpt-5.5-pro`}]},{name:`local`,description:`Never leaves the machine.`,targets:[{provider:`openai-compatible`,model:`openrouter/auto`,accountId:`acc_openrouter`}]}],on=[[`auto`,.62],[`fast`,.24],[`reasoning`,.06],[`local`,.08]],H=(e,t)=>new Date(t-e*6e4).toISOString();function sn(e){return[{id:`foundation`,title:`Monorepo foundation, shared contracts and OSS docs`,status:`SUCCESS`,dependsOn:[],priority:100,attempts:1,branch:`davecode/task-foundation`,acceptance:[`pnpm lint, typecheck, test and build pass`,`Contracts documented in docs/API.md`],updatedAt:H(1560,e)},{id:`p1-storage`,title:`SQLite storage (WAL), migrations and repositories`,description:`accounts, secrets, sessions, token_usage and audit_logs tables with typed repositories.`,status:`SUCCESS`,dependsOn:[`foundation`],priority:90,attempts:1,branch:`davecode/task-p1-storage`,acceptance:[`Migrations are idempotent`,`WAL mode enabled`,`Repositories covered by tests`],updatedAt:H(1200,e)},{id:`p1-config`,title:`Layered config loader (defaults, global, project, env)`,status:`SUCCESS`,dependsOn:[`foundation`],priority:90,attempts:2,branch:`davecode/task-p1-config`,acceptance:[`Later layers win`,`Invalid config reports the zod path`],notes:`First attempt merged env vars before the project file; fixed in repair cycle 1.`,updatedAt:H(1140,e)},{id:`p1-identity`,title:`Encrypted keyring, sandbox manager and Chromium profile manager`,status:`SUCCESS`,dependsOn:[`p1-storage`],priority:90,attempts:1,branch:`davecode/task-p1-identity`,acceptance:[`Secrets are AES-256-GCM encrypted at rest`,`master.key created with 0600 permissions`,`Each CLI account gets its own CLAUDE_CONFIG_DIR / CODEX_HOME`],updatedAt:H(840,e)},{id:`p2-quota`,title:`Sliding-window quota engine (1m, 5h, 24h) and SQLite-backed tracker`,status:`SUCCESS`,dependsOn:[`p1-storage`],priority:80,attempts:1,branch:`davecode/task-p2-quota`,acceptance:[`Windows slide, never reset on the hour`,`Utilization = max(tokens, requests) ratio`],updatedAt:H(540,e)},{id:`p2-providers`,title:`Provider adapters: anthropic, openai, gemini, openai-compatible, claude-cli`,status:`SUCCESS`,dependsOn:[`p1-identity`],priority:80,attempts:2,branch:`davecode/task-p2-providers`,acceptance:[`Upstream errors mapped to ProviderError kinds`,`Streaming and non-streaming paths`],updatedAt:H(360,e)},{id:`p2-codex-cli`,title:`Codex CLI adapter isolated via CODEX_HOME`,status:`FAILED`,dependsOn:[`p2-providers`],priority:70,attempts:3,branch:`davecode/task-p2-codex-cli`,acceptance:[`codex exec runs inside the account sandbox`,`Usage parsed from the JSON event stream`],notes:"Failed after 3 repair cycles: `codex exec --json` exits 2 under a fresh CODEX_HOME on Windows (no login prompt in non-TTY mode). Needs a human decision on the auth flow.",updatedAt:H(240,e)},{id:`p3-brain`,title:`Global and project brain managers, task graph DAG resolver with cycle detection`,status:`SUCCESS`,dependsOn:[`foundation`],priority:70,attempts:1,branch:`davecode/task-p3-brain`,acceptance:[`Unknown dependencies rejected`,`Cycles rejected with the offending path`],updatedAt:H(480,e)},{id:`p2-router`,title:`Router with balancing, backpressure, cooldowns and hot failover`,description:`Score candidates by priority, then weight × headroom. Smooth backpressure above 85 %, shift above 90 % of the 5 h quota, fail over before the first byte.`,status:`IN_PROGRESS`,dependsOn:[`p2-quota`,`p2-providers`,`p1-config`],priority:80,attempts:2,branch:`davecode/task-p2-router`,acceptance:[`Never routes to an account in cooldown`,`Weight is smoothly reduced above backpressureThreshold`,`Failover honours Retry-After and routing.maxFailovers`,`Emits router.failover for every hop`],notes:`Repair cycle 1: two vitest assertions failed on Retry-After parsing (HTTP-date form).`,updatedAt:H(3,e)},{id:`p1-gateway`,title:`Fastify gateway: /v1 OpenAI-compatible proxy, /api REST, SSE events`,status:`PENDING`,dependsOn:[`p2-router`],priority:75,acceptance:[`Implements docs/API.md exactly`,`SSE heartbeat every 15 s`,`Serves packages/ui/dist`]},{id:`p4-runner`,title:`Autonomous runner: state machine, validator, repair cycles, git flow`,status:`PENDING`,dependsOn:[`p2-router`,`p3-brain`],priority:60,acceptance:[`At most 3 repair cycles`,`Only merges after lint, typecheck and tests pass`]},{id:`p5-cli`,title:`CLI commands and Ink TUI`,status:`PENDING`,dependsOn:[`p1-gateway`,`p4-runner`],priority:40,acceptance:[`davecode start | status | add-account | run`,`TUI mirrors the dashboard overview`]},{id:`release-0.1.0`,title:`Integration tests, docs polish and v0.1.0 release`,status:`PENDING`,dependsOn:[`p5-cli`,`p2-codex-cli`],priority:10,acceptance:[`End-to-end failover test against two fake upstreams`,`npm publish dry-run passes`]}]}function cn(e,t){let n=e.filter(e=>e.status===`SUCCESS`),r=e.find(e=>e.status===`IN_PROGRESS`),i=e.filter(e=>e.status===`FAILED`);return`# DaveCode: project state
|
|
3
3
|
|
|
4
4
|
_Last updated: ${new Date(t).toISOString().slice(0,10)} by the autonomous runner_
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"./cn-BwE4cei0.js";import{M as r,W as i}from"./index-
|
|
1
|
+
import{n as e,r as t,t as n}from"./cn-BwE4cei0.js";import{M as r,W as i}from"./index-CpztPbom.js";var a={name:`octagon-alert`,size:24,node:[[`path`,{d:`M12 16h.01`,key:`1drbdi`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z`,key:`1fd625`}]],aliases:[`alert-octagon`]};a.node;var o=e(a),s=t(),c={info:{box:`border-info/25 bg-info-soft [&_svg]:text-info`,icon:i},warn:{box:`border-warn/30 bg-warn-soft [&_svg]:text-warn`,icon:r},err:{box:`border-err/30 bg-err-soft [&_svg]:text-err`,icon:o}};function l({tone:e=`info`,title:t,children:r,action:i,className:a}){let{box:o,icon:l}=c[e];return(0,s.jsxs)(`div`,{role:e===`info`?`note`:`alert`,className:n(`flex gap-2.5 rounded-md border px-3 py-2.5 text-[12px] leading-5`,o,a),children:[(0,s.jsx)(l,{"aria-hidden":!0,className:`mt-0.5 size-3.5 shrink-0`,strokeWidth:1.75}),(0,s.jsxs)(`div`,{className:`min-w-0 flex-1 text-fg-2`,children:[t&&(0,s.jsx)(`p`,{className:`font-medium text-fg`,children:t}),r]}),i&&(0,s.jsx)(`div`,{className:`shrink-0 self-center`,children:i})]})}export{l as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t,o as n,r,t as i}from"./cn-BwE4cei0.js";import{C as a,M as o,T as s,V as c,d as l,ft as u,g as d,i as f,pt as p,r as m,t as h,w as g}from"./Badge-Z4RBdO9j.js";import{n as _,t as v}from"./Switch-DPYlLseH.js";import{n as y,t as b}from"./Markdown-DCZ4Awcc.js";import{t as x}from"./Callout-w8BTYh4k.js";import{B as S,C,F as w,N as T,d as E,i as D,m as O,n as k,p as A,r as j,s as M,u as N,w as P,y as F}from"./index-BDBa5cb0.js";import{i as I,n as L,t as R}from"./Field-Cmpgg_1z.js";var z={name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]};z.node;var B=t(z),V={name:`shield-check`,size:24,node:[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]};V.node;var H=t(V),U=n(e(),1),W=r(),G={planning:`info`,running:`info`,reviewing:`info`,planned:`accent`,succeeded:`ok`,failed:`err`,cancelled:`neutral`,budget_exhausted:`warn`},K={planning:`planning`,running:`running`,reviewing:`reviewing`,planned:`planned (dry run)`,succeeded:`succeeded`,failed:`failed`,cancelled:`cancelled`,budget_exhausted:`out of budget`},q=new Set([`planning`,`running`,`reviewing`]);function J(e){return q.has(e.status)}function Y(e){let t=Number(e);return e.trim()&&Number.isInteger(t)&&t>0?t:void 0}function X(){let e=s(),[t,n]=(0,U.useState)(),r=p(e.error)&&e.error.status===501,a=e.data??[],o=a.find(e=>e.id===t)??a[0],c=a.find(J);return(0,W.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,W.jsx)(k,{title:`Goals`,description:`Give the agent team an objective: a planner splits it into tasks, role agents execute them, a reviewer re-plans until it is done or the budget runs out.`}),r?(0,W.jsxs)(x,{tone:`warn`,title:`Goal mode unavailable`,children:[(0,W.jsxs)(`p`,{children:[`This gateway answered `,(0,W.jsx)(`code`,{className:`font-mono text-fg`,children:`501 goals_unavailable`}),`: it was started outside a project. Start it inside a repository with a project brain, or run a goal from the terminal:`]}),(0,W.jsx)(A,{command:`davecode goal "<objective>"`,className:`mt-2 max-w-sm`})]}):(0,W.jsx)(Z,{busy:c?.id,onStarted:e=>n(e.id)}),e.isError&&!r&&(0,W.jsx)(x,{tone:`err`,title:`Could not load goals`,children:u(e.error)}),!r&&(0,W.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 xl:grid-cols-[320px_minmax(0,1fr)]`,children:[(0,W.jsxs)(j,{"aria-labelledby":`goal-list-title`,className:`xl:self-start`,children:[(0,W.jsx)(D,{id:`goal-list-title`,title:`History`,meta:a.length?`${a.length} goal${a.length===1?``:`s`}`:void 0}),e.isPending?(0,W.jsx)(N,{rows:4,className:`p-3`}):a.length===0?(0,W.jsx)(M,{icon:T,title:`No goals yet`,description:`Describe an objective above, or try a dry run to see the plan first.`}):(0,W.jsx)(`ul`,{className:`flex flex-col p-1.5`,"aria-label":`Goals`,children:a.map(e=>{let t=e.tasks.filter(e=>e.status===`SUCCESS`).length,r=e.id===o?.id;return(0,W.jsx)(`li`,{children:(0,W.jsxs)(`button`,{type:`button`,"aria-current":r?`true`:void 0,onClick:()=>n(e.id),className:i(`flex w-full flex-col gap-1 rounded-md px-2.5 py-2 text-left transition-colors duration-150`,r?`bg-hover`:`hover:bg-hover/60`),children:[(0,W.jsx)(`span`,{className:`line-clamp-2 text-[13px] leading-5 text-fg`,children:e.objective}),(0,W.jsxs)(`span`,{className:`flex items-center gap-2 text-2xs text-muted`,children:[(0,W.jsx)(h,{tone:G[e.status],dot:!0,pulse:J(e),children:K[e.status]}),(0,W.jsxs)(`span`,{className:`tnum`,children:[t,`/`,e.tasks.length,` tasks`]}),(0,W.jsx)(`span`,{className:`ml-auto`,children:l(Date.parse(e.createdAt))})]})]})},e.id)})})]}),o?(0,W.jsx)($,{goal:o}):null]})]})}function Z({busy:e,onStarted:t}){let n=o(),[r,i]=(0,U.useState)(``),[a,s]=(0,U.useState)(``),[c,l]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[m,h]=(0,U.useState)(!1),[g,_]=(0,U.useState)(null);return(0,W.jsxs)(j,{"aria-labelledby":`new-goal-title`,children:[(0,W.jsx)(D,{id:`new-goal-title`,title:`New goal`,meta:(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,W.jsx)(H,{"aria-hidden":!0,className:`size-3.5 text-ok`,strokeWidth:1.75}),`Never emails, posts, pays or signs up: those become drafts`]})}),(0,W.jsxs)(`form`,{onSubmit:e=>{if(e.preventDefault(),!r.trim()){_(`Describe what the team should achieve.`);return}_(null);let o={objective:r.trim()},s=Y(a),l=Y(c),f=Y(d);s&&(o.maxRounds=s),l&&(o.maxTasks=l),f&&(o.maxTokens=f),m&&(o.dryRun=!0),n.mutate(o,{onSuccess:e=>{C({tone:`info`,title:m?`Planning (dry run)`:`Goal started`,description:e.objective}),i(``),t(e)},onError:e=>C({tone:`err`,title:`Could not start the goal`,description:p(e)&&e.code===`busy`?`${e.message}. Goals and the runner take turns on the working tree.`:u(e)})})},className:`flex flex-col gap-3 p-4`,children:[(0,W.jsx)(R,{label:`Objective`,required:!0,error:g,children:({id:e,describedBy:t,invalid:n})=>(0,W.jsx)(I,{id:e,"aria-describedby":t,"aria-invalid":n,rows:2,maxLength:4e3,placeholder:`e.g. Write positioning and landing-page copy for this project, then add a /pricing page`,value:r,onChange:e=>i(e.target.value)})}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,W.jsx)(R,{label:`Max rounds`,className:`w-28`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`4`,value:a,onChange:e=>s(e.target.value)})}),(0,W.jsx)(R,{label:`Max tasks`,className:`w-28`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`12`,value:c,onChange:e=>l(e.target.value)})}),(0,W.jsx)(R,{label:`Token budget`,className:`w-36`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`1000000`,value:d,onChange:e=>f(e.target.value)})}),(0,W.jsxs)(`span`,{className:`flex h-8 items-center gap-2 text-[12px] text-fg-2`,children:[(0,W.jsx)(v,{checked:m,onChange:h,label:`Dry run`}),`Dry run (plan only)`]}),(0,W.jsx)(P,{type:`submit`,variant:`primary`,icon:S,className:`ml-auto`,loading:n.isPending,disabled:n.isPending||!!e&&!m,title:e&&!m?`Goal ${e} is still running`:void 0,children:m?`Plan`:`Start goal`})]})]})]})}function Q({label:e,value:t,max:n,format:r=String}){let a=n>0?Math.min(100,t/n*100):0;return(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-[12px]`,children:[(0,W.jsx)(`span`,{className:`text-muted`,children:e}),(0,W.jsxs)(`span`,{className:`tnum font-mono text-fg`,children:[r(t),(0,W.jsxs)(`span`,{className:`text-muted`,children:[` / `,r(n)]})]})]}),(0,W.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-track`,"aria-hidden":!0,children:(0,W.jsx)(`div`,{className:i(`h-full rounded-full transition-[width] duration-500 ease-snappy`,a>=90?`bg-warn`:`bg-accent`),style:{width:`${a}%`}})})]})}function $({goal:e}){let t=d(),n=a(),r=c(),[o,s]=(0,U.useState)(!1),[l,p]=(0,U.useState)(),g=J(e),v=e.tasks.filter(e=>e.status===`SUCCESS`).length,x=r.events.filter(t=>t.type===`goal.log`&&t.goalId===e.id),T=()=>t.mutate(e.id,{onSuccess:e=>C({tone:`info`,title:`Goal ${e.status}`,description:e.objective}),onError:e=>C({tone:`err`,title:`Could not cancel`,description:u(e)})});return(0,W.jsxs)(j,{"aria-labelledby":`goal-detail-title`,className:`min-w-0`,children:[(0,W.jsx)(D,{id:`goal-detail-title`,title:(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:e.id}),meta:(0,W.jsx)(h,{tone:G[e.status],dot:!0,pulse:g,children:K[e.status]}),actions:(0,W.jsxs)(W.Fragment,{children:[e.status===`planned`&&(0,W.jsx)(P,{size:`sm`,variant:`primary`,icon:S,loading:n.isPending,onClick:()=>n.mutate(e.id,{onSuccess:e=>C({tone:`info`,title:`Executing planned goal`,description:e.objective}),onError:e=>C({tone:`err`,title:`Could not execute plan`,description:u(e)})}),children:`Execute plan`}),g&&(0,W.jsx)(P,{size:`sm`,variant:`danger`,icon:w,loading:t.isPending,onClick:()=>s(!0),children:`Cancel`})]})}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,W.jsx)(`p`,{className:`text-[15px] leading-6 font-medium text-fg`,children:e.objective}),(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-3`,children:[(0,W.jsx)(Q,{label:`Rounds`,value:e.round,max:e.limits.maxRounds}),(0,W.jsx)(Q,{label:`Tasks done`,value:v,max:Math.max(e.tasks.length,1)}),(0,W.jsx)(Q,{label:`Tokens`,value:e.limits.tokensUsed,max:e.limits.maxTokens,format:f})]}),e.lastError&&(0,W.jsx)(`p`,{className:`rounded-md border border-err/30 bg-err-soft p-2 font-mono text-2xs text-err`,children:e.lastError}),(0,W.jsx)(`section`,{"aria-label":`Tasks`,className:`flex flex-col`,children:e.tasks.length===0?(0,W.jsx)(`p`,{className:`text-[12px] text-muted`,children:g?`The planner is drafting the task graph…`:`No tasks were planned.`}):(0,W.jsx)(`ol`,{className:`flex flex-col divide-y divide-line rounded-md border border-line`,children:e.tasks.map(t=>(0,W.jsxs)(`li`,{className:i(`flex flex-col gap-1.5 px-3 py-2.5`,t.id===e.activeTaskId&&`bg-accent-soft/40`),children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsx)(F,{status:t.status}),(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:t.id}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px] text-fg`,children:t.title}),(0,W.jsx)(h,{mono:!0,children:t.role}),(0,W.jsx)(h,{tone:t.kind===`code`?`accent`:`neutral`,mono:!0,children:t.kind}),t.round>1&&(0,W.jsxs)(h,{mono:!0,children:[`round `,t.round]})]}),t.dependsOn.length>0&&(0,W.jsxs)(`p`,{className:`text-2xs text-muted`,children:[`after `,t.dependsOn.join(`, `)]}),t.artifact&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 font-mono text-2xs text-fg-2`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>p(e=>e===t.id?void 0:t.id),"aria-expanded":l===t.id,className:`inline-flex items-center gap-1 rounded px-1 py-0.5 text-fg-2 transition-colors hover:bg-hover hover:text-fg`,children:[l===t.id?(0,W.jsx)(B,{"aria-hidden":!0,className:`size-3.5 text-muted`}):(0,W.jsx)(_,{"aria-hidden":!0,className:`size-3.5 text-muted`}),(0,W.jsx)(y,{"aria-hidden":!0,className:`size-3.5 text-muted`,strokeWidth:1.75}),(0,W.jsx)(`span`,{className:`truncate`,children:t.artifact})]}),(0,W.jsx)(O,{value:t.artifact,label:`Copy path`})]}),l===t.id&&(0,W.jsx)(ee,{goalId:e.id,taskId:t.id})]}),t.status===`FAILED`&&t.notes&&(0,W.jsx)(`p`,{className:`line-clamp-3 font-mono text-2xs text-err`,children:t.notes})]},t.id))})}),e.summary&&(0,W.jsx)(`section`,{"aria-label":`Summary`,className:`rounded-md border border-line bg-raised/40 p-3`,children:(0,W.jsx)(b,{source:e.summary,className:`text-[13px]`})}),(0,W.jsx)(`section`,{"aria-label":`Goal log`,className:`term max-h-64 overflow-auto rounded-md border border-line bg-term py-2 font-mono text-[12px] leading-[1.6]`,children:x.length===0?(0,W.jsx)(`p`,{className:`px-3 text-muted`,children:g?`Waiting for agent output…`:`No live log for this goal in this session.`}):x.map(e=>(0,W.jsxs)(`div`,{className:`flex gap-3 px-3`,children:[(0,W.jsx)(`span`,{className:`tnum shrink-0 text-faint select-none`,children:m(e.ts)}),(0,W.jsx)(`span`,{className:`w-20 shrink-0 truncate text-info`,children:e.role??`goal`}),(0,W.jsx)(`span`,{className:i(`min-w-0 break-words`,e.level===`error`?`text-err`:e.level===`warn`?`text-warn`:`text-fg-2`),children:e.message})]},`${e.ts}-${e.message}`))})]}),(0,W.jsx)(E,{open:o,onClose:()=>s(!1),title:`Cancel this goal?`,description:`The agent in flight is stopped. Finished artifacts and merged code stay; an interrupted code task keeps its partial work on its branch.`,footer:(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(P,{variant:`ghost`,onClick:()=>s(!1),children:`Keep going`}),(0,W.jsx)(P,{variant:`danger`,icon:w,onClick:()=>{s(!1),T()},children:`Cancel goal`})]}),children:(0,W.jsx)(`p`,{className:`text-[12px] text-muted`,children:e.objective})})]})}function ee({goalId:e,taskId:t}){let n=g(e,t);return n.isPending?(0,W.jsx)(N,{rows:3,className:`p-2`}):n.isError?(0,W.jsx)(`p`,{className:`rounded-md border border-err/30 bg-err-soft p-2 font-mono text-2xs text-err`,children:u(n.error)}):(0,W.jsxs)(`div`,{className:`rounded-md border border-line bg-raised/50 p-3`,children:[(0,W.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2 border-b border-line pb-1.5`,children:[(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:n.data.path}),(0,W.jsx)(O,{value:n.data.content,label:`Copy markdown`})]}),(0,W.jsx)(b,{source:n.data.content,className:`text-[13px]`})]})}export{$ as GoalDetail,X as Goals,J as isActiveGoal,B as t};
|
|
1
|
+
import{i as e,n as t,o as n,r,t as i}from"./cn-BwE4cei0.js";import{C as a,M as o,T as s,V as c,d as l,ft as u,g as d,i as f,pt as p,r as m,t as h,w as g}from"./Badge-DUGKlx3Z.js";import{n as _,t as v}from"./Switch-DPYlLseH.js";import{n as y,t as b}from"./Markdown-CGgIydUh.js";import{t as x}from"./Callout-WgXHDPg0.js";import{B as S,C,F as w,N as T,d as E,i as D,m as O,n as k,p as A,r as j,s as M,u as N,w as P,y as F}from"./index-CpztPbom.js";import{i as I,n as L,t as R}from"./Field-Cmpgg_1z.js";var z={name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]};z.node;var B=t(z),V={name:`shield-check`,size:24,node:[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]};V.node;var H=t(V),U=n(e(),1),W=r(),G={planning:`info`,running:`info`,reviewing:`info`,planned:`accent`,succeeded:`ok`,failed:`err`,cancelled:`neutral`,budget_exhausted:`warn`},K={planning:`planning`,running:`running`,reviewing:`reviewing`,planned:`planned (dry run)`,succeeded:`succeeded`,failed:`failed`,cancelled:`cancelled`,budget_exhausted:`out of budget`},q=new Set([`planning`,`running`,`reviewing`]);function J(e){return q.has(e.status)}function Y(e){let t=Number(e);return e.trim()&&Number.isInteger(t)&&t>0?t:void 0}function X(){let e=s(),[t,n]=(0,U.useState)(),r=p(e.error)&&e.error.status===501,a=e.data??[],o=a.find(e=>e.id===t)??a[0],c=a.find(J);return(0,W.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,W.jsx)(k,{title:`Goals`,description:`Give the agent team an objective: a planner splits it into tasks, role agents execute them, a reviewer re-plans until it is done or the budget runs out.`}),r?(0,W.jsxs)(x,{tone:`warn`,title:`Goal mode unavailable`,children:[(0,W.jsxs)(`p`,{children:[`This gateway answered `,(0,W.jsx)(`code`,{className:`font-mono text-fg`,children:`501 goals_unavailable`}),`: it was started outside a project. Start it inside a repository with a project brain, or run a goal from the terminal:`]}),(0,W.jsx)(A,{command:`davecode goal "<objective>"`,className:`mt-2 max-w-sm`})]}):(0,W.jsx)(Z,{busy:c?.id,onStarted:e=>n(e.id)}),e.isError&&!r&&(0,W.jsx)(x,{tone:`err`,title:`Could not load goals`,children:u(e.error)}),!r&&(0,W.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 xl:grid-cols-[320px_minmax(0,1fr)]`,children:[(0,W.jsxs)(j,{"aria-labelledby":`goal-list-title`,className:`xl:self-start`,children:[(0,W.jsx)(D,{id:`goal-list-title`,title:`History`,meta:a.length?`${a.length} goal${a.length===1?``:`s`}`:void 0}),e.isPending?(0,W.jsx)(N,{rows:4,className:`p-3`}):a.length===0?(0,W.jsx)(M,{icon:T,title:`No goals yet`,description:`Describe an objective above, or try a dry run to see the plan first.`}):(0,W.jsx)(`ul`,{className:`flex flex-col p-1.5`,"aria-label":`Goals`,children:a.map(e=>{let t=e.tasks.filter(e=>e.status===`SUCCESS`).length,r=e.id===o?.id;return(0,W.jsx)(`li`,{children:(0,W.jsxs)(`button`,{type:`button`,"aria-current":r?`true`:void 0,onClick:()=>n(e.id),className:i(`flex w-full flex-col gap-1 rounded-md px-2.5 py-2 text-left transition-colors duration-150`,r?`bg-hover`:`hover:bg-hover/60`),children:[(0,W.jsx)(`span`,{className:`line-clamp-2 text-[13px] leading-5 text-fg`,children:e.objective}),(0,W.jsxs)(`span`,{className:`flex items-center gap-2 text-2xs text-muted`,children:[(0,W.jsx)(h,{tone:G[e.status],dot:!0,pulse:J(e),children:K[e.status]}),(0,W.jsxs)(`span`,{className:`tnum`,children:[t,`/`,e.tasks.length,` tasks`]}),(0,W.jsx)(`span`,{className:`ml-auto`,children:l(Date.parse(e.createdAt))})]})]})},e.id)})})]}),o?(0,W.jsx)($,{goal:o}):null]})]})}function Z({busy:e,onStarted:t}){let n=o(),[r,i]=(0,U.useState)(``),[a,s]=(0,U.useState)(``),[c,l]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[m,h]=(0,U.useState)(!1),[g,_]=(0,U.useState)(null);return(0,W.jsxs)(j,{"aria-labelledby":`new-goal-title`,children:[(0,W.jsx)(D,{id:`new-goal-title`,title:`New goal`,meta:(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,W.jsx)(H,{"aria-hidden":!0,className:`size-3.5 text-ok`,strokeWidth:1.75}),`Never emails, posts, pays or signs up: those become drafts`]})}),(0,W.jsxs)(`form`,{onSubmit:e=>{if(e.preventDefault(),!r.trim()){_(`Describe what the team should achieve.`);return}_(null);let o={objective:r.trim()},s=Y(a),l=Y(c),f=Y(d);s&&(o.maxRounds=s),l&&(o.maxTasks=l),f&&(o.maxTokens=f),m&&(o.dryRun=!0),n.mutate(o,{onSuccess:e=>{C({tone:`info`,title:m?`Planning (dry run)`:`Goal started`,description:e.objective}),i(``),t(e)},onError:e=>C({tone:`err`,title:`Could not start the goal`,description:p(e)&&e.code===`busy`?`${e.message}. Goals and the runner take turns on the working tree.`:u(e)})})},className:`flex flex-col gap-3 p-4`,children:[(0,W.jsx)(R,{label:`Objective`,required:!0,error:g,children:({id:e,describedBy:t,invalid:n})=>(0,W.jsx)(I,{id:e,"aria-describedby":t,"aria-invalid":n,rows:2,maxLength:4e3,placeholder:`e.g. Write positioning and landing-page copy for this project, then add a /pricing page`,value:r,onChange:e=>i(e.target.value)})}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,W.jsx)(R,{label:`Max rounds`,className:`w-28`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`4`,value:a,onChange:e=>s(e.target.value)})}),(0,W.jsx)(R,{label:`Max tasks`,className:`w-28`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`12`,value:c,onChange:e=>l(e.target.value)})}),(0,W.jsx)(R,{label:`Token budget`,className:`w-36`,children:({id:e})=>(0,W.jsx)(L,{id:e,inputMode:`numeric`,placeholder:`1000000`,value:d,onChange:e=>f(e.target.value)})}),(0,W.jsxs)(`span`,{className:`flex h-8 items-center gap-2 text-[12px] text-fg-2`,children:[(0,W.jsx)(v,{checked:m,onChange:h,label:`Dry run`}),`Dry run (plan only)`]}),(0,W.jsx)(P,{type:`submit`,variant:`primary`,icon:S,className:`ml-auto`,loading:n.isPending,disabled:n.isPending||!!e&&!m,title:e&&!m?`Goal ${e} is still running`:void 0,children:m?`Plan`:`Start goal`})]})]})]})}function Q({label:e,value:t,max:n,format:r=String}){let a=n>0?Math.min(100,t/n*100):0;return(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-[12px]`,children:[(0,W.jsx)(`span`,{className:`text-muted`,children:e}),(0,W.jsxs)(`span`,{className:`tnum font-mono text-fg`,children:[r(t),(0,W.jsxs)(`span`,{className:`text-muted`,children:[` / `,r(n)]})]})]}),(0,W.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-track`,"aria-hidden":!0,children:(0,W.jsx)(`div`,{className:i(`h-full rounded-full transition-[width] duration-500 ease-snappy`,a>=90?`bg-warn`:`bg-accent`),style:{width:`${a}%`}})})]})}function $({goal:e}){let t=d(),n=a(),r=c(),[o,s]=(0,U.useState)(!1),[l,p]=(0,U.useState)(),g=J(e),v=e.tasks.filter(e=>e.status===`SUCCESS`).length,x=r.events.filter(t=>t.type===`goal.log`&&t.goalId===e.id),T=()=>t.mutate(e.id,{onSuccess:e=>C({tone:`info`,title:`Goal ${e.status}`,description:e.objective}),onError:e=>C({tone:`err`,title:`Could not cancel`,description:u(e)})});return(0,W.jsxs)(j,{"aria-labelledby":`goal-detail-title`,className:`min-w-0`,children:[(0,W.jsx)(D,{id:`goal-detail-title`,title:(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:e.id}),meta:(0,W.jsx)(h,{tone:G[e.status],dot:!0,pulse:g,children:K[e.status]}),actions:(0,W.jsxs)(W.Fragment,{children:[e.status===`planned`&&(0,W.jsx)(P,{size:`sm`,variant:`primary`,icon:S,loading:n.isPending,onClick:()=>n.mutate(e.id,{onSuccess:e=>C({tone:`info`,title:`Executing planned goal`,description:e.objective}),onError:e=>C({tone:`err`,title:`Could not execute plan`,description:u(e)})}),children:`Execute plan`}),g&&(0,W.jsx)(P,{size:`sm`,variant:`danger`,icon:w,loading:t.isPending,onClick:()=>s(!0),children:`Cancel`})]})}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,W.jsx)(`p`,{className:`text-[15px] leading-6 font-medium text-fg`,children:e.objective}),(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-3`,children:[(0,W.jsx)(Q,{label:`Rounds`,value:e.round,max:e.limits.maxRounds}),(0,W.jsx)(Q,{label:`Tasks done`,value:v,max:Math.max(e.tasks.length,1)}),(0,W.jsx)(Q,{label:`Tokens`,value:e.limits.tokensUsed,max:e.limits.maxTokens,format:f})]}),e.lastError&&(0,W.jsx)(`p`,{className:`rounded-md border border-err/30 bg-err-soft p-2 font-mono text-2xs text-err`,children:e.lastError}),(0,W.jsx)(`section`,{"aria-label":`Tasks`,className:`flex flex-col`,children:e.tasks.length===0?(0,W.jsx)(`p`,{className:`text-[12px] text-muted`,children:g?`The planner is drafting the task graph…`:`No tasks were planned.`}):(0,W.jsx)(`ol`,{className:`flex flex-col divide-y divide-line rounded-md border border-line`,children:e.tasks.map(t=>(0,W.jsxs)(`li`,{className:i(`flex flex-col gap-1.5 px-3 py-2.5`,t.id===e.activeTaskId&&`bg-accent-soft/40`),children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsx)(F,{status:t.status}),(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:t.id}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px] text-fg`,children:t.title}),(0,W.jsx)(h,{mono:!0,children:t.role}),(0,W.jsx)(h,{tone:t.kind===`code`?`accent`:`neutral`,mono:!0,children:t.kind}),t.round>1&&(0,W.jsxs)(h,{mono:!0,children:[`round `,t.round]})]}),t.dependsOn.length>0&&(0,W.jsxs)(`p`,{className:`text-2xs text-muted`,children:[`after `,t.dependsOn.join(`, `)]}),t.artifact&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 font-mono text-2xs text-fg-2`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>p(e=>e===t.id?void 0:t.id),"aria-expanded":l===t.id,className:`inline-flex items-center gap-1 rounded px-1 py-0.5 text-fg-2 transition-colors hover:bg-hover hover:text-fg`,children:[l===t.id?(0,W.jsx)(B,{"aria-hidden":!0,className:`size-3.5 text-muted`}):(0,W.jsx)(_,{"aria-hidden":!0,className:`size-3.5 text-muted`}),(0,W.jsx)(y,{"aria-hidden":!0,className:`size-3.5 text-muted`,strokeWidth:1.75}),(0,W.jsx)(`span`,{className:`truncate`,children:t.artifact})]}),(0,W.jsx)(O,{value:t.artifact,label:`Copy path`})]}),l===t.id&&(0,W.jsx)(ee,{goalId:e.id,taskId:t.id})]}),t.status===`FAILED`&&t.notes&&(0,W.jsx)(`p`,{className:`line-clamp-3 font-mono text-2xs text-err`,children:t.notes})]},t.id))})}),e.summary&&(0,W.jsx)(`section`,{"aria-label":`Summary`,className:`rounded-md border border-line bg-raised/40 p-3`,children:(0,W.jsx)(b,{source:e.summary,className:`text-[13px]`})}),(0,W.jsx)(`section`,{"aria-label":`Goal log`,className:`term max-h-64 overflow-auto rounded-md border border-line bg-term py-2 font-mono text-[12px] leading-[1.6]`,children:x.length===0?(0,W.jsx)(`p`,{className:`px-3 text-muted`,children:g?`Waiting for agent output…`:`No live log for this goal in this session.`}):x.map(e=>(0,W.jsxs)(`div`,{className:`flex gap-3 px-3`,children:[(0,W.jsx)(`span`,{className:`tnum shrink-0 text-faint select-none`,children:m(e.ts)}),(0,W.jsx)(`span`,{className:`w-20 shrink-0 truncate text-info`,children:e.role??`goal`}),(0,W.jsx)(`span`,{className:i(`min-w-0 break-words`,e.level===`error`?`text-err`:e.level===`warn`?`text-warn`:`text-fg-2`),children:e.message})]},`${e.ts}-${e.message}`))})]}),(0,W.jsx)(E,{open:o,onClose:()=>s(!1),title:`Cancel this goal?`,description:`The agent in flight is stopped. Finished artifacts and merged code stay; an interrupted code task keeps its partial work on its branch.`,footer:(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(P,{variant:`ghost`,onClick:()=>s(!1),children:`Keep going`}),(0,W.jsx)(P,{variant:`danger`,icon:w,onClick:()=>{s(!1),T()},children:`Cancel goal`})]}),children:(0,W.jsx)(`p`,{className:`text-[12px] text-muted`,children:e.objective})})]})}function ee({goalId:e,taskId:t}){let n=g(e,t);return n.isPending?(0,W.jsx)(N,{rows:3,className:`p-2`}):n.isError?(0,W.jsx)(`p`,{className:`rounded-md border border-err/30 bg-err-soft p-2 font-mono text-2xs text-err`,children:u(n.error)}):(0,W.jsxs)(`div`,{className:`rounded-md border border-line bg-raised/50 p-3`,children:[(0,W.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2 border-b border-line pb-1.5`,children:[(0,W.jsx)(`span`,{className:`font-mono text-2xs text-muted`,children:n.data.path}),(0,W.jsx)(O,{value:n.data.content,label:`Copy markdown`})]}),(0,W.jsx)(b,{source:n.data.content,className:`text-[13px]`})]})}export{$ as GoalDetail,X as Goals,J as isActiveGoal,B as t};
|