@qredence/fleet 0.9.0 → 0.10.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/bin/prime-runtime.d.mts +19 -0
  3. package/bin/prime-runtime.mjs +42 -5
  4. package/dist/web/client/assets/{agents-CGjUBYX7.js → agents-BMQXA18L.js} +2 -2
  5. package/dist/web/client/assets/{agents-page-CTuFJL9H.js → agents-page-D2soW46O.js} +1 -1
  6. package/dist/web/client/assets/{chat-queries-CfZiupub.js → chat-queries-ty76G6rK.js} +1 -1
  7. package/dist/web/client/assets/{connectors-CFxLqG2x.js → connectors-E4KW6hBL.js} +2 -2
  8. package/dist/web/client/assets/{connectors-page-DQJdoAnl.js → connectors-page-CDzzjCIJ.js} +1 -1
  9. package/dist/web/client/assets/globals-DDDleTbS.css +2 -0
  10. package/dist/web/client/assets/{index-C9FHZDGw.js → index-CEZTSuLf.js} +2 -2
  11. package/dist/web/client/assets/{mcp-connections-section-DEo6Kemv.js → mcp-connections-section-BsNhp1b2.js} +2 -2
  12. package/dist/web/client/assets/routes-EKRITFZz.js +14 -0
  13. package/dist/web/client/assets/settings-dialog-BomLOETY.js +3 -0
  14. package/dist/web/client/bundle-budget.json +5 -5
  15. package/dist/web/server/{_tanstack-start-manifest_v-B6ne-00G-OFX7UD4K.js → _tanstack-start-manifest_v-BiMhF9NX-QUZEGAB6.js} +7 -7
  16. package/dist/web/server/{agents-BwzqhPjK-ANFHE5AG.js → agents-DOgCHixY-KUZP2VDO.js} +2 -2
  17. package/dist/web/server/{agents-page-DEqPV-eG-BR5MR74O.js → agents-page-BdiR9H8w-M6X6SXMF.js} +3 -3
  18. package/dist/web/server/{artifacts-panel-DLO8OfXb-B2ZWCDFP.js → artifacts-panel-BNiaRF83-HDC6VQ66.js} +5 -5
  19. package/dist/web/server/{chat-command-palette-CaDQAMAu-KDH7BTDS.js → chat-command-palette-CT9aJAWG-LV26BDEW.js} +5 -5
  20. package/dist/web/server/{chunk-UDUG3MYZ.js → chunk-27J2LPAW.js} +2 -2
  21. package/dist/web/server/{chunk-V2GCVTDP.js → chunk-3CU2ITG7.js} +33 -48
  22. package/dist/web/server/{chunk-B5FKCW75.js → chunk-3R7XCOWI.js} +4 -4
  23. package/dist/web/server/{chunk-6AFVCERK.js → chunk-4TKPOOIG.js} +4 -4
  24. package/dist/web/server/{chunk-HUHUPGHT.js → chunk-4YQ7RBB7.js} +5 -5
  25. package/dist/web/server/{chunk-5IE54MRG.js → chunk-5XRESJQR.js} +3 -3
  26. package/dist/web/server/{chunk-TOJA3X5N.js → chunk-BLGKLQJG.js} +16 -5
  27. package/dist/web/server/{chunk-TQ2RECTH.js → chunk-C5XHGLET.js} +1 -1
  28. package/dist/web/server/{chunk-TTNONWZZ.js → chunk-LEZMRXSP.js} +923 -697
  29. package/dist/web/server/{chunk-KDCSEISZ.js → chunk-NZCEQWK2.js} +2 -1
  30. package/dist/web/server/{chunk-VM3U6PUU.js → chunk-QOZCYKMA.js} +2 -2
  31. package/dist/web/server/{connectors-C0xm91Ss-DJVBGD73.js → connectors-Dv_uPdv0-2X5VWQXK.js} +2 -2
  32. package/dist/web/server/{connectors-page-B6tJNZ6c-R5K4NSAT.js → connectors-page-DW75T-uH-EKRHUZ6K.js} +4 -4
  33. package/dist/web/server/{create-project-dialog-PFPHHWIV-GH7JR5IK.js → create-project-dialog-EwieT1Vw-X5MYQSZM.js} +5 -5
  34. package/dist/web/server/{openui-renderer-B9D8-Av--LFZP4U5V.js → openui-renderer-DCkg_JoD-4QCKSVY5.js} +4 -4
  35. package/dist/web/server/{resources-panel-CTzOOKPz-5G6RS2D6.js → resources-panel-s0mgyvgQ-FVMBBLJJ.js} +6 -6
  36. package/dist/web/server/{router-CnBux_Ld-YTVBMJFL.js → router-DXxChQOI-B7VVEX3H.js} +2 -2
  37. package/dist/web/server/{routes-BUGzvQoO-WW43X7W2.js → routes-D-g2ILNg-LDYCQ4NU.js} +4 -4
  38. package/dist/web/server/server.js +2 -2
  39. package/dist/web/server/{session-activity-panel-f0d3fCm7-I6L5IKFQ.js → session-activity-panel-wC0jAJvs-QAHJXPAM.js} +6 -6
  40. package/dist/web/server/{session-reasoning-panel-QIt_xjP0-FKJWMNHO.js → session-reasoning-panel-B_K8YgF5-AQPMFM3Y.js} +5 -5
  41. package/dist/web/server/{session-tool-renderer-Cg_ZPHxS-BNQKNJNZ.js → session-tool-renderer-D96BACVh-CH5CV3TS.js} +5 -5
  42. package/dist/web/server/{session-tree-panel-B--el8O5-NZOZJM5L.js → session-tree-panel-CZGXNZIP-FBB3XGMN.js} +5 -5
  43. package/dist/web/server/{settings-dialog-D_eJN2ia-W47Y474K.js → settings-dialog-BrjqiTVe-H7WOTB4I.js} +145 -66
  44. package/dist/web/server/{subagent-chat-panel-C9nWP21E-D5C2TTYD.js → subagent-chat-panel-Dz62jo_m-X4ZRN5KI.js} +8 -8
  45. package/dist/web/server/{subagents-panel-fAKvBNRG-O7QHXNE2.js → subagents-panel-CwpbzJJz-N3ISHODM.js} +8 -8
  46. package/dist/web/server/{workspace-panel-CZMNMU63-SYOSM3B7.js → workspace-panel-C7akv5b9-XUKEHPOP.js} +6 -6
  47. package/package.json +1 -1
  48. package/dist/web/client/assets/globals-DJhWyayo.css +0 -2
  49. package/dist/web/client/assets/routes-ja_liP8Z.js +0 -14
  50. package/dist/web/client/assets/settings-dialog-DiikSLhF.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,83 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 0b78235: Keep the packaged kernel runtime when `fleet-prime` installs Prime Agent
8
+
9
+ 0.10.0 fixed the runtime install inside the web server, but the `fleet-prime`
10
+ command installs Prime Agent itself before it starts the server, and that path
11
+ still kept only the `prime-agent` executable and deleted the
12
+ `prime-agent-runtime` directory the kernel bootstraps from. The server then
13
+ reused that binary as-is, so sessions started from the npm package could still
14
+ fail with "the runtime bundle that ships beside the Prime Agent binary is
15
+ missing".
16
+
17
+ `fleet-prime` and the server now share one installer. It keeps
18
+ `prime-agent-runtime` beside the binary, and an existing binary-only install
19
+ under `~/.prime/fleet/runtimes` is repaired automatically on the next start; no
20
+ manual cleanup is needed.
21
+
22
+ ## 0.10.0
23
+
24
+ ### Minor Changes
25
+
26
+ - 871ce42: Serve the model catalog from the Prime Agent daemon instead of the SDK
27
+
28
+ Fleet no longer builds or refreshes the stock runtime's `ModelRegistry`. The
29
+ model picker reads the pinned daemon's `get_model_catalog`, which re-parses
30
+ `models.json` and `auth.json` from disk on every call, through a short-lived
31
+ in-process snapshot so a page load does not create a daemon session per request.
32
+
33
+ Two user-visible fixes come with it:
34
+
35
+ - Providers configured only through an environment variable now count as
36
+ configured. The retired path hard-coded `configured: false` for environment
37
+ candidates, so a working `ANTHROPIC_API_KEY` or `GROQ_API_KEY` reported its
38
+ models as unavailable and hid them from the default model list.
39
+ - A custom provider in `models.json` that is missing `apiKey` now produces an
40
+ actionable diagnostic. The runtime silently drops every custom provider in the
41
+ file in that case, with no error on any surface.
42
+
43
+ Model thinking levels, the `Unknown model` error, and the stale-model fallback
44
+ to a provider's first available model are unchanged.
45
+
46
+ ### Patch Changes
47
+
48
+ - daee396: Restore the packaged Python kernel runtime on install
49
+
50
+ Fleet's installer extracted the pinned Prime Agent release, installed only the
51
+ executable, and deleted the rest of the payload. The `prime-agent-runtime`
52
+ directory the kernel bootstraps from was destroyed on every install, so sessions
53
+ failed with "the runtime bundle that ships beside the Prime Agent binary is
54
+ missing" even though the release contains it.
55
+
56
+ The installer now keeps the packaged runtime beside the binary, repairs an
57
+ existing binary-only install on the next start, and no longer claims a binary is
58
+ missing when the spawn working directory is the thing that does not exist.
59
+ - b2648a8: Correct the MCP and provider sign-in guidance
60
+
61
+ Fleet cannot start OAuth sign-in itself: the pinned daemon exposes no login command,
62
+ and the only entry point is Prime Agent's interactive terminal. The previous guidance
63
+ told users to "launch Prime Agent in a terminal and complete sign-in", which fails —
64
+ the CLI `mcp` subcommand has no `login`, only `add|list|get|remove`.
65
+
66
+ The alerts and the 501 responses now name the commands that exist (`/mcp login <name>`
67
+ for MCP servers, `/login` for providers) and no longer claim a Fleet restart is needed.
68
+ Restarting Fleet cannot reload the credential in any case: the daemon is spawned
69
+ detached and re-attaches to an already-running socket, and it re-reads `auth.json` on
70
+ each call.
71
+ - 32f79ab: Contain provider dialogs, protect credential hints, and refresh supported provider model lists when adding models.
72
+ - 32f79ab: Refresh cached settings after saving so newly enabled models appear in the model picker without restarting the server.
73
+ - 9bf257a: Share one cleared-session presentation value
74
+
75
+ The cleared-session presentation was hand-spelled at four reset sites (initial
76
+ state, project switch, session delete, and forbidden-session recovery). A single
77
+ shared, frozen value now backs all of them, so a new required field on the
78
+ presentation type is a compile-time error in one place instead of a silent gap
79
+ in four.
80
+
3
81
  ## 0.9.0
4
82
 
5
83
  ### Minor Changes
@@ -0,0 +1,19 @@
1
+ export interface PrimeRuntimeAsset {
2
+ archive: string;
3
+ sha256: string;
4
+ executableSha256: string;
5
+ }
6
+
7
+ export interface PrimeRuntimeManifest {
8
+ rust: { version: string; baseUrl: string; platforms: Record<string, PrimeRuntimeAsset | undefined> };
9
+ }
10
+
11
+ export function runtimeTarget(os?: string, cpu?: string): string;
12
+
13
+ export function ensurePrimeRuntime(options: {
14
+ manifest: PrimeRuntimeManifest;
15
+ installRoot?: string;
16
+ home?: string;
17
+ fetch?: typeof fetch;
18
+ target?: string;
19
+ }): Promise<string>;
@@ -1,9 +1,13 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { chmod, mkdir, mkdtemp, open, rename, rm, writeFile } from "node:fs/promises";
3
+ import { chmod, mkdir, mkdtemp, open, rename, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { arch, homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
+ // This module is the single Prime Agent runtime installer. The npm launcher
8
+ // (`fleet-prime`) runs it directly, and the web server re-exports it from
9
+ // `web/server/src/prime-runtime.ts`, so both install the same payload.
10
+
7
11
  export function runtimeTarget(os = platform(), cpu = arch()) {
8
12
  const target = `${os}-${cpu}`;
9
13
  if (!["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"].includes(target)) {
@@ -26,7 +30,13 @@ export async function ensurePrimeRuntime({
26
30
  if (!asset) throw new Error(`Fleet has no pinned Prime Agent runtime for ${target}`);
27
31
  const destination = installRoot ?? join(home, ".prime", "fleet", "runtimes", runtime.version, target);
28
32
  const executable = join(destination, "prime-agent");
29
- if (await matchesDigest(executable, asset.executableSha256)) return executable;
33
+ const packagedRuntime = join(destination, "prime-agent-runtime");
34
+ // A verified binary is not enough: the kernel bootstraps from the packaged
35
+ // runtime beside it. Installs made by earlier Fleet releases kept only the
36
+ // executable, so that state is repaired rather than short-circuited.
37
+ if ((await matchesDigest(executable, asset.executableSha256)) && (await directoryExists(packagedRuntime))) {
38
+ return executable;
39
+ }
30
40
 
31
41
  await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
32
42
  const staging = await mkdtemp(join(dirname(destination), ".fleet-prime-runtime-"));
@@ -50,18 +60,45 @@ export async function ensurePrimeRuntime({
50
60
  const result = spawnSync("tar", ["-xzf", archivePath, "-C", unpacked], { encoding: "utf8" });
51
61
  if (result.status !== 0)
52
62
  throw new Error(`Could not extract Prime Agent runtime: ${result.stderr || "tar failed"}`);
53
- if (!(await matchesDigest(join(unpacked, "prime-agent"), asset.executableSha256))) {
63
+ const extractedBinary = join(unpacked, "prime-agent");
64
+ if (!(await matchesDigest(extractedBinary, asset.executableSha256))) {
54
65
  throw new Error("Extracted Prime Agent executable checksum mismatch; refusing to install it.");
55
66
  }
56
- await chmod(join(unpacked, "prime-agent"), 0o755);
67
+ await chmod(extractedBinary, 0o755);
57
68
  await mkdir(destination, { recursive: true, mode: 0o700 });
58
- await rename(join(unpacked, "prime-agent"), executable);
69
+ // The kernel bootstraps from `prime-agent-runtime/`, which ships beside the
70
+ // binary. It lands before the executable is replaced, so a failed rename
71
+ // cannot leave a binary that looks current with no runtime. Any existing
72
+ // copy (possibly damaged) is moved aside into the private staging dir
73
+ // rather than deleted in place, so the window with no runtime is two
74
+ // renames, and the verified copy always replaces it.
75
+ const extractedRuntime = join(unpacked, "prime-agent-runtime");
76
+ if (await directoryExists(extractedRuntime)) {
77
+ await rename(packagedRuntime, join(staging, "previous-runtime")).catch((error) => {
78
+ if (error.code !== "ENOENT") throw error;
79
+ });
80
+ await rename(extractedRuntime, packagedRuntime).catch((error) => {
81
+ // A concurrent install of the same checksummed archive placed it first.
82
+ if (error.code !== "ENOTEMPTY" && error.code !== "EEXIST") throw error;
83
+ });
84
+ }
85
+ await rename(extractedBinary, executable);
59
86
  return executable;
60
87
  } finally {
61
88
  await rm(staging, { recursive: true, force: true });
62
89
  }
63
90
  }
64
91
 
92
+ async function directoryExists(path) {
93
+ try {
94
+ return (await stat(path)).isDirectory();
95
+ } catch (error) {
96
+ // Only absence means "not installed"; surface permission or symlink errors.
97
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return false;
98
+ throw error;
99
+ }
100
+ }
101
+
65
102
  async function matchesDigest(path, expected) {
66
103
  let file;
67
104
  try {
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-page-CTuFJL9H.js","assets/rolldown-runtime-hePW80VL.js","assets/react-Cvdyeg_0.js","assets/mutation-Da9zdeWr.js","assets/jsx-runtime-NZYk81nU.js","assets/with-selector-B_VDO56x.js","assets/chat-queries-CfZiupub.js","assets/chat-hpzV6IA6.js","assets/card-Dj1SnGUU.js","assets/utils-oBThwhjm.js","assets/createLucideIcon-CQY2ECfR.js","assets/activity-BPIKUzOU.js","assets/arrow-up-right-CG9RNk4p.js","assets/bot-DETalD3q.js","assets/clock-3-BwWCSCm_.js","assets/loader-circle-BmKYM_C4.js","assets/button-CWYjn8Zk.js","assets/useButton-CvcmqA2s.js","assets/dist-BogNzeK9.js","assets/clsx-DB0hHKMi.js","assets/product-page-header-Ck6I13CE.js","assets/alert-CzWGeumf.js","assets/badge-CzQFgmVK.js","assets/useRender-CzJUrRlB.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{t as r}from"./preload-helper-BLdHbfdN.js";var i=e(t()),a=n(),o=(0,i.lazy)(()=>r(async()=>{let{AgentsPage:e}=await import(`./agents-page-CTuFJL9H.js`);return{AgentsPage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])).then(({AgentsPage:e})=>({default:e})));function s(){return(0,a.jsx)(`main`,{className:`min-h-svh bg-background p-8`,children:(0,a.jsx)(`p`,{className:`mx-auto max-w-5xl text-sm text-muted-foreground`,children:`Loading agents…`})})}var c=()=>(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(s,{}),children:(0,a.jsx)(o,{})});export{c as component};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-page-D2soW46O.js","assets/rolldown-runtime-hePW80VL.js","assets/react-Cvdyeg_0.js","assets/mutation-Da9zdeWr.js","assets/jsx-runtime-NZYk81nU.js","assets/with-selector-B_VDO56x.js","assets/chat-queries-ty76G6rK.js","assets/chat-hpzV6IA6.js","assets/card-Dj1SnGUU.js","assets/utils-oBThwhjm.js","assets/createLucideIcon-CQY2ECfR.js","assets/activity-BPIKUzOU.js","assets/arrow-up-right-CG9RNk4p.js","assets/bot-DETalD3q.js","assets/clock-3-BwWCSCm_.js","assets/loader-circle-BmKYM_C4.js","assets/button-CWYjn8Zk.js","assets/useButton-CvcmqA2s.js","assets/dist-BogNzeK9.js","assets/clsx-DB0hHKMi.js","assets/product-page-header-Ck6I13CE.js","assets/alert-CzWGeumf.js","assets/badge-CzQFgmVK.js","assets/useRender-CzJUrRlB.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{t as r}from"./preload-helper-BLdHbfdN.js";var i=e(t()),a=n(),o=(0,i.lazy)(()=>r(async()=>{let{AgentsPage:e}=await import(`./agents-page-D2soW46O.js`);return{AgentsPage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])).then(({AgentsPage:e})=>({default:e})));function s(){return(0,a.jsx)(`main`,{className:`min-h-svh bg-background p-8`,children:(0,a.jsx)(`p`,{className:`mx-auto max-w-5xl text-sm text-muted-foreground`,children:`Loading agents…`})})}var c=()=>(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(s,{}),children:(0,a.jsx)(o,{})});export{c as component};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{O as n}from"./mutation-Da9zdeWr.js";import{t as r}from"./jsx-runtime-NZYk81nU.js";import{O as i,o as a,v as o}from"./chat-queries-CfZiupub.js";import{a as s,i as c,n as l,r as u,t as d}from"./card-Dj1SnGUU.js";import{t as f}from"./createLucideIcon-CQY2ECfR.js";import{t as p}from"./activity-BPIKUzOU.js";import{t as m}from"./arrow-up-right-CG9RNk4p.js";import{t as h}from"./bot-DETalD3q.js";import{t as g}from"./clock-3-BwWCSCm_.js";import{t as _}from"./loader-circle-BmKYM_C4.js";import{t as v}from"./button-CWYjn8Zk.js";import{t as y}from"./product-page-header-Ck6I13CE.js";import{n as b,r as x,t as S}from"./alert-CzWGeumf.js";import{t as C}from"./badge-CzQFgmVK.js";var w={name:`calendar-clock`,size:24,node:[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`path`,{d:`M21 7.338V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h2.338`,key:`7hb8p4`}],[`path`,{d:`M3 9h5.859`,key:`numkqi`}],[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]};w.node;var T=f(w),E=e(t(),1),D=r();function O(){let[e,t]=(0,E.useState)(20),r=a(),f=i({queryKey:[`chat`,`sessions`,`all`],queryFn:()=>o.listSessions()}),w=new Map((r.data?.projects??[]).map(e=>[e.projectId,e.name])),O=[...f.data??[]].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)),j=O.slice(0,e);return(0,D.jsxs)(`main`,{className:`min-h-svh bg-background`,children:[(0,D.jsx)(y,{active:`agents`}),(0,D.jsxs)(`div`,{className:`mx-auto flex w-full max-w-5xl flex-col gap-8 px-5 py-10 sm:px-8`,children:[(0,D.jsxs)(`div`,{className:`max-w-2xl`,children:[(0,D.jsx)(`div`,{className:`mb-3 flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary`,children:(0,D.jsx)(h,{className:`size-5`})}),(0,D.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Agents`}),(0,D.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-muted-foreground`,children:`Review conversations and schedules.`})]}),(0,D.jsxs)(`section`,{"aria-labelledby":`schedule-heading`,className:`space-y-3`,children:[(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`h2`,{id:`schedule-heading`,className:`text-base font-medium`,children:`Heartbeat and cron`}),(0,D.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Not supported in Fleet.`})]}),(0,D.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,D.jsx)(k,{icon:(0,D.jsx)(p,{className:`size-4`}),title:`Heartbeat`}),(0,D.jsx)(k,{icon:(0,D.jsx)(T,{className:`size-4`}),title:`Cron`})]})]}),(0,D.jsxs)(`section`,{"aria-labelledby":`saved-sessions-heading`,className:`space-y-3`,children:[(0,D.jsxs)(`div`,{className:`flex items-end justify-between gap-3`,children:[(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`h2`,{id:`saved-sessions-heading`,className:`text-base font-medium`,children:`Recent sessions`}),(0,D.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Recent conversations.`})]}),(0,D.jsx)(v,{asChild:!0,variant:`outline`,size:`compact`,children:(0,D.jsxs)(n,{to:`/`,children:[`Open sessions `,(0,D.jsx)(m,{"data-icon":`inline-end`})]})})]}),f.isLoading?(0,D.jsxs)(`div`,{className:`flex items-center gap-2 py-5 text-sm text-muted-foreground`,children:[(0,D.jsx)(_,{className:`size-4 animate-spin`}),` Loading saved sessions…`]}):f.isError?(0,D.jsxs)(S,{variant:`destructive`,children:[(0,D.jsx)(x,{children:`Could not load saved sessions`}),(0,D.jsx)(b,{children:f.error.message})]}):O.length===0?(0,D.jsx)(d,{children:(0,D.jsx)(l,{className:`py-6 text-sm text-muted-foreground`,children:`No saved sessions yet.`})}):(0,D.jsx)(`div`,{className:`grid gap-3 md:grid-cols-2`,children:j.map(e=>{let t=e.title||e.firstMessage||`Untitled session`;return(0,D.jsxs)(d,{size:`sm`,className:`min-w-0 overflow-hidden`,children:[(0,D.jsx)(c,{className:`min-w-0`,children:(0,D.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,D.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,D.jsx)(s,{className:`min-w-0 truncate`,title:t,children:t}),(0,D.jsxs)(u,{className:`mt-1 truncate`,children:[e.projectId?w.get(e.projectId)??`Project`:`Unassigned project`,`· `,e.messageCount,` `,e.messageCount===1?`message`:`messages`]})]}),(0,D.jsx)(C,{variant:`outline`,className:`capitalize`,children:e.status})]})}),(0,D.jsxs)(l,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,D.jsx)(g,{className:`size-3.5`}),`Updated `,A(e.updatedAt)]})]},e.sessionId)})}),!f.isLoading&&!f.isError&&O.length>20?(0,D.jsx)(`div`,{className:`flex justify-center`,children:(0,D.jsx)(v,{type:`button`,variant:`ghost`,size:`compact`,onClick:()=>t(e=>e>=O.length?20:e+20),children:e>=O.length?`Show fewer sessions`:`Show more sessions`})}):null]})]})]})}function k({icon:e,title:t}){return(0,D.jsxs)(d,{size:`sm`,className:`opacity-80`,children:[(0,D.jsx)(c,{children:(0,D.jsxs)(s,{className:`flex items-center gap-2`,children:[e,t]})}),(0,D.jsx)(l,{children:(0,D.jsx)(C,{variant:`outline`,children:`Unavailable`})})]})}function A(e){let t=new Date(e);return Number.isNaN(t.getTime())?`an unknown time`:t.toLocaleString()}export{O as AgentsPage};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{O as n}from"./mutation-Da9zdeWr.js";import{t as r}from"./jsx-runtime-NZYk81nU.js";import{O as i,o as a,v as o}from"./chat-queries-ty76G6rK.js";import{a as s,i as c,n as l,r as u,t as d}from"./card-Dj1SnGUU.js";import{t as f}from"./createLucideIcon-CQY2ECfR.js";import{t as p}from"./activity-BPIKUzOU.js";import{t as m}from"./arrow-up-right-CG9RNk4p.js";import{t as h}from"./bot-DETalD3q.js";import{t as g}from"./clock-3-BwWCSCm_.js";import{t as _}from"./loader-circle-BmKYM_C4.js";import{t as v}from"./button-CWYjn8Zk.js";import{t as y}from"./product-page-header-Ck6I13CE.js";import{n as b,r as x,t as S}from"./alert-CzWGeumf.js";import{t as C}from"./badge-CzQFgmVK.js";var w={name:`calendar-clock`,size:24,node:[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`path`,{d:`M21 7.338V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h2.338`,key:`7hb8p4`}],[`path`,{d:`M3 9h5.859`,key:`numkqi`}],[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]};w.node;var T=f(w),E=e(t(),1),D=r();function O(){let[e,t]=(0,E.useState)(20),r=a(),f=i({queryKey:[`chat`,`sessions`,`all`],queryFn:()=>o.listSessions()}),w=new Map((r.data?.projects??[]).map(e=>[e.projectId,e.name])),O=[...f.data??[]].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)),j=O.slice(0,e);return(0,D.jsxs)(`main`,{className:`min-h-svh bg-background`,children:[(0,D.jsx)(y,{active:`agents`}),(0,D.jsxs)(`div`,{className:`mx-auto flex w-full max-w-5xl flex-col gap-8 px-5 py-10 sm:px-8`,children:[(0,D.jsxs)(`div`,{className:`max-w-2xl`,children:[(0,D.jsx)(`div`,{className:`mb-3 flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary`,children:(0,D.jsx)(h,{className:`size-5`})}),(0,D.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Agents`}),(0,D.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-muted-foreground`,children:`Review conversations and schedules.`})]}),(0,D.jsxs)(`section`,{"aria-labelledby":`schedule-heading`,className:`space-y-3`,children:[(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`h2`,{id:`schedule-heading`,className:`text-base font-medium`,children:`Heartbeat and cron`}),(0,D.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Not supported in Fleet.`})]}),(0,D.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,D.jsx)(k,{icon:(0,D.jsx)(p,{className:`size-4`}),title:`Heartbeat`}),(0,D.jsx)(k,{icon:(0,D.jsx)(T,{className:`size-4`}),title:`Cron`})]})]}),(0,D.jsxs)(`section`,{"aria-labelledby":`saved-sessions-heading`,className:`space-y-3`,children:[(0,D.jsxs)(`div`,{className:`flex items-end justify-between gap-3`,children:[(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`h2`,{id:`saved-sessions-heading`,className:`text-base font-medium`,children:`Recent sessions`}),(0,D.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Recent conversations.`})]}),(0,D.jsx)(v,{asChild:!0,variant:`outline`,size:`compact`,children:(0,D.jsxs)(n,{to:`/`,children:[`Open sessions `,(0,D.jsx)(m,{"data-icon":`inline-end`})]})})]}),f.isLoading?(0,D.jsxs)(`div`,{className:`flex items-center gap-2 py-5 text-sm text-muted-foreground`,children:[(0,D.jsx)(_,{className:`size-4 animate-spin`}),` Loading saved sessions…`]}):f.isError?(0,D.jsxs)(S,{variant:`destructive`,children:[(0,D.jsx)(x,{children:`Could not load saved sessions`}),(0,D.jsx)(b,{children:f.error.message})]}):O.length===0?(0,D.jsx)(d,{children:(0,D.jsx)(l,{className:`py-6 text-sm text-muted-foreground`,children:`No saved sessions yet.`})}):(0,D.jsx)(`div`,{className:`grid gap-3 md:grid-cols-2`,children:j.map(e=>{let t=e.title||e.firstMessage||`Untitled session`;return(0,D.jsxs)(d,{size:`sm`,className:`min-w-0 overflow-hidden`,children:[(0,D.jsx)(c,{className:`min-w-0`,children:(0,D.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,D.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,D.jsx)(s,{className:`min-w-0 truncate`,title:t,children:t}),(0,D.jsxs)(u,{className:`mt-1 truncate`,children:[e.projectId?w.get(e.projectId)??`Project`:`Unassigned project`,`· `,e.messageCount,` `,e.messageCount===1?`message`:`messages`]})]}),(0,D.jsx)(C,{variant:`outline`,className:`capitalize`,children:e.status})]})}),(0,D.jsxs)(l,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,D.jsx)(g,{className:`size-3.5`}),`Updated `,A(e.updatedAt)]})]},e.sessionId)})}),!f.isLoading&&!f.isError&&O.length>20?(0,D.jsx)(`div`,{className:`flex justify-center`,children:(0,D.jsx)(v,{type:`button`,variant:`ghost`,size:`compact`,onClick:()=>t(e=>e>=O.length?20:e+20),children:e>=O.length?`Show fewer sessions`:`Show more sessions`})}):null]})]})]})}function k({icon:e,title:t}){return(0,D.jsxs)(d,{size:`sm`,className:`opacity-80`,children:[(0,D.jsx)(c,{children:(0,D.jsxs)(s,{className:`flex items-center gap-2`,children:[e,t]})}),(0,D.jsx)(l,{children:(0,D.jsx)(C,{variant:`outline`,children:`Unavailable`})})]})}function A(e){let t=new Date(e);return Number.isNaN(t.getTime())?`an unknown time`:t.toLocaleString()}export{O as AgentsPage};
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{D as n,S as r,T as i,_ as a,b as o,c as s,d as c,i as l,l as u,m as d,n as f,o as p,s as m,w as h,x as g,y as ee}from"./mutation-Da9zdeWr.js";import{t as te}from"./jsx-runtime-NZYk81nU.js";import{A as _,C as v,D as y,F as b,H as x,I as S,L as C,M as w,N as T,O as ne,P as re,R as E,S as ie,T as ae,V as D,_ as oe,a as se,b as ce,f as le,g as O,h as k,i as ue,l as A,m as j,n as de,o as fe,p as M,r as pe,s as me,t as he,u as ge,v as _e,w as ve,x as ye}from"./chat-hpzV6IA6.js";var be=class extends s{#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),Se(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ce(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ce(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 o(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&&!g(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&we(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||o(this.options.enabled,this.#t)!==o(t.enabled,this.#t)||o(this.options.staleTime,this.#t)!==o(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||o(this.options.enabled,this.#t)!==o(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 g(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().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(a)),t}#h(e){return!u()&&o(this.options.enabled,this.#t)!==!1&&d(e)}#g(){this.#b();let e=o(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=h(this.#r.dataUpdatedAt,e)+1;this.#u=i.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return o(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,!(this.#f===0||!this.#h(this.#f))&&(this.#d=i.setInterval(()=>{(this.options.refetchIntervalInBackground||m.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(i.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(i.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,s=this.#a,c=e===n?this.#n:e.state,{state:u}=e,d={...u},f=!1,p;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Se(e,t),o=i&&we(e,n,t,r);(a||o)&&(d={...d,...l(u.data,e.options)}),t._optimisticResults===`isRestoring`&&(d.fetchStatus=`idle`)}let{error:m,errorUpdatedAt:h,status:g}=d;p=d.data;let te=!1;if(t.placeholderData!==void 0&&p===void 0&&g===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(e=i.data,te=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(g=`success`,p=ee(i?.data,e,t),f=!0)}if(t.select&&p!==void 0&&!te){if(i&&p===a?.data&&t.select===this.#s)p=this.#c;else try{this.#s=t.select,p=t.select(p),p=ee(i?.data,p,t),this.#c=p,this.#o=null}catch(e){this.#o=e}}else p===void 0&&(this.#o=null);this.#o&&(m=this.#o,p=this.#c,h=Date.now(),g=`error`,f=!1);let _=d.fetchStatus===`fetching`,v=g===`pending`,y=g===`error`,b=v&&_,x=p!==void 0;return{status:g,fetchStatus:d.fetchStatus,isPending:v,isSuccess:g===`success`,isError:y,isInitialLoading:b,isLoading:b,data:p,dataUpdatedAt:d.dataUpdatedAt,error:m,errorUpdatedAt:h,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>c.dataUpdateCount||d.errorUpdateCount>c.errorUpdateCount,isFetching:_,isRefetching:_&&!v,isLoadingError:y&&!x,isPaused:d.fetchStatus===`paused`,isPlaceholderData:f,isRefetchError:y&&x,isStale:Te(e,t),refetch:this.refetch,isEnabled:o(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),g(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)})})();p.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 xe(e,t){return o(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||o(t.retryOnMount,e)!==!1)}function Se(e,t){return xe(e,t)||e.state.data!==void 0&&Ce(e,t,t.refetchOnMount)}function Ce(e,t,n){if(o(t.enabled,e)!==!1&&o(t.staleTime,e)!==`static`){let r=o(n,e);return r===`always`||r!==!1&&Te(e,t)}return!1}function we(e,t,n,r){return(e!==t||o(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Te(e,n)}function Te(e,t){return o(t.enabled,e)!==!1&&e.isStaleByTime(o(t.staleTime,e))}var Ee=class extends s{#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),g(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&c(t.mutationKey)!==c(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??f();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){p.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)})})}},N=e(t(),1),De=N.createContext(!1),Oe=()=>N.useContext(De);De.Provider,te();function ke(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ae=N.createContext(ke()),je=()=>N.useContext(Ae),Me=(e,t,n)=>{let i=n?.state.error&&typeof e.throwOnError==`function`?r(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||i)&&(t.isReset()||(e.retryOnMount=!1))},Ne=e=>{N.useEffect(()=>{e.clearReset()},[e])},Pe=({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:a})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(a&&e.data===void 0||r(n,[e.error,i])),Fe=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))}},Ie=(e,t)=>e?.suspense&&t.isPending,Le=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Re(e,t,r){let i=Oe(),o=je(),s=n(r),c=s.defaultQueryOptions(e),l=s.getQueryCache().get(c.queryHash),u=e.subscribed!==!1;c._optimisticResults=i?`isRestoring`:u?`optimistic`:void 0,Fe(c),Me(c,o,l),Ne(o);let[d]=N.useState(()=>new t(s,c)),f=d.getOptimisticResult(c),m=!i&&u;if(N.useSyncExternalStore(N.useCallback(e=>{let t=m?d.subscribe(p.batchCalls(e)):a;return d.updateResult(),t},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),N.useEffect(()=>{d.setOptions(c)},[c,d]),Ie(c,f))throw Le(c,d,o);if(Pe({result:f,errorResetBoundary:o,throwOnError:c.throwOnError,query:l,suspense:c.suspense}))throw f.error;return c.notifyOnChangeProps?f:d.trackResult(f)}function P(e,t){return Re(e,be,t)}function F(e,t){let i=n(t),[o]=N.useState(()=>new Ee(i,e));N.useEffect(()=>{o.setOptions(e)},[o,e]);let s=N.useSyncExternalStore(N.useCallback(e=>o.subscribe(p.batchCalls(e)),[o]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),c=N.useCallback((...e)=>{o.mutate(e[0],e[1]).catch(a)},[o]);if(s.error&&r(o.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:c,mutateAsync:s.mutate}}var ze=E({key:D(),provider:D(),id:D(),name:D(),version:D().optional(),reasoning:T(),input:w(_([`text`,`image`])),contextWindow:C().optional(),maxTokens:C().optional(),available:T(),defaultThinkingLevel:j.optional(),thinkingLevels:w(j).optional()}).openapi({description:`Chat model info`}),Be=E({models:w(ze),selectedModelKey:D().optional(),defaultProvider:D().optional(),defaultModel:D().optional(),defaultThinkingLevel:j.optional(),diagnostics:w(D())}).openapi({description:`Chat models response`}),Ve=E({providerId:D().min(1).max(128)}).openapi({description:`Discover models for a provider`}),He=E({providerId:D(),models:w(ze)}).openapi({description:`Discovered models for a provider`}),I=E({activationStatus:_([`active`,`staged`,`reload-required`]).optional(),name:D(),description:D().optional(),installedInWorkspace:T().optional(),path:D().optional(),source:D().optional(),workspacePath:D().optional(),argumentHint:D().optional()}).openapi({description:`Chat resource info`}),Ue=E({packages:w(I),skills:w(I),prompts:w(I),extensions:w(I),themes:w(I),agentsFiles:w(I),diagnostics:w(D())}).openapi({description:`Chat resources response`}),We=b(()=>E({name:D(),path:D(),type:_([`directory`,`file`]),children:w(We).optional()})),Ge=E({root:D(),nodes:w(We),diagnostics:w(D())}).openapi({description:`Workspace tree response`}),Ke=E({path:D(),name:D(),content:D(),mediaType:_([`text/markdown`,`text/plain`,`application/octet-stream`]),size:C().optional(),status:_([`ok`,`too-large`,`unsupported`]).optional()}).openapi({description:`Workspace file preview response`}),qe=E({name:D(),path:D()}).openapi({description:`Directory entry in the project-folder picker`});E({path:D(),parent:D().nullable(),entries:w(qe)}).openapi({description:`Workspace directory browse response`});var L=E({id:D(),name:D(),isConfigured:T(),envVarName:D(),authType:_([`apiKey`,`oauth`]).optional(),supportsOAuth:T().optional(),providerFamily:D().optional(),displayName:D().optional(),api:_([`openai-completions`,`openai-responses`,`anthropic-messages`,`google-genai`]).optional(),baseUrl:D().optional(),modelIds:w(D().max(4096)).max(64).optional(),discoverable:T().optional()}).openapi({description:`Chat provider info`}),Je=E({providers:w(L)}).openapi({description:`Chat providers response`}),Ye=E({providerId:D(),apiKey:D().max(4096),baseUrl:D().max(4096).optional(),modelId:D().max(4096).optional(),displayName:D().max(256).optional(),createOccInstance:T().optional(),api:_([`openai-completions`,`openai-responses`,`anthropic-messages`,`google-genai`]).optional(),models:w(D().max(4096)).max(64).optional()}).openapi({description:`Chat provider update request`}),R=E({success:T(),providers:w(L),reloadRequired:T().optional()}).openapi({description:`Chat provider update response`}),Xe=E({providerId:D()}).openapi({description:`Chat provider remove request`});R.openapi({description:`Chat provider remove response`});var Ze=_([`waiting`,`success`,`error`]).openapi({description:`OAuth login status`}),Qe=E({message:D(),placeholder:D().optional(),allowEmpty:T().optional()}).openapi({description:`Interactive OAuth prompt`});E({providerId:D().min(1),loginId:D().min(1).optional(),promptAnswer:D().max(8192).optional(),cancel:T().optional()}).openapi({description:`Chat provider OAuth login request`}),E({status:Ze,loginId:D().optional(),authUrl:D().optional(),userCode:D().optional(),instructions:D().optional(),prompt:Qe.optional(),error:D().optional(),providers:w(L).optional()}).openapi({description:`Chat provider OAuth login response`});var $e=E({name:D(),description:D().optional(),argumentHint:D().optional(),source:_([`builtin`,`extension`,`prompt`,`skill`]),passThrough:T().optional()}).openapi({description:`Chat slash command info`}),et=E({commands:w($e),diagnostics:w(D())}).openapi({description:`Chat slash commands response`}),tt=_([`session`,`corpus`]).openapi({description:`Where a completion came from: this session or another session`});_([`append`,`replace`]).openapi({description:`Whether accepting appends the completion or replaces the draft with it`}),E({text:O.max(2e3),sessionId:O.max(200).optional(),projectId:ie.optional()}).openapi({description:`Composer ghost-text completion request`}),E({completion:D().min(1).max(2e3).optional(),confidence:C().min(0).max(1).optional(),source:tt.optional()}).openapi({description:`Composer ghost-text completion from history; a verbatim string that always extends the draft, never model prose`});var nt=_([`unconfigured`,`unverified`,`ready`,`error`]).openapi({description:`Coarse readiness of the optional composer intent classifier`}),rt=_([`disabled`,`not_ready`,`empty`,`no_match`,`code_task`,`below_floor`,`unavailable`,`rate_limited`]).openapi({description:`Why a routing attempt produced no action`}),it=_([`settings`,`environment`,`none`]).openapi({description:`Which key the classifier is using; never the key itself`}),at=_([`execute`,`suggest`]).openapi({description:`Whether a matched command may run automatically or is only offered`});E({text:O.max(2e3),projectId:ie.optional()}).openapi({description:`Composer free-text intent routing request`}),E({enabled:T(),outcome:_([`none`,`matched`]),command:D().min(1).max(64).optional(),confidence:C().min(0).max(1).optional(),disposition:at.optional(),reason:rt.optional(),model:D().max(120).optional(),latencyMs:C().nonnegative().optional()}).openapi({description:`Composer intent routing decision; never carries model prose or error text`}),E({enabled:T(),status:nt,keySource:it}).openapi({description:`Composer intent routing availability; never reveals the key or a raw error`}),E({apiKey:O.max(400).nullable()}).openapi({description:`Set or clear the stored classifier key; write-only`}),E({enabled:T()}).openapi({description:`Enable or disable composer intent routing`});var ot=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,st=/^[A-Za-z_][A-Za-z0-9_]*$/,z=D().regex(ot,`MCP server names must be 1-64 letters, numbers, underscores, or hyphens and start with a letter or number.`),B=D().regex(st,`Environment variable names must be letters, digits, or underscores.`),ct=_([`builtin`,`user`]),lt=_([`http`,`stdio`]),ut=_([`connected`,`needs_auth`,`disabled`,`anonymous`]),dt=E({child:B,source:B}).openapi({description:`Stdio env mapping as CHILD=SOURCE variable names only`}),V=E({name:z,label:O,source:ct,transport:lt,url:D().optional(),commandPreview:D().optional(),cwdPreview:D().optional(),usesOAuth:T(),enabled:T(),status:ut,acceptsPastedToken:T().optional(),bearerTokenEnvVar:D().optional(),envBindings:w(dt).optional(),error:D().optional()}).openapi({description:`Browser-safe MCP connection row; never includes tokens or env values`}),H=E({connections:w(V)}).openapi({description:`MCP connection list`}),ft=E({name:z,transport:S(`http`),url:O,oauth:T().optional(),bearerTokenEnvVar:B.optional(),force:T().optional()}),pt=E({name:z,transport:S(`stdio`),command:O,args:w(D().min(1).max(1024)).max(32).optional(),cwd:D().min(1).max(1024).optional(),env:w(dt).max(32).optional(),force:T().optional()}),mt=re(`transport`,[ft,pt]).openapi({description:`Add or replace a user MCP server`}),ht=E({name:z}).openapi({description:`Remove a user MCP server`}),gt=_([`login`,`logout`,`reconnect`]),_t=E({name:z,action:gt.optional(),loginId:D().min(1).optional(),promptAnswer:D().max(8192).optional(),cancel:T().optional()}).openapi({description:`MCP OAuth login, logout, or reconnect`});E({name:z,token:D().min(1).max(8192)}).openapi({description:`Store an MCP server token`}),E({verified:T(),toolCount:C().int().nonnegative().nullable(),error:D().optional(),connections:w(V)}).openapi({description:`MCP token storage result`});var vt=E({status:Ze,loginId:D().optional(),authUrl:D().optional(),userCode:D().optional(),instructions:D().optional(),prompt:Qe.optional(),error:D().optional(),connections:w(V).optional()}).openapi({description:`MCP OAuth login snapshot`});E({message:D()}).openapi({description:`Error response`}),E({status:S(`ok`)}).openapi({description:`Health check response`});var yt=_([`user`,`assistant`,`system`,`unknown`]),bt=_([`message`,`system`,`other`]),xt=b(()=>E({id:D().min(1),parentId:D().min(1).optional(),kind:bt,role:yt.optional(),label:D(),preview:D(),isLeaf:T(),isOnActiveBranch:T(),messageIndex:C().int().nonnegative().optional(),children:w(xt)}).openapi({description:`Browser-safe session tree node`})),St=E({sessionId:y,leafId:D().min(1).nullable(),nodes:w(xt)}).openapi({description:`Session entry tree snapshot for the active branch and branches`}),Ct=E({snapshot:St}).openapi({description:`Session tree read response`}),wt=E({sessionId:y,targetEntryId:D().min(1).max(256),expectedLeafId:D().min(1).max(256).optional()}).openapi({description:`Navigate the live session tree to an earlier entry`}),Tt=E({snapshot:St}).openapi({description:`Session tree navigate response with authoritative snapshot`}),Et=O.max(1024),U=w(Et),W=U.max(100),Dt=E({source:O,extensions:w(O).optional(),skills:w(O).optional(),prompts:w(O).optional(),themes:w(O).optional()}),Ot=x([O,Dt]),G=w(Ot),kt=G.max(100),K=E({compaction:E({enabled:T(),reserveTokens:_e,keepRecentTokens:_e}),defaultModel:D().optional(),defaultProvider:D().optional(),defaultThinkingLevel:j.optional(),enableSkillCommands:T(),enabledModels:w(O).optional(),extensions:U,followUpMode:M,packages:G,prompts:U,retry:E({enabled:T(),maxRetries:oe,baseDelayMs:oe}),skills:U,steeringMode:M,themes:U,transport:k}).openapi({description:`Editable Pi settings`}),At=E({compaction:K.shape.compaction.partial().optional(),defaultModel:D().optional(),defaultProvider:D().optional(),defaultThinkingLevel:j.optional(),enableSkillCommands:T().optional(),enabledModels:w(O).nullable().optional(),extensions:W.optional(),followUpMode:M.optional(),packages:kt.optional(),prompts:W.optional(),retry:K.shape.retry.partial().optional(),skills:W.optional(),steeringMode:M.optional(),themes:W.optional(),transport:k.optional()}).strict().openapi({description:`Pi settings update`}),jt=E({compaction:K.shape.compaction.partial().optional(),defaultModel:D().optional(),defaultProvider:D().optional(),defaultThinkingLevel:j.optional(),enableSkillCommands:T().optional(),enabledModels:w(O).nullable().optional(),extensions:U.optional(),followUpMode:M.optional(),packages:G.optional(),prompts:U.optional(),retry:K.shape.retry.partial().optional(),skills:U.optional(),steeringMode:M.optional(),themes:U.optional(),transport:k.optional()}).strict(),Mt=E({settings:At}).openapi({description:`Pi settings update request`}),Nt=E({diagnostics:w(D()),effective:K,project:jt,projectPath:D(),updateImpact:E({newSessionRecommended:T(),resourceReloadRequired:T()})}).openapi({description:`Pi settings response`}),Pt=[`/api/health`,`/api/chat`,`/api/projects`,`/api/workspace`];function Ft(){return``}function It(e){return Pt.some(t=>e===t||e.startsWith(`${t}?`)||e.startsWith(`${t}/`))}function q(e){let t=Ft();if(!t)return e;let[n]=e.split(`?`);return It(n)?`${t}${e}`:e}var Lt=class extends Error{constructor(){super(`The chat stream received an invalid event. The response may still be running; reload the conversation to refresh it.`),this.name=`ChatStreamContractError`}},J=class extends Error{status;body;code;remediation;constructor(e,t){super(Bt(e,t)),this.name=`ChatRequestError`,this.status=e,this.body=t;let n=zt(t);this.code=n?.code,this.remediation=n?.remediation}};function Rt(e){return typeof e==`object`&&!!e&&typeof e.action==`string`&&typeof e.label==`string`}function zt(e){let t=e.trim();if(!t)return null;try{let e=JSON.parse(t);if(typeof e.code==`string`)return{code:e.code,remediation:Rt(e.remediation)?e.remediation:void 0}}catch{}return null}function Bt(e,t){let n=t.trim();if(!n)return`Request failed (${e})`;try{let e=JSON.parse(n);if(typeof e.message==`string`&&e.message.length>0)return e.message}catch{}return n}function Vt(e){return(e instanceof J?e.body:e instanceof Error?e.message:String(e)).includes(`Session belongs to another user`)}function Ht(e){return e instanceof J&&e.status===404}function Ut(e){return e instanceof Error?e.code===`NETWORK_DISCONNECTED`||/daemon is not connected/i.test(e.message)||/cannot send daemon command/i.test(e.message):!1}function Wt(e){let t=Error(e.message);return e.code&&(t.code=e.code),t}async function Y(e,t){let n=q(e),r=new Headers(t?.headers),i=await fetch(n,{...t,headers:r});if(!i.ok){let e=await i.text();throw new J(i.status,e)}return await i.json()}async function X(e,t,n){return Kt(t,await Y(e,n),`Response from ${e}`)}async function Gt(e,t){let n=e.body?.getReader();if(!n)throw Error(`Chat response did not include a stream`);let r=new TextDecoder,i=``,a=new Map;function o(e,t,n){let r=a.get(`${e}:${t}`)??0;n>r+1&&console.warn(`[chat-sequence] Gap detected in ${t} sequence for session ${e}: expected ${r+1}, got ${n}`),a.set(`${e}:${t}`,n)}let s=e=>{let n=e.trim();if(!n)return;let r;try{r=JSON.parse(n)}catch{throw console.error(`[chat-stream] Invalid NDJSON event {"type":"unknown","issues":["invalid_json:[root]"]}`),new Lt}let i=typeof r==`object`&&r?`type`in r&&r.type:void 0,a=typeof r==`object`&&r&&`sessionId`in r?String(r.sessionId):void 0,s=typeof r==`object`&&r&&`sequenceNumber`in r?Number(r.sequenceNumber):void 0;if(i===`start`||i===`done`||i===`error`||i===`plan`||i===`state`||i===`tool`||i===`queue`||i===`reasoning`||i===`reasoning_text`||i===`compaction`||i===`retry`||i===`payload`||i===`session_snapshot`){let e=Kt(le,r,`Chat stream event`);a&&s!==void 0&&o(a,String(e.type),s),t(e)}else t(r)};try{for(;;){let{value:e,done:t}=await n.read();if(t)break;let a=r.decode(e,{stream:!0});i+=a;let o=i.indexOf(`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{D as n,S as r,T as i,_ as a,b as o,c as s,d as c,i as l,l as u,m as d,n as f,o as p,s as m,w as h,x as g,y as ee}from"./mutation-Da9zdeWr.js";import{t as te}from"./jsx-runtime-NZYk81nU.js";import{A as _,C as v,D as y,F as b,H as x,I as S,L as C,M as w,N as T,O as ne,P as re,R as E,S as ie,T as ae,V as D,_ as oe,a as se,b as ce,f as le,g as O,h as k,i as ue,l as A,m as j,n as de,o as fe,p as M,r as pe,s as me,t as he,u as ge,v as _e,w as ve,x as ye}from"./chat-hpzV6IA6.js";var be=class extends s{#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),Se(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ce(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ce(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 o(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&&!g(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&we(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||o(this.options.enabled,this.#t)!==o(t.enabled,this.#t)||o(this.options.staleTime,this.#t)!==o(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||o(this.options.enabled,this.#t)!==o(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 g(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().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(a)),t}#h(e){return!u()&&o(this.options.enabled,this.#t)!==!1&&d(e)}#g(){this.#b();let e=o(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=h(this.#r.dataUpdatedAt,e)+1;this.#u=i.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return o(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,!(this.#f===0||!this.#h(this.#f))&&(this.#d=i.setInterval(()=>{(this.options.refetchIntervalInBackground||m.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(i.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(i.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,s=this.#a,c=e===n?this.#n:e.state,{state:u}=e,d={...u},f=!1,p;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Se(e,t),o=i&&we(e,n,t,r);(a||o)&&(d={...d,...l(u.data,e.options)}),t._optimisticResults===`isRestoring`&&(d.fetchStatus=`idle`)}let{error:m,errorUpdatedAt:h,status:g}=d;p=d.data;let te=!1;if(t.placeholderData!==void 0&&p===void 0&&g===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(e=i.data,te=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(g=`success`,p=ee(i?.data,e,t),f=!0)}if(t.select&&p!==void 0&&!te){if(i&&p===a?.data&&t.select===this.#s)p=this.#c;else try{this.#s=t.select,p=t.select(p),p=ee(i?.data,p,t),this.#c=p,this.#o=null}catch(e){this.#o=e}}else p===void 0&&(this.#o=null);this.#o&&(m=this.#o,p=this.#c,h=Date.now(),g=`error`,f=!1);let _=d.fetchStatus===`fetching`,v=g===`pending`,y=g===`error`,b=v&&_,x=p!==void 0;return{status:g,fetchStatus:d.fetchStatus,isPending:v,isSuccess:g===`success`,isError:y,isInitialLoading:b,isLoading:b,data:p,dataUpdatedAt:d.dataUpdatedAt,error:m,errorUpdatedAt:h,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>c.dataUpdateCount||d.errorUpdateCount>c.errorUpdateCount,isFetching:_,isRefetching:_&&!v,isLoadingError:y&&!x,isPaused:d.fetchStatus===`paused`,isPlaceholderData:f,isRefetchError:y&&x,isStale:Te(e,t),refetch:this.refetch,isEnabled:o(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),g(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)})})();p.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 xe(e,t){return o(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||o(t.retryOnMount,e)!==!1)}function Se(e,t){return xe(e,t)||e.state.data!==void 0&&Ce(e,t,t.refetchOnMount)}function Ce(e,t,n){if(o(t.enabled,e)!==!1&&o(t.staleTime,e)!==`static`){let r=o(n,e);return r===`always`||r!==!1&&Te(e,t)}return!1}function we(e,t,n,r){return(e!==t||o(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Te(e,n)}function Te(e,t){return o(t.enabled,e)!==!1&&e.isStaleByTime(o(t.staleTime,e))}var Ee=class extends s{#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),g(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&c(t.mutationKey)!==c(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??f();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){p.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)})})}},N=e(t(),1),De=N.createContext(!1),Oe=()=>N.useContext(De);De.Provider,te();function ke(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ae=N.createContext(ke()),je=()=>N.useContext(Ae),Me=(e,t,n)=>{let i=n?.state.error&&typeof e.throwOnError==`function`?r(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||i)&&(t.isReset()||(e.retryOnMount=!1))},Ne=e=>{N.useEffect(()=>{e.clearReset()},[e])},Pe=({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:a})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(a&&e.data===void 0||r(n,[e.error,i])),Fe=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))}},Ie=(e,t)=>e?.suspense&&t.isPending,Le=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Re(e,t,r){let i=Oe(),o=je(),s=n(r),c=s.defaultQueryOptions(e),l=s.getQueryCache().get(c.queryHash),u=e.subscribed!==!1;c._optimisticResults=i?`isRestoring`:u?`optimistic`:void 0,Fe(c),Me(c,o,l),Ne(o);let[d]=N.useState(()=>new t(s,c)),f=d.getOptimisticResult(c),m=!i&&u;if(N.useSyncExternalStore(N.useCallback(e=>{let t=m?d.subscribe(p.batchCalls(e)):a;return d.updateResult(),t},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),N.useEffect(()=>{d.setOptions(c)},[c,d]),Ie(c,f))throw Le(c,d,o);if(Pe({result:f,errorResetBoundary:o,throwOnError:c.throwOnError,query:l,suspense:c.suspense}))throw f.error;return c.notifyOnChangeProps?f:d.trackResult(f)}function P(e,t){return Re(e,be,t)}function F(e,t){let i=n(t),[o]=N.useState(()=>new Ee(i,e));N.useEffect(()=>{o.setOptions(e)},[o,e]);let s=N.useSyncExternalStore(N.useCallback(e=>o.subscribe(p.batchCalls(e)),[o]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),c=N.useCallback((...e)=>{o.mutate(e[0],e[1]).catch(a)},[o]);if(s.error&&r(o.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:c,mutateAsync:s.mutate}}var ze=E({key:D(),provider:D(),id:D(),name:D(),version:D().optional(),reasoning:T(),input:w(_([`text`,`image`])),contextWindow:C().optional(),maxTokens:C().optional(),available:T(),defaultThinkingLevel:j.optional(),thinkingLevels:w(j).optional()}).openapi({description:`Chat model info`}),Be=E({models:w(ze),selectedModelKey:D().optional(),defaultProvider:D().optional(),defaultModel:D().optional(),defaultThinkingLevel:j.optional(),diagnostics:w(D())}).openapi({description:`Chat models response`}),Ve=E({providerId:D().min(1).max(128)}).openapi({description:`Discover models for a provider`}),He=E({providerId:D(),error:D().optional(),models:w(ze)}).openapi({description:`Discovered models for a provider`}),I=E({activationStatus:_([`active`,`staged`,`reload-required`]).optional(),name:D(),description:D().optional(),installedInWorkspace:T().optional(),path:D().optional(),source:D().optional(),workspacePath:D().optional(),argumentHint:D().optional()}).openapi({description:`Chat resource info`}),Ue=E({packages:w(I),skills:w(I),prompts:w(I),extensions:w(I),themes:w(I),agentsFiles:w(I),diagnostics:w(D())}).openapi({description:`Chat resources response`}),We=b(()=>E({name:D(),path:D(),type:_([`directory`,`file`]),children:w(We).optional()})),Ge=E({root:D(),nodes:w(We),diagnostics:w(D())}).openapi({description:`Workspace tree response`}),Ke=E({path:D(),name:D(),content:D(),mediaType:_([`text/markdown`,`text/plain`,`application/octet-stream`]),size:C().optional(),status:_([`ok`,`too-large`,`unsupported`]).optional()}).openapi({description:`Workspace file preview response`}),qe=E({name:D(),path:D()}).openapi({description:`Directory entry in the project-folder picker`});E({path:D(),parent:D().nullable(),entries:w(qe)}).openapi({description:`Workspace directory browse response`});var L=E({id:D(),name:D(),isConfigured:T(),envVarName:D(),authType:_([`apiKey`,`oauth`]).optional(),supportsOAuth:T().optional(),providerFamily:D().optional(),displayName:D().optional(),api:_([`openai-completions`,`openai-responses`,`anthropic-messages`,`google-genai`]).optional(),baseUrl:D().optional(),modelIds:w(D().max(4096)).max(64).optional(),discoverable:T().optional()}).openapi({description:`Chat provider info`}),Je=E({providers:w(L)}).openapi({description:`Chat providers response`}),Ye=E({providerId:D(),apiKey:D().max(4096),baseUrl:D().max(4096).optional(),modelId:D().max(4096).optional(),displayName:D().max(256).optional(),createOccInstance:T().optional(),api:_([`openai-completions`,`openai-responses`,`anthropic-messages`,`google-genai`]).optional(),models:w(D().max(4096)).max(64).optional()}).openapi({description:`Chat provider update request`}),R=E({success:T(),providers:w(L),reloadRequired:T().optional()}).openapi({description:`Chat provider update response`}),Xe=E({providerId:D()}).openapi({description:`Chat provider remove request`});R.openapi({description:`Chat provider remove response`});var Ze=_([`waiting`,`success`,`error`]).openapi({description:`OAuth login status`}),Qe=E({message:D(),placeholder:D().optional(),allowEmpty:T().optional()}).openapi({description:`Interactive OAuth prompt`});E({providerId:D().min(1),loginId:D().min(1).optional(),promptAnswer:D().max(8192).optional(),cancel:T().optional()}).openapi({description:`Chat provider OAuth login request`}),E({status:Ze,loginId:D().optional(),authUrl:D().optional(),userCode:D().optional(),instructions:D().optional(),prompt:Qe.optional(),error:D().optional(),providers:w(L).optional()}).openapi({description:`Chat provider OAuth login response`});var $e=E({name:D(),description:D().optional(),argumentHint:D().optional(),source:_([`builtin`,`extension`,`prompt`,`skill`]),passThrough:T().optional()}).openapi({description:`Chat slash command info`}),et=E({commands:w($e),diagnostics:w(D())}).openapi({description:`Chat slash commands response`}),tt=_([`session`,`corpus`]).openapi({description:`Where a completion came from: this session or another session`});_([`append`,`replace`]).openapi({description:`Whether accepting appends the completion or replaces the draft with it`}),E({text:O.max(2e3),sessionId:O.max(200).optional(),projectId:ie.optional()}).openapi({description:`Composer ghost-text completion request`}),E({completion:D().min(1).max(2e3).optional(),confidence:C().min(0).max(1).optional(),source:tt.optional()}).openapi({description:`Composer ghost-text completion from history; a verbatim string that always extends the draft, never model prose`});var nt=_([`unconfigured`,`unverified`,`ready`,`error`]).openapi({description:`Coarse readiness of the optional composer intent classifier`}),rt=_([`disabled`,`not_ready`,`empty`,`no_match`,`code_task`,`below_floor`,`unavailable`,`rate_limited`]).openapi({description:`Why a routing attempt produced no action`}),it=_([`settings`,`environment`,`none`]).openapi({description:`Which key the classifier is using; never the key itself`}),at=_([`execute`,`suggest`]).openapi({description:`Whether a matched command may run automatically or is only offered`});E({text:O.max(2e3),projectId:ie.optional()}).openapi({description:`Composer free-text intent routing request`}),E({enabled:T(),outcome:_([`none`,`matched`]),command:D().min(1).max(64).optional(),confidence:C().min(0).max(1).optional(),disposition:at.optional(),reason:rt.optional(),model:D().max(120).optional(),latencyMs:C().nonnegative().optional()}).openapi({description:`Composer intent routing decision; never carries model prose or error text`}),E({enabled:T(),status:nt,keySource:it}).openapi({description:`Composer intent routing availability; never reveals the key or a raw error`}),E({apiKey:O.max(400).nullable()}).openapi({description:`Set or clear the stored classifier key; write-only`}),E({enabled:T()}).openapi({description:`Enable or disable composer intent routing`});var ot=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,st=/^[A-Za-z_][A-Za-z0-9_]*$/,z=D().regex(ot,`MCP server names must be 1-64 letters, numbers, underscores, or hyphens and start with a letter or number.`),B=D().regex(st,`Environment variable names must be letters, digits, or underscores.`),ct=_([`builtin`,`user`]),lt=_([`http`,`stdio`]),ut=_([`connected`,`needs_auth`,`disabled`,`anonymous`]),dt=E({child:B,source:B}).openapi({description:`Stdio env mapping as CHILD=SOURCE variable names only`}),V=E({name:z,label:O,source:ct,transport:lt,url:D().optional(),commandPreview:D().optional(),cwdPreview:D().optional(),usesOAuth:T(),enabled:T(),status:ut,acceptsPastedToken:T().optional(),bearerTokenEnvVar:D().optional(),envBindings:w(dt).optional(),error:D().optional()}).openapi({description:`Browser-safe MCP connection row; never includes tokens or env values`}),H=E({connections:w(V)}).openapi({description:`MCP connection list`}),ft=E({name:z,transport:S(`http`),url:O,oauth:T().optional(),bearerTokenEnvVar:B.optional(),force:T().optional()}),pt=E({name:z,transport:S(`stdio`),command:O,args:w(D().min(1).max(1024)).max(32).optional(),cwd:D().min(1).max(1024).optional(),env:w(dt).max(32).optional(),force:T().optional()}),mt=re(`transport`,[ft,pt]).openapi({description:`Add or replace a user MCP server`}),ht=E({name:z}).openapi({description:`Remove a user MCP server`}),gt=_([`login`,`logout`,`reconnect`]),_t=E({name:z,action:gt.optional(),loginId:D().min(1).optional(),promptAnswer:D().max(8192).optional(),cancel:T().optional()}).openapi({description:`MCP OAuth login, logout, or reconnect`});E({name:z,token:D().min(1).max(8192)}).openapi({description:`Store an MCP server token`}),E({verified:T(),toolCount:C().int().nonnegative().nullable(),error:D().optional(),connections:w(V)}).openapi({description:`MCP token storage result`});var vt=E({status:Ze,loginId:D().optional(),authUrl:D().optional(),userCode:D().optional(),instructions:D().optional(),prompt:Qe.optional(),error:D().optional(),connections:w(V).optional()}).openapi({description:`MCP OAuth login snapshot`});E({message:D()}).openapi({description:`Error response`}),E({status:S(`ok`)}).openapi({description:`Health check response`});var yt=_([`user`,`assistant`,`system`,`unknown`]),bt=_([`message`,`system`,`other`]),xt=b(()=>E({id:D().min(1),parentId:D().min(1).optional(),kind:bt,role:yt.optional(),label:D(),preview:D(),isLeaf:T(),isOnActiveBranch:T(),messageIndex:C().int().nonnegative().optional(),children:w(xt)}).openapi({description:`Browser-safe session tree node`})),St=E({sessionId:y,leafId:D().min(1).nullable(),nodes:w(xt)}).openapi({description:`Session entry tree snapshot for the active branch and branches`}),Ct=E({snapshot:St}).openapi({description:`Session tree read response`}),wt=E({sessionId:y,targetEntryId:D().min(1).max(256),expectedLeafId:D().min(1).max(256).optional()}).openapi({description:`Navigate the live session tree to an earlier entry`}),Tt=E({snapshot:St}).openapi({description:`Session tree navigate response with authoritative snapshot`}),Et=O.max(1024),U=w(Et),W=U.max(100),Dt=E({source:O,extensions:w(O).optional(),skills:w(O).optional(),prompts:w(O).optional(),themes:w(O).optional()}),Ot=x([O,Dt]),G=w(Ot),kt=G.max(100),K=E({compaction:E({enabled:T(),reserveTokens:_e,keepRecentTokens:_e}),defaultModel:D().optional(),defaultProvider:D().optional(),defaultThinkingLevel:j.optional(),enableSkillCommands:T(),enabledModels:w(O).optional(),extensions:U,followUpMode:M,packages:G,prompts:U,retry:E({enabled:T(),maxRetries:oe,baseDelayMs:oe}),skills:U,steeringMode:M,themes:U,transport:k}).openapi({description:`Editable Pi settings`}),At=E({compaction:K.shape.compaction.partial().optional(),defaultModel:D().optional(),defaultProvider:D().optional(),defaultThinkingLevel:j.optional(),enableSkillCommands:T().optional(),enabledModels:w(O).nullable().optional(),extensions:W.optional(),followUpMode:M.optional(),packages:kt.optional(),prompts:W.optional(),retry:K.shape.retry.partial().optional(),skills:W.optional(),steeringMode:M.optional(),themes:W.optional(),transport:k.optional()}).strict().openapi({description:`Pi settings update`}),jt=E({compaction:K.shape.compaction.partial().optional(),defaultModel:D().optional(),defaultProvider:D().optional(),defaultThinkingLevel:j.optional(),enableSkillCommands:T().optional(),enabledModels:w(O).nullable().optional(),extensions:U.optional(),followUpMode:M.optional(),packages:G.optional(),prompts:U.optional(),retry:K.shape.retry.partial().optional(),skills:U.optional(),steeringMode:M.optional(),themes:U.optional(),transport:k.optional()}).strict(),Mt=E({settings:At}).openapi({description:`Pi settings update request`}),Nt=E({diagnostics:w(D()),effective:K,project:jt,projectPath:D(),updateImpact:E({newSessionRecommended:T(),resourceReloadRequired:T()})}).openapi({description:`Pi settings response`}),Pt=[`/api/health`,`/api/chat`,`/api/projects`,`/api/workspace`];function Ft(){return``}function It(e){return Pt.some(t=>e===t||e.startsWith(`${t}?`)||e.startsWith(`${t}/`))}function q(e){let t=Ft();if(!t)return e;let[n]=e.split(`?`);return It(n)?`${t}${e}`:e}var Lt=class extends Error{constructor(){super(`The chat stream received an invalid event. The response may still be running; reload the conversation to refresh it.`),this.name=`ChatStreamContractError`}},J=class extends Error{status;body;code;remediation;constructor(e,t){super(Bt(e,t)),this.name=`ChatRequestError`,this.status=e,this.body=t;let n=zt(t);this.code=n?.code,this.remediation=n?.remediation}};function Rt(e){return typeof e==`object`&&!!e&&typeof e.action==`string`&&typeof e.label==`string`}function zt(e){let t=e.trim();if(!t)return null;try{let e=JSON.parse(t);if(typeof e.code==`string`)return{code:e.code,remediation:Rt(e.remediation)?e.remediation:void 0}}catch{}return null}function Bt(e,t){let n=t.trim();if(!n)return`Request failed (${e})`;try{let e=JSON.parse(n);if(typeof e.message==`string`&&e.message.length>0)return e.message}catch{}return n}function Vt(e){return(e instanceof J?e.body:e instanceof Error?e.message:String(e)).includes(`Session belongs to another user`)}function Ht(e){return e instanceof J&&e.status===404}function Ut(e){return e instanceof Error?e.code===`NETWORK_DISCONNECTED`||/daemon is not connected/i.test(e.message)||/cannot send daemon command/i.test(e.message):!1}function Wt(e){let t=Error(e.message);return e.code&&(t.code=e.code),t}async function Y(e,t){let n=q(e),r=new Headers(t?.headers),i=await fetch(n,{...t,headers:r});if(!i.ok){let e=await i.text();throw new J(i.status,e)}return await i.json()}async function X(e,t,n){return Kt(t,await Y(e,n),`Response from ${e}`)}async function Gt(e,t){let n=e.body?.getReader();if(!n)throw Error(`Chat response did not include a stream`);let r=new TextDecoder,i=``,a=new Map;function o(e,t,n){let r=a.get(`${e}:${t}`)??0;n>r+1&&console.warn(`[chat-sequence] Gap detected in ${t} sequence for session ${e}: expected ${r+1}, got ${n}`),a.set(`${e}:${t}`,n)}let s=e=>{let n=e.trim();if(!n)return;let r;try{r=JSON.parse(n)}catch{throw console.error(`[chat-stream] Invalid NDJSON event {"type":"unknown","issues":["invalid_json:[root]"]}`),new Lt}let i=typeof r==`object`&&r?`type`in r&&r.type:void 0,a=typeof r==`object`&&r&&`sessionId`in r?String(r.sessionId):void 0,s=typeof r==`object`&&r&&`sequenceNumber`in r?Number(r.sequenceNumber):void 0;if(i===`start`||i===`done`||i===`error`||i===`plan`||i===`state`||i===`tool`||i===`queue`||i===`reasoning`||i===`reasoning_text`||i===`compaction`||i===`retry`||i===`payload`||i===`session_snapshot`){let e=Kt(le,r,`Chat stream event`);a&&s!==void 0&&o(a,String(e.type),s),t(e)}else t(r)};try{for(;;){let{value:e,done:t}=await n.read();if(t)break;let a=r.decode(e,{stream:!0});i+=a;let o=i.indexOf(`
2
2
  `);for(;o>=0;)s(i.slice(0,o)),i=i.slice(o+1),o=i.indexOf(`
3
3
  `)}i+=r.decode(),s(i)}catch(e){throw await n.cancel().catch(()=>void 0),e}finally{n.releaseLock()}}function Kt(e,t,n){let r=e.safeParse(t);if(r.success)return r.data;if(n===`Chat stream event`||n===`Subagent chat stream event`){let e=new Set([`start`,`done`,`error`,`plan`,`state`,`tool`,`queue`,`reasoning`,`reasoning_text`,`compaction`,`retry`,`payload`,`session_snapshot`,`delta`,`message`,`thinking`,`presentation`,`rlm`]),n=new Set(`type.part.message.messages.parts.id.role.text.state.name.phase.status.sessionId.runId.messageId.toolCallId.toolName.input.output.result.error.code.presentation.revision.sequenceNumber.contentIndex.terminal.session.queue.payload.category.reasoning.steps.durationMs.createdAt.requestKind.data.content`.split(`.`)),i=(e,t=[])=>e.flatMap(e=>{let r=[...t,...e.path??[]];if(e.code===`invalid_union`&&e.errors)return e.errors.filter(e=>!e.some(e=>e.code===`invalid_value`&&e.path?.[0]===`type`)).flatMap(e=>i(e,r));let a=r.map(e=>typeof e==`number`?`[]`:typeof e==`string`&&n.has(e)?e:`[field]`).join(`.`);return[`${e.code??`invalid`}:${a||`[root]`}`]}),a=typeof t==`object`&&t&&`type`in t&&typeof t.type==`string`&&e.has(t.type)?t.type:`unknown`;throw console.error(`[chat-stream] Invalid event ${JSON.stringify({type:a,issues:i(r.error.issues).slice(0,12)})}`),new Lt}throw Error(`${n} did not match the expected contract`)}function qt(e){let t=new URLSearchParams;return e.sessionId&&t.set(`sessionId`,e.sessionId),e.projectId&&t.set(`projectId`,e.projectId),e.openUI&&t.set(`openUI`,`true`),t.toString()}function Jt(e){switch(e){case`agent_start`:return`Working`;case`turn_start`:return`Waiting`;case`message_start`:return`Thinking`;case`message_end`:return`Writing`;case`tool_start`:case`tool_execution_start`:case`tool_execution`:return`Executing`;case`tool_end`:case`tool_execution_end`:return`Writing`;case`turn_end`:return`Turn finished`;case`agent_end`:return;default:return}}var Z=E({project:ae}),Q={async abortSession(e){await Y(`/api/chat/abort`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})},async answerQuestion(e){return X(`/api/chat/question`,se,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})},async mutateQueuedMessage(e){let t=fe.parse(e);return X(`/api/chat/session`,me,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})},async deleteQueuedMessage(e){return this.mutateQueuedMessage({...e,mutation:e.mutation??{type:`delete`}})},async createSession(e,t){return X(`/api/chat/new`,A,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({openUI:!0,...e?{projectId:e}:{}}),signal:t})},async listProjects(){return X(`/api/projects`,v)},async createProject(e){let t=ce.parse(e);return(await X(`/api/projects`,Z,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).project},async renameProject(e,t){let n=ve.parse({name:t});return(await X(`/api/projects?projectId=${encodeURIComponent(e)}`,Z,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})).project},async unregisterProject(e){return(await X(`/api/projects?projectId=${encodeURIComponent(e)}`,Z,{method:`DELETE`})).project},async browseProjectDirectories(e){let t=new URLSearchParams;e?.path&&t.set(`path`,e.path),e?.token&&t.set(`token`,e.token);let n=t.toString();return X(`/api/projects/browse${n?`?${n}`:``}`,ye)},async getModels(e){let t=new URLSearchParams;e?.scope===`all`&&t.set(`scope`,`all`),e?.projectId&&t.set(`projectId`,e.projectId);let n=t.toString();return X(`/api/chat/models${n?`?${n}`:``}`,Be)},async discoverModels(e){return X(`/api/chat/models/discover`,He,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Ve.parse(e))})},async getResources(e){return X(`/api/chat/resources${e?`?projectId=${encodeURIComponent(e)}`:``}`,Ue)},async getCommands(e){return X(`/api/chat/commands${e?`?projectId=${encodeURIComponent(e)}`:``}`,et)},async getSettings(e){return X(`/api/chat/settings${e?`?projectId=${encodeURIComponent(e)}`:``}`,Nt)},async getWorkspaceTree(e){return X(`/api/workspace/tree${e?`?projectId=${encodeURIComponent(e)}`:``}`,Ge)},async getWorkspaceFile(e,t,n){let r=new URLSearchParams({path:e});return t&&r.set(`projectId`,t),X(`/api/workspace/file?${r}`,Ke,n?{signal:n}:void 0)},async listSessions(e){return(await X(`/api/chat/sessions${e?`?projectId=${encodeURIComponent(e)}`:``}`,ge)).sessions},async renameSession(e,t){await Y(`/api/chat/sessions`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:e,title:t})})},async deleteSession(e){await Y(`/api/chat/sessions`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:e})})},async uploadAttachments(e,t){let n=new FormData;n.set(`sessionId`,e);for(let e of t)n.append(`files`,e);let r=await fetch(q(`/api/chat/session`),{method:`POST`,body:n});if(!r.ok)throw new J(r.status,await r.text());return E({attachments:w(ne)}).parse(await r.json()).attachments},async getSessionTree(e){return X(`/api/chat/session-tree?${new URLSearchParams({sessionId:e})}`,Ct).then(e=>e.snapshot)},async navigateSessionTree(e){let t=wt.parse(e);return X(`/api/chat/session-tree`,Tt,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}).then(e=>e.snapshot)},async loadSession(e){return X(`/api/chat/session?${qt({...e,openUI:!0})}`,A)},async loadSubagentSession(e,t){return X(`/api/chat/session?${new URLSearchParams({parentSessionId:e,childId:t})}`,A)},openSubagentEvents(e,t,n){let r=new URLSearchParams({parentSessionId:e,childId:t});return n?.streamGeneration&&r.set(`streamGeneration`,n.streamGeneration),n?.lastEventId&&n.lastEventId>0&&r.set(`lastEventId`,String(n.lastEventId)),q(`/api/chat/events?${r}`)},async upsertPlanPresentation(e){let t=ue.parse(e);return X(`/api/chat/session`,E({presentation:pe}),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}).then(e=>e.presentation)},async upsertOpenUIArtifact(e){let t=he.parse(e);return X(`/api/chat/artifacts`,de,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})},async resumeSession(e){return X(`/api/chat/resume`,A,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,openUI:!0})})},async updateSettings(e,t){let n=Mt.parse(e);return X(`/api/chat/settings${t?`?projectId=${encodeURIComponent(t)}`:``}`,Nt,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})},async streamMessage(e,t,n){let r=await fetch(q(`/api/chat`),{method:`POST`,headers:new Headers({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:n});if(!r.ok){let e=await r.text();throw new J(r.status,e)}await Gt(r,t)},async getMcpConnections(){return X(`/api/chat/mcp`,H)},async upsertMcpConnection(e){let t=mt.parse(e);return X(`/api/chat/mcp`,H,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})},async removeMcpConnection(e){let t=ht.parse(e);return X(`/api/chat/mcp`,H,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})},async mcpOAuth(e){let t=_t.parse(e);return X(`/api/chat/mcp/oauth`,vt,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})},async getProviders(){return X(`/api/chat/providers`,Je)},async updateProvider(e){let t=Ye.parse(e);return X(`/api/chat/providers`,R,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})},async removeProvider(e){let t=Xe.parse(e);return X(`/api/chat/providers`,R,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}},Yt={models:e=>[`chat`,`models`,e??`default`],modelCatalog:e=>[`chat`,`models`,`catalog`,e??`default`],providers:[`chat`,`providers`],mcp:[`chat`,`mcp`],resources:e=>[`chat`,`resources`,e??`default`],commands:e=>[`chat`,`commands`,e??`default`],settings:e=>[`chat`,`settings`,e??`default`],workspace:e=>[`workspace`,`tree`,e??`default`],projects:[`projects`]},$=Yt;function Xt(e){return P({queryKey:$.models(e),queryFn:()=>Q.getModels({projectId:e}),enabled:!!e})}function Zt(){return P({queryKey:$.projects,queryFn:()=>Q.listProjects(),staleTime:5e3})}function Qt(e){return P({queryKey:$.modelCatalog(e?.projectId),queryFn:()=>Q.getModels({scope:`all`,projectId:e?.projectId}),enabled:!!e?.projectId&&e?.enabled!==!1})}function $t(){let e=n();return F({mutationFn:e=>Q.discoverModels({providerId:e}),onSuccess:()=>{e.invalidateQueries({queryKey:[`chat`,`models`]})}})}function en(e){return P({queryKey:$.resources(e),queryFn:()=>Q.getResources(e),enabled:!!e})}function tn(e){return P({queryKey:$.commands(e),queryFn:()=>Q.getCommands(e),enabled:!!e})}function nn(e){return P({queryKey:$.settings(e),queryFn:()=>Q.getSettings(e),enabled:!!e})}function rn(){let e=n();return F({mutationFn:e=>Q.updateSettings(e.request,e.projectId),onSuccess:(t,n)=>{e.setQueryData($.settings(n.projectId),t),e.invalidateQueries({queryKey:[`chat`,`models`]}),e.invalidateQueries({queryKey:[`chat`,`resources`]}),e.invalidateQueries({queryKey:[`chat`,`commands`]})}})}function an(e,t){return P({queryKey:$.workspace(e),queryFn:()=>Q.getWorkspaceTree(e),enabled:!!e&&t?.enabled!==!1})}function on(){return P({queryKey:$.mcp,queryFn:()=>Q.getMcpConnections()})}function sn(){let e=n();return F({mutationFn:e=>Q.upsertMcpConnection(e),onSuccess:t=>{e.setQueryData($.mcp,t),e.invalidateQueries({queryKey:[`chat`,`resources`]})}})}function cn(){let e=n();return F({mutationFn:e=>Q.removeMcpConnection(e),onSuccess:t=>{e.setQueryData($.mcp,t),e.invalidateQueries({queryKey:[`chat`,`resources`]})}})}function ln(){let e=n();return F({mutationFn:e=>Q.mcpOAuth(e),onSuccess:t=>{t.status!==`success`||!t.connections||(e.setQueryData($.mcp,{connections:t.connections}),e.invalidateQueries({queryKey:[`chat`,`resources`]}))}})}function un(){return P({queryKey:$.providers,queryFn:()=>Q.getProviders()})}function dn(){let e=n();return F({mutationFn:e=>Q.updateProvider(e),onSuccess:t=>{e.setQueryData($.providers,{providers:t.providers}),e.invalidateQueries({queryKey:[`chat`,`models`]}),e.invalidateQueries({queryKey:[`chat`,`settings`]})}})}function fn(){let e=n();return F({mutationFn:e=>Q.removeProvider(e),onSuccess:t=>{e.setQueryData($.providers,{providers:t.providers}),e.invalidateQueries({queryKey:[`chat`,`models`]}),e.invalidateQueries({queryKey:[`chat`,`settings`]})}})}export{Vt as C,q as D,Kt as E,P as O,Ut as S,Jt as T,an as _,Xt as a,Wt as b,en as c,ln as d,fn as f,sn as g,rn as h,Qt as i,nn as l,dn as m,tn as n,Zt as o,cn as p,on as r,un as s,Yt as t,$t as u,Q as v,Ht as w,Y as x,Lt as y};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/connectors-page-DQJdoAnl.js","assets/jsx-runtime-NZYk81nU.js","assets/rolldown-runtime-hePW80VL.js","assets/chat-queries-CfZiupub.js","assets/react-Cvdyeg_0.js","assets/mutation-Da9zdeWr.js","assets/with-selector-B_VDO56x.js","assets/chat-hpzV6IA6.js","assets/mcp-connections-section-DEo6Kemv.js","assets/utils-oBThwhjm.js","assets/select-DYh951qi.js","assets/react-dom-B7th3XGm.js","assets/useButton-CvcmqA2s.js","assets/createBaseUIEventDetails-DIxvaz-Y.js","assets/FloatingPortal-D8-EPDs2.js","assets/useScrollLock-BcsteNzT.js","assets/useBaseUiId-lKfDDIcw.js","assets/check-BTwIaCtI.js","assets/createLucideIcon-CQY2ECfR.js","assets/chevron-down-Bse1ggZM.js","assets/input-CBoTMPC_.js","assets/useControlled-CkQSkSv1.js","assets/surfaces-BUjUJTyD.js","assets/loader-circle-BmKYM_C4.js","assets/plug-wCz-036u.js","assets/plus-DUP2JPVG.js","assets/rotate-ccw-DLkfsmG9.js","assets/trash-sm2UyOxe.js","assets/button-CWYjn8Zk.js","assets/dist-BogNzeK9.js","assets/clsx-DB0hHKMi.js","assets/alert-CzWGeumf.js","assets/switch-BrxDfsX6.js","assets/tokens-DinEQBG4.js","assets/spinner-B5TaKP7k.js","assets/notify-BIL0-CGy.js","assets/toast-BNWkgZ0u.js","assets/circle-check-DBhaebaM.js","assets/triangle-alert-BuzmrrqI.js","assets/x-DEU6H3M-.js","assets/product-page-header-Ck6I13CE.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{t as r}from"./preload-helper-BLdHbfdN.js";var i=e(t()),a=n(),o=(0,i.lazy)(()=>r(async()=>{let{ConnectorsPage:e}=await import(`./connectors-page-DQJdoAnl.js`);return{ConnectorsPage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40])).then(({ConnectorsPage:e})=>({default:e})));function s(){return(0,a.jsx)(`main`,{className:`min-h-svh bg-background p-8`,children:(0,a.jsx)(`p`,{className:`mx-auto max-w-5xl text-sm text-muted-foreground`,children:`Loading connectors…`})})}var c=()=>(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(s,{}),children:(0,a.jsx)(o,{})});export{c as component};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/connectors-page-CDzzjCIJ.js","assets/jsx-runtime-NZYk81nU.js","assets/rolldown-runtime-hePW80VL.js","assets/chat-queries-ty76G6rK.js","assets/react-Cvdyeg_0.js","assets/mutation-Da9zdeWr.js","assets/with-selector-B_VDO56x.js","assets/chat-hpzV6IA6.js","assets/mcp-connections-section-BsNhp1b2.js","assets/utils-oBThwhjm.js","assets/select-DYh951qi.js","assets/react-dom-B7th3XGm.js","assets/useButton-CvcmqA2s.js","assets/createBaseUIEventDetails-DIxvaz-Y.js","assets/FloatingPortal-D8-EPDs2.js","assets/useScrollLock-BcsteNzT.js","assets/useBaseUiId-lKfDDIcw.js","assets/check-BTwIaCtI.js","assets/createLucideIcon-CQY2ECfR.js","assets/chevron-down-Bse1ggZM.js","assets/input-CBoTMPC_.js","assets/useControlled-CkQSkSv1.js","assets/surfaces-BUjUJTyD.js","assets/loader-circle-BmKYM_C4.js","assets/plug-wCz-036u.js","assets/plus-DUP2JPVG.js","assets/rotate-ccw-DLkfsmG9.js","assets/trash-sm2UyOxe.js","assets/button-CWYjn8Zk.js","assets/dist-BogNzeK9.js","assets/clsx-DB0hHKMi.js","assets/alert-CzWGeumf.js","assets/switch-BrxDfsX6.js","assets/tokens-DinEQBG4.js","assets/spinner-B5TaKP7k.js","assets/notify-BIL0-CGy.js","assets/toast-BNWkgZ0u.js","assets/circle-check-DBhaebaM.js","assets/triangle-alert-BuzmrrqI.js","assets/x-DEU6H3M-.js","assets/product-page-header-Ck6I13CE.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-Cvdyeg_0.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{t as r}from"./preload-helper-BLdHbfdN.js";var i=e(t()),a=n(),o=(0,i.lazy)(()=>r(async()=>{let{ConnectorsPage:e}=await import(`./connectors-page-CDzzjCIJ.js`);return{ConnectorsPage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40])).then(({ConnectorsPage:e})=>({default:e})));function s(){return(0,a.jsx)(`main`,{className:`min-h-svh bg-background p-8`,children:(0,a.jsx)(`p`,{className:`mx-auto max-w-5xl text-sm text-muted-foreground`,children:`Loading connectors…`})})}var c=()=>(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(s,{}),children:(0,a.jsx)(o,{})});export{c as component};
@@ -1 +1 @@
1
- import{t as e}from"./jsx-runtime-NZYk81nU.js";import{d as t,g as n,p as r,r as i}from"./chat-queries-CfZiupub.js";import{t as a}from"./mcp-connections-section-DEo6Kemv.js";import{t as o}from"./product-page-header-Ck6I13CE.js";import{n as s,r as c,t as l}from"./alert-CzWGeumf.js";var u=e();function d(){let e=i(),d=n(),f=r(),p=t();return(0,u.jsxs)(`main`,{className:`min-h-svh bg-background`,children:[(0,u.jsx)(o,{active:`connectors`}),(0,u.jsxs)(`div`,{className:`mx-auto flex w-full max-w-5xl flex-col gap-6 px-5 py-10 sm:px-8`,children:[(0,u.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Connectors`}),e.isError?(0,u.jsxs)(l,{variant:`destructive`,children:[(0,u.jsx)(c,{children:`Could not load connectors`}),(0,u.jsx)(s,{children:e.error.message})]}):null,(0,u.jsx)(a,{connections:e.data?.connections??[],description:`Connect Model Context Protocol (MCP) servers. For bearer sign-in, enter the name of the server's environment variable that contains your secret. You cannot enter the secret here.`,isLoading:e.isLoading,isPending:d.isPending||f.isPending||p.isPending,onOAuth:e=>p.mutateAsync(e),onRemove:e=>f.mutateAsync(e),onUpsert:e=>d.mutateAsync(e),title:`Servers`})]})]})}export{d as ConnectorsPage};
1
+ import{t as e}from"./jsx-runtime-NZYk81nU.js";import{d as t,g as n,p as r,r as i}from"./chat-queries-ty76G6rK.js";import{t as a}from"./mcp-connections-section-BsNhp1b2.js";import{t as o}from"./product-page-header-Ck6I13CE.js";import{n as s,r as c,t as l}from"./alert-CzWGeumf.js";var u=e();function d(){let e=i(),d=n(),f=r(),p=t();return(0,u.jsxs)(`main`,{className:`min-h-svh bg-background`,children:[(0,u.jsx)(o,{active:`connectors`}),(0,u.jsxs)(`div`,{className:`mx-auto flex w-full max-w-5xl flex-col gap-6 px-5 py-10 sm:px-8`,children:[(0,u.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Connectors`}),e.isError?(0,u.jsxs)(l,{variant:`destructive`,children:[(0,u.jsx)(c,{children:`Could not load connectors`}),(0,u.jsx)(s,{children:e.error.message})]}):null,(0,u.jsx)(a,{connections:e.data?.connections??[],description:`Connect Model Context Protocol (MCP) servers. For bearer sign-in, enter the name of the server's environment variable that contains your secret. You cannot enter the secret here.`,isLoading:e.isLoading,isPending:d.isPending||f.isPending||p.isPending,onOAuth:e=>p.mutateAsync(e),onRemove:e=>f.mutateAsync(e),onUpsert:e=>d.mutateAsync(e),title:`Servers`})]})]})}export{d as ConnectorsPage};