cartethyia 2.5.8 → 2.5.10

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 (157) hide show
  1. package/.env.example +7 -42
  2. package/README.md +11 -10
  3. package/dist/dashboard/assets/{BannedPage-BKAI54IA.js → BannedPage-Cd30Z0b9.js} +1 -1
  4. package/dist/dashboard/assets/BannedPage-Cd30Z0b9.js.gz +0 -0
  5. package/dist/dashboard/assets/{CliToolDetailPage-CkGvxrHu.js → CliToolDetailPage-wf5u-ww6.js} +1 -1
  6. package/dist/dashboard/assets/CliToolDetailPage-wf5u-ww6.js.gz +0 -0
  7. package/dist/dashboard/assets/{CliToolsPage-Cj8MYpeY.js → CliToolsPage-DykPvuck.js} +1 -1
  8. package/dist/dashboard/assets/CliToolsPage-DykPvuck.js.gz +0 -0
  9. package/dist/dashboard/assets/{CombosPage-BDXBEbWT.js → CombosPage-DwvSD3vs.js} +1 -1
  10. package/dist/dashboard/assets/CombosPage-DwvSD3vs.js.gz +0 -0
  11. package/dist/dashboard/assets/{ConsoleLogPage-49KH4z3l.js → ConsoleLogPage-CIr7KDex.js} +1 -1
  12. package/dist/dashboard/assets/ConsoleLogPage-CIr7KDex.js.gz +0 -0
  13. package/dist/dashboard/assets/{CustomizationPage-EHjBmNBZ.js → CustomizationPage-82X0DDdH.js} +1 -1
  14. package/dist/dashboard/assets/CustomizationPage-82X0DDdH.js.gz +0 -0
  15. package/dist/dashboard/assets/{HealthEventsModal-ByUTtj7j.js → HealthEventsModal-BYPucTTn.js} +1 -1
  16. package/dist/dashboard/assets/HealthEventsModal-BYPucTTn.js.gz +0 -0
  17. package/dist/dashboard/assets/{LoginPage-CYSCKT8S.js → LoginPage-CS5mPuVF.js} +1 -1
  18. package/dist/dashboard/assets/LoginPage-CS5mPuVF.js.gz +0 -0
  19. package/dist/dashboard/assets/{ModelPicker-C7pDb41R.js → ModelPicker-C0UCUsVJ.js} +1 -1
  20. package/dist/dashboard/assets/ModelPicker-C0UCUsVJ.js.gz +0 -0
  21. package/dist/dashboard/assets/{OverviewPage-Bu3iqBMm.js → OverviewPage-Dk_ew3YU.js} +1 -1
  22. package/dist/dashboard/assets/OverviewPage-Dk_ew3YU.js.gz +0 -0
  23. package/dist/dashboard/assets/{ProviderDetailPage-FHdgmgjU.js → ProviderDetailPage-CAiRn2Q0.js} +1 -1
  24. package/dist/dashboard/assets/ProviderDetailPage-CAiRn2Q0.js.gz +0 -0
  25. package/dist/dashboard/assets/{ProvidersPage-CCvYS9CF.js → ProvidersPage-vdja5ZPK.js} +1 -1
  26. package/dist/dashboard/assets/ProvidersPage-vdja5ZPK.js.gz +0 -0
  27. package/dist/dashboard/assets/{ProxyPage-HOl9cjxl.js → ProxyPage-BB4CNm4-.js} +1 -1
  28. package/dist/dashboard/assets/ProxyPage-BB4CNm4-.js.gz +0 -0
  29. package/dist/dashboard/assets/{QuotaPage-MUGzIpTK.js → QuotaPage-FEc4iNyq.js} +1 -1
  30. package/dist/dashboard/assets/QuotaPage-FEc4iNyq.js.gz +0 -0
  31. package/dist/dashboard/assets/{SettingsPage-CTdF5TCa.js → SettingsPage-Dlfi5L4N.js} +1 -1
  32. package/dist/dashboard/assets/SettingsPage-Dlfi5L4N.js.gz +0 -0
  33. package/dist/dashboard/assets/{SetupPage-Bra7rkKx.js → SetupPage-FadUOl9S.js} +1 -1
  34. package/dist/dashboard/assets/SetupPage-FadUOl9S.js.gz +0 -0
  35. package/dist/dashboard/assets/{SortableList-BRscd-vl.js → SortableList-Cfy6_Khv.js} +1 -1
  36. package/dist/dashboard/assets/SortableList-Cfy6_Khv.js.gz +0 -0
  37. package/dist/dashboard/assets/{StudioPage-BeevnFtM.js → StudioPage-CM92fgJf.js} +1 -1
  38. package/dist/dashboard/assets/StudioPage-CM92fgJf.js.gz +0 -0
  39. package/dist/dashboard/assets/{UsagePage-BWik9fpu.js → UsagePage-BT4MyQeT.js} +1 -1
  40. package/dist/dashboard/assets/UsagePage-BT4MyQeT.js.gz +0 -0
  41. package/dist/dashboard/assets/{app-BIt446yE.js → app-B7pVRhJ1.js} +1 -1
  42. package/dist/dashboard/assets/{app-BIt446yE.js.gz → app-B7pVRhJ1.js.gz} +0 -0
  43. package/dist/dashboard/assets/{badge-CR72dasT.js → badge-Bvyr7D0u.js} +1 -1
  44. package/dist/dashboard/assets/badge-Bvyr7D0u.js.gz +0 -0
  45. package/dist/dashboard/assets/{banner-CI9_eSfO.js → banner-DIvKAZih.js} +1 -1
  46. package/dist/dashboard/assets/banner-DIvKAZih.js.gz +0 -0
  47. package/dist/dashboard/assets/{card-DS7CQEsO.js → card-D5_gYIS_.js} +1 -1
  48. package/dist/dashboard/assets/card-D5_gYIS_.js.gz +0 -0
  49. package/dist/dashboard/assets/{clipboard-button-611pSsaX.js → clipboard-button-B6vDBtbm.js} +1 -1
  50. package/dist/dashboard/assets/clipboard-button-B6vDBtbm.js.gz +0 -0
  51. package/dist/dashboard/assets/{dialog-k37exjNt.js → dialog-CpjrgdwJ.js} +1 -1
  52. package/dist/dashboard/assets/dialog-CpjrgdwJ.js.gz +0 -0
  53. package/dist/dashboard/assets/{drawer-CX7N8ucR.js → drawer-BWmt3b5y.js} +1 -1
  54. package/dist/dashboard/assets/drawer-BWmt3b5y.js.gz +0 -0
  55. package/dist/dashboard/assets/{entry-B9Xvtnfj.js → entry-B-gvimrg.js} +1 -1
  56. package/dist/dashboard/assets/entry-B-gvimrg.js.gz +0 -0
  57. package/dist/dashboard/assets/{entry-CTP8AyiS.js → entry-C_oakV3z.js} +1 -1
  58. package/dist/dashboard/assets/entry-C_oakV3z.js.gz +0 -0
  59. package/dist/dashboard/assets/{entry-BqZ5vrM7.js → entry-Dj0cHfEc.js} +3 -3
  60. package/dist/dashboard/assets/entry-Dj0cHfEc.js.gz +0 -0
  61. package/dist/dashboard/assets/{github-badge-sltk1qUi.js → github-badge-RRHHWGxh.js} +1 -1
  62. package/dist/dashboard/assets/github-badge-RRHHWGxh.js.gz +0 -0
  63. package/dist/dashboard/assets/{index-9ARd3FIs.js → index-Bhey_rg_.js} +2 -2
  64. package/dist/dashboard/assets/index-Bhey_rg_.js.gz +0 -0
  65. package/dist/dashboard/assets/{inline-BhY2sSnO.js → inline-C2_EQ5Uf.js} +1 -1
  66. package/dist/dashboard/assets/inline-C2_EQ5Uf.js.gz +0 -0
  67. package/dist/dashboard/assets/{input-V1umFiBk.js → input-BMRlQ450.js} +1 -1
  68. package/dist/dashboard/assets/input-BMRlQ450.js.gz +0 -0
  69. package/dist/dashboard/assets/{layout-BBOYycyS.js → layout-XR5xP8ew.js} +1 -1
  70. package/dist/dashboard/assets/layout-XR5xP8ew.js.gz +0 -0
  71. package/dist/dashboard/assets/{list-row-1zzZYM0B.js → list-row-Cw07dioc.js} +1 -1
  72. package/dist/dashboard/assets/list-row-Cw07dioc.js.gz +0 -0
  73. package/dist/dashboard/assets/{numbers-DkfMR5Qs.js → numbers-DrdA9oSM.js} +1 -1
  74. package/dist/dashboard/assets/numbers-DrdA9oSM.js.gz +0 -0
  75. package/dist/dashboard/assets/{select-D_BBhBEF.js → select-CxVVB__N.js} +1 -1
  76. package/dist/dashboard/assets/select-CxVVB__N.js.gz +0 -0
  77. package/dist/dashboard/assets/{stack-BHTfXdz_.js → stack-uPOwM9Hs.js} +1 -1
  78. package/dist/dashboard/assets/stack-uPOwM9Hs.js.gz +0 -0
  79. package/dist/dashboard/assets/{state-mPDRlQkl.js → state-D1Yz79iL.js} +1 -1
  80. package/dist/dashboard/assets/state-D1Yz79iL.js.gz +0 -0
  81. package/dist/dashboard/assets/{switch-DOmJxg7H.js → switch-sevsRrRo.js} +1 -1
  82. package/dist/dashboard/assets/switch-sevsRrRo.js.gz +0 -0
  83. package/dist/dashboard/index.html +1 -1
  84. package/dist/dashboard/index.html.gz +0 -0
  85. package/dist/dashboard/precompressed-assets.json +40 -40
  86. package/package.json +1 -3
  87. package/scripts/cli/admin.ts +3 -0
  88. package/scripts/cli/console-menu.ts +299 -275
  89. package/scripts/cli/doctor.ts +1 -1
  90. package/scripts/cli/gateway.ts +1 -2
  91. package/scripts/{health.ts → cli/health.ts} +4 -4
  92. package/scripts/cli/main.ts +3 -0
  93. package/scripts/cli/prompt.ts +137 -107
  94. package/scripts/cli/start.ts +3 -0
  95. package/scripts/cli/tray.ts +167 -208
  96. package/src/config/package-paths.ts +24 -0
  97. package/src/console/backup/nine-router.ts +43 -9
  98. package/src/console/remote-support/service.ts +270 -114
  99. package/src/console/routing/pools/store.ts +1 -1
  100. package/src/console/updates/repository-updates.ts +40 -39
  101. package/src/observability/event-day-index.ts +1 -2
  102. package/src/protocol/registry.ts +2 -0
  103. package/src/providers/default-registry.ts +4 -0
  104. package/src/providers/discovery/openrouter-free-roster.ts +0 -1
  105. package/src/providers/integrations/buddy/buddy-catalog-shared.ts +3 -2
  106. package/src/providers/integrations/buddy/capabilities.ts +4 -0
  107. package/src/providers/integrations/buddy/codebuddy/cn-provider.ts +2 -1
  108. package/src/providers/integrations/github/github.ts +3 -1
  109. package/src/providers/integrations/opencode/provider.ts +2 -3
  110. package/src/providers/integrations/trae/trae-headers.ts +17 -48
  111. package/src/providers/integrations/trae/trae.ts +22 -24
  112. package/src/providers/operations/provider-credential-service.ts +29 -3
  113. package/src/providers/provider-probe.ts +3 -0
  114. package/dist/dashboard/assets/BannedPage-BKAI54IA.js.gz +0 -0
  115. package/dist/dashboard/assets/CliToolDetailPage-CkGvxrHu.js.gz +0 -0
  116. package/dist/dashboard/assets/CliToolsPage-Cj8MYpeY.js.gz +0 -0
  117. package/dist/dashboard/assets/CombosPage-BDXBEbWT.js.gz +0 -0
  118. package/dist/dashboard/assets/ConsoleLogPage-49KH4z3l.js.gz +0 -0
  119. package/dist/dashboard/assets/CustomizationPage-EHjBmNBZ.js.gz +0 -0
  120. package/dist/dashboard/assets/HealthEventsModal-ByUTtj7j.js.gz +0 -0
  121. package/dist/dashboard/assets/LoginPage-CYSCKT8S.js.gz +0 -0
  122. package/dist/dashboard/assets/ModelPicker-C7pDb41R.js.gz +0 -0
  123. package/dist/dashboard/assets/OverviewPage-Bu3iqBMm.js.gz +0 -0
  124. package/dist/dashboard/assets/ProviderDetailPage-FHdgmgjU.js.gz +0 -0
  125. package/dist/dashboard/assets/ProvidersPage-CCvYS9CF.js.gz +0 -0
  126. package/dist/dashboard/assets/ProxyPage-HOl9cjxl.js.gz +0 -0
  127. package/dist/dashboard/assets/QuotaPage-MUGzIpTK.js.gz +0 -0
  128. package/dist/dashboard/assets/SettingsPage-CTdF5TCa.js.gz +0 -0
  129. package/dist/dashboard/assets/SetupPage-Bra7rkKx.js.gz +0 -0
  130. package/dist/dashboard/assets/SortableList-BRscd-vl.js.gz +0 -0
  131. package/dist/dashboard/assets/StudioPage-BeevnFtM.js.gz +0 -0
  132. package/dist/dashboard/assets/UsagePage-BWik9fpu.js.gz +0 -0
  133. package/dist/dashboard/assets/badge-CR72dasT.js.gz +0 -0
  134. package/dist/dashboard/assets/banner-CI9_eSfO.js.gz +0 -0
  135. package/dist/dashboard/assets/card-DS7CQEsO.js.gz +0 -0
  136. package/dist/dashboard/assets/clipboard-button-611pSsaX.js.gz +0 -0
  137. package/dist/dashboard/assets/dialog-k37exjNt.js.gz +0 -0
  138. package/dist/dashboard/assets/drawer-CX7N8ucR.js.gz +0 -0
  139. package/dist/dashboard/assets/entry-B9Xvtnfj.js.gz +0 -0
  140. package/dist/dashboard/assets/entry-BqZ5vrM7.js.gz +0 -0
  141. package/dist/dashboard/assets/entry-CTP8AyiS.js.gz +0 -0
  142. package/dist/dashboard/assets/github-badge-sltk1qUi.js.gz +0 -0
  143. package/dist/dashboard/assets/index-9ARd3FIs.js.gz +0 -0
  144. package/dist/dashboard/assets/inline-BhY2sSnO.js.gz +0 -0
  145. package/dist/dashboard/assets/input-V1umFiBk.js.gz +0 -0
  146. package/dist/dashboard/assets/layout-BBOYycyS.js.gz +0 -0
  147. package/dist/dashboard/assets/list-row-1zzZYM0B.js.gz +0 -0
  148. package/dist/dashboard/assets/numbers-DkfMR5Qs.js.gz +0 -0
  149. package/dist/dashboard/assets/select-D_BBhBEF.js.gz +0 -0
  150. package/dist/dashboard/assets/stack-BHTfXdz_.js.gz +0 -0
  151. package/dist/dashboard/assets/state-mPDRlQkl.js.gz +0 -0
  152. package/dist/dashboard/assets/switch-DOmJxg7H.js.gz +0 -0
  153. package/scripts/build/aot.ts +0 -143
  154. package/scripts/build/build.ts +0 -24
  155. package/scripts/build/compile.ts +0 -88
  156. package/scripts/build/restart.ts +0 -120
  157. package/scripts/build/start.ts +0 -25
@@ -1,275 +1,299 @@
1
- import { existsSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import { randomUUID } from "node:crypto";
5
- import { isNewerRelease } from "../../src/console/updates/version-compare";
6
- import { resolvePackagePath } from "../../src/config/package-paths";
7
- import { resolvePort } from "../../src/config/runtime";
8
- import { ensureDrainToken } from "./instance";
9
- import { attachGateway, stopAttachedGateway, type RunningGateway } from "./instance";
10
- import { startGateway } from "./gateway";
11
- import { stopGateway } from "./gateway";
12
- import { ENV_PATH, readEnvFile } from "./env";
13
- import { readInstalledVersion, readLatestPublishedVersion } from "./version";
14
- import { launchBackgroundWithStatus, openUrl } from "./background";
15
- import { chooseFromMenu, confirmByTyping, confirmStep } from "./prompt";
16
- import { renderWordmark } from "./wordmark";
17
- import { exportBackup, resetConsoleAccount } from "./admin";
18
- import { runDetachedUpdate } from "./update";
19
-
20
-
21
- /**
22
- * The default `carte` experience: start the gateway, then offer an arrow-key
23
- * menu. This needs no desktop environment, so it works over SSH, on a headless
24
- * box, and on Windows where the tray icon lands in the hidden-icons overflow
25
- * and is never seen. `carte --tray` opts into the icon instead.
26
- */
27
- export async function startMenu(): Promise<void> {
28
- // A fresh install has no config file yet, and the gateway refuses to boot
29
- // without CARTETHYIA_DB_MODE — which surfaced as a stack trace about a
30
- // missing database mode rather than "you have not set this up". Run setup
31
- // first, the way `carte` is expected to behave on a new install.
32
- const configured = existsSync(ENV_PATH) && (await readEnvFile(ENV_PATH)).CARTETHYIA_DB_MODE;
33
- if (!configured) {
34
- console.log(
35
- existsSync(ENV_PATH)
36
- ? "Cartethyia is missing its database mode. Starting setup.\n"
37
- : "Cartethyia is not set up yet. Starting setup.\n",
38
- );
39
- // Dynamic on purpose: `setup` pulls in the whole wizard and the database
40
- // mode resolver, and it is only reachable on a first run. A static import
41
- // would pay that cost on every `carte`, which is the one path that has to
42
- // stay fast.
43
- const { setup } = await import("./setup");
44
- await setup();
45
- const after = existsSync(ENV_PATH) ? (await readEnvFile(ENV_PATH)).CARTETHYIA_DB_MODE : undefined;
46
- if (!after) {
47
- console.error(
48
- `Setup did not record CARTETHYIA_DB_MODE in ${ENV_PATH}; run \`cartethyia setup\` and try again.`,
49
- );
50
- process.exitCode = 1;
51
- return;
52
- }
53
- process.env.CARTETHYIA_DB_MODE = after;
54
- }
55
-
56
- const port = resolvePort();
57
- const drainToken = ensureDrainToken();
58
- const dashboardUrl = `http://127.0.0.1:${port}/console`;
59
- const currentVersion = await readInstalledVersion();
60
-
61
- // Reattach without draining a healthy instance. A new child must either be
62
- // ready or produce its actionable failure before the menu is shown; otherwise
63
- // the UI offers gateway actions for a process that already exited.
64
- const attached = await attachGateway(port, drainToken);
65
- let startupError: unknown = null;
66
- const ready: Promise<Bun.Subprocess | null> = attached
67
- ? Promise.resolve(null)
68
- : startGateway(port, drainToken).catch((error: unknown) => {
69
- startupError = error;
70
- return null;
71
- });
72
- let gateway: Bun.Subprocess | null = null;
73
- const runningAttached: RunningGateway | null = attached;
74
- void ready.then((child) => {
75
- if (child === null) return;
76
- gateway = child;
77
- child.unref();
78
- }).catch((error: unknown) => {
79
- console.error(`The gateway did not start: ${error instanceof Error ? error.message : "unknown error"}`);
80
- });
81
-
82
- if (!attached) {
83
- await ready;
84
- if (startupError !== null) {
85
- const detail = startupError instanceof Error ? startupError.message : "unknown startup error";
86
- console.error(`The gateway did not start on port ${port}.\n${detail}`);
87
- console.error("Fix the reported issue, then run `carte` again.");
88
- process.exitCode = 1;
89
- return;
90
- }
91
- }
92
-
93
- let stopping = false;
94
- let handedOff = false;
95
- const shutDown = async (): Promise<void> => {
96
- if (stopping) return;
97
- stopping = true;
98
- const child = gateway ?? (await ready.catch(() => null));
99
- if (child) await stopGateway(child, port, drainToken);
100
- else if (runningAttached) await stopAttachedGateway(runningAttached, drainToken);
101
- };
102
- const detachAttached = (): void => {
103
- if (runningAttached !== null) stopping = true;
104
- };
105
- // Ctrl-C has to stop the gateway, and the drain endpoint cannot be called
106
- // from an exit path: it is async, and enquirer's own Ctrl-C handler calls
107
- // process.exit(130) while a prompt is live. So the gateway is a child in this
108
- // process group — a terminal's Ctrl-C signals the whole group, and the
109
- // gateway drains through the SIGINT handler it already has in src/main.ts —
110
- // and `process.on("exit")` is the synchronous backstop for every other way
111
- // this process can end (a closed terminal, a crash, a signal Bun cannot
112
- // deliver on Windows). That handler can only call synchronous APIs, which is
113
- // why it signals the child rather than awaiting the drain endpoint.
114
- // `handedOff` is set by "Hide to tray": the gateway is being given to a tray
115
- // that will own it, so this process must not kill it on the way out.
116
- process.on("exit", () => {
117
- if (stopping || handedOff || gateway === null || runningAttached !== null) return;
118
- try {
119
- gateway.kill();
120
- } catch {
121
- // Already gone; nothing to stop.
122
- }
123
- });
124
- const interrupt = async (): Promise<void> => {
125
- if (runningAttached !== null) {
126
- detachAttached();
127
- process.exit(0);
128
- }
129
- process.stdout.write("\u001b[2J\u001b[H");
130
- console.log("Stopping Cartethyia…");
131
- await shutDown();
132
- process.exit(0);
133
- };
134
- process.on("SIGTERM", () => void interrupt());
135
- process.on("SIGINT", () => void interrupt());
136
-
137
- let latestVersion = await readLatestPublishedVersion();
138
- let running = true;
139
-
140
- const header = [...renderWordmark(), `Cartethyia ${currentVersion} \u00b7 ${dashboardUrl}`];
141
-
142
- while (running) {
143
- const upToDate = latestVersion === null || !isNewerRelease(currentVersion, latestVersion);
144
- const updateLabel =
145
- latestVersion === null
146
- ? "Check for updates"
147
- : upToDate
148
- ? `Up to date (${currentVersion})`
149
- : `Update to ${latestVersion}`;
150
-
151
- // Anything that talks to the gateway waits for it to be listening; the menu
152
- // itself does not.
153
- const whenReady = async (): Promise<void> => {
154
- await ready.catch(() => undefined);
155
- };
156
-
157
- const actions: readonly (() => Promise<void>)[] = [
158
- async () => openUrl(dashboardUrl),
159
- async () => {
160
- // Deleting the console account is the only real password recovery:
161
- // /change-password needs the current password, and first-boot setup
162
- // only runs when no user exists. Removing the user puts the wizard
163
- // back. Providers, keys, and routing are untouched.
164
- console.log("");
165
- console.log("This deletes every console account and its sessions.");
166
- console.log("The next visit to /console asks you to create a new one.");
167
- console.log("Providers, API keys, and routing are not touched.");
168
- console.log("");
169
- if (!(await confirmStep("Continue with the reset?"))) {
170
- console.log("Cancelled.");
171
- return;
172
- }
173
- if (!(await confirmByTyping("RESET", "Confirm deleting the console account"))) {
174
- console.log("Cancelled.");
175
- return;
176
- }
177
- await whenReady();
178
- const status = await resetConsoleAccount(port, drainToken);
179
- console.log(
180
- status === 0
181
- ? `Console account removed. Open ${dashboardUrl} to create a new one.`
182
- : "Reset failed; see the gateway log.",
183
- );
184
- },
185
- async () => {
186
- // Export straight to the download directory. The console page asks for
187
- // the operator password, which is exactly the thing a locked-out
188
- // operator does not have; the CLI already runs as the OS user who owns
189
- // the database, so the loopback token is the whole gate.
190
- await whenReady();
191
- const result = await exportBackup(port, drainToken);
192
- if (result === null) return;
193
- console.log(
194
- `Backup written to ${result.path} (${(result.bytes / 1024).toFixed(1)} KiB, ${Object.keys(result.counts).length} tables).`,
195
- );
196
- console.log("Telemetry is not included: it is per-request history, not configuration.");
197
- },
198
- async () => {
199
- if (upToDate) return;
200
- // npm cannot replace this package's directory while this process is
201
- // running out of it: on Windows the rename fails with EBUSY and npm
202
- // exits 14. Even with the gateway stopped, the CLI itself is executing
203
- // from that directory, so an in-process install can never succeed.
204
- // Print the command and exit, the way 9router does.
205
- await shutDown();
206
- runDetachedUpdate();
207
- console.log("");
208
- console.log(`Update available: ${currentVersion} \u2192 ${latestVersion}`);
209
- console.log("Detached update started; this process will exit now.");
210
- console.log("Re-run `carte` after it finishes.");
211
- console.log("");
212
- running = false;
213
- process.exit(0);
214
- },
215
- async () => {
216
- // Drain first, then start the tray.
217
- //
218
- // The tray's own startup probe refuses to boot when the port is busy,
219
- // so starting it before this process has let go made it fail with
220
- // "already running on port" every time — while the menu still printed
221
- // that everything was running, because a detached child with no stdio
222
- // cannot report anything back. Releasing the port first is the fix, and
223
- // waiting on the child's signal is what stops the menu from claiming
224
- // success for a child that died.
225
- console.log("Stopping the gateway to free the port…");
226
- running = false;
227
- stopping = true;
228
- handedOff = true;
229
- await shutDown();
230
- console.log("Starting the tray in the background…");
231
- const signalPath = join(tmpdir(), `cartethyia-tray-menu-${process.pid}-${randomUUID()}.json`);
232
- try {
233
- const url = await launchBackgroundWithStatus(
234
- ["run", resolvePackagePath("scripts", "cli", "main.ts"), "tray"],
235
- { signalPath },
236
- );
237
- console.log(`Cartethyia is running in the background at ${url || dashboardUrl}.`);
238
- console.log("The tray icon owns it; use Exit there to stop it.");
239
- } catch (error) {
240
- handedOff = false;
241
- console.error(
242
- `Could not hand off to the tray: ${error instanceof Error ? error.message : "unknown error"}`,
243
- );
244
- console.error("Cartethyia is stopped. Start it again from this menu.");
245
- }
246
- },
247
- async () => {
248
- running = false;
249
- },
250
- ];
251
-
252
- const choice = await chooseFromMenu(header, [
253
- { kind: "action", label: "Open Console", hint: `browser \u00b7 ${dashboardUrl}` },
254
- { kind: "action", label: "Reset console password", hint: "deletes the account" },
255
- { kind: "action", label: "Backup", hint: "export config to Downloads" },
256
- { kind: "action", label: updateLabel, hint: upToDate ? "open the repository" : "installs now" },
257
- { kind: "action", label: "Hide to tray", hint: "keep the gateway running" },
258
- { kind: "rule" },
259
- { kind: "action", label: "Exit", hint: "stop the gateway" },
260
- ],
261
- );
262
- if (choice === -1) break;
263
- const action = actions[choice];
264
- if (action) await action();
265
- }
266
- // "Hide to tray" has already given the gateway to the tray. Draining here
267
- // would stop the very process the tray just adopted, which is why the menu
268
- // appeared to hand over a gateway that was not listening.
269
- if (handedOff) return;
270
- if (runningAttached !== null) {
271
- detachAttached();
272
- return;
273
- }
274
- await shutDown();
275
- }
1
+ import { existsSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { isNewerRelease } from "../../src/console/updates/version-compare";
6
+ import { resolvePackagePath } from "../../src/config/package-paths";
7
+ import { resolvePort } from "../../src/config/runtime";
8
+ import { ensureDrainToken } from "./instance";
9
+ import { attachGateway, stopAttachedGateway, type RunningGateway } from "./instance";
10
+ import { startGateway } from "./gateway";
11
+ import { stopGateway } from "./gateway";
12
+ import { ENV_PATH, readEnvFile } from "./env";
13
+ import { readInstalledVersion, readLatestPublishedVersion } from "./version";
14
+ import { launchBackgroundWithStatus, openUrl } from "./background";
15
+ import { chooseFromMenu, confirmByTyping, confirmStep, type MenuRow } from "./prompt";
16
+ import { renderWordmark } from "./wordmark";
17
+ import { exportBackup, resetConsoleAccount } from "./admin";
18
+ import { runDetachedUpdate } from "./update";
19
+
20
+
21
+ /**
22
+ * The default `carte` experience: start the gateway, then offer an arrow-key
23
+ * menu. This needs no desktop environment, so it works over SSH, on a headless
24
+ * box, and on Windows where the tray icon lands in the hidden-icons overflow
25
+ * and is never seen. `carte --tray` opts into the icon instead.
26
+ */
27
+ export async function startMenu(): Promise<void> {
28
+ // A fresh install has no config file yet, and the gateway refuses to boot
29
+ // without CARTETHYIA_DB_MODE — which surfaced as a stack trace about a
30
+ // missing database mode rather than "you have not set this up". Run setup
31
+ // first, the way `carte` is expected to behave on a new install.
32
+ const configured = existsSync(ENV_PATH) && (await readEnvFile(ENV_PATH)).CARTETHYIA_DB_MODE;
33
+ if (!configured) {
34
+ console.log(
35
+ existsSync(ENV_PATH)
36
+ ? "Cartethyia is missing its database mode. Starting setup.\n"
37
+ : "Cartethyia is not set up yet. Starting setup.\n",
38
+ );
39
+ // dynamic-import: `setup` pulls in the whole wizard and the database mode
40
+ // resolver, and it is only reachable on a first run. A static import
41
+ // would pay that cost on every `carte`, which is the one path that has
42
+ // to stay fast.
43
+ const { setup } = await import("./setup");
44
+ await setup();
45
+ const after = existsSync(ENV_PATH) ? (await readEnvFile(ENV_PATH)).CARTETHYIA_DB_MODE : undefined;
46
+ if (!after) {
47
+ console.error(
48
+ `Setup did not record CARTETHYIA_DB_MODE in ${ENV_PATH}; run \`cartethyia setup\` and try again.`,
49
+ );
50
+ process.exitCode = 1;
51
+ return;
52
+ }
53
+ process.env.CARTETHYIA_DB_MODE = after;
54
+ }
55
+
56
+ const port = resolvePort();
57
+ const drainToken = ensureDrainToken();
58
+ const dashboardUrl = `http://127.0.0.1:${port}/console`;
59
+ const currentVersion = await readInstalledVersion();
60
+
61
+ // Reattach without draining a healthy instance. A new child must either be
62
+ // ready or produce its actionable failure before the menu is shown; otherwise
63
+ // the UI offers gateway actions for a process that already exited.
64
+ const attached = await attachGateway(port, drainToken);
65
+ let startupError: unknown = null;
66
+ const ready: Promise<Bun.Subprocess | null> = attached
67
+ ? Promise.resolve(null)
68
+ : startGateway(port, drainToken).catch((error: unknown) => {
69
+ startupError = error;
70
+ return null;
71
+ });
72
+ let gateway: Bun.Subprocess | null = null;
73
+ const runningAttached: RunningGateway | null = attached;
74
+ void ready.then((child) => {
75
+ if (child === null) return;
76
+ gateway = child;
77
+ child.unref();
78
+ }).catch((error: unknown) => {
79
+ console.error(`The gateway did not start: ${error instanceof Error ? error.message : "unknown error"}`);
80
+ });
81
+
82
+ if (!attached) {
83
+ await ready;
84
+ if (startupError !== null) {
85
+ const detail = startupError instanceof Error ? startupError.message : "unknown startup error";
86
+ console.error(`The gateway did not start on port ${port}.\n${detail}`);
87
+ console.error("Fix the reported issue, then run `carte` again.");
88
+ process.exitCode = 1;
89
+ return;
90
+ }
91
+ }
92
+
93
+ let stopping = false;
94
+ let handedOff = false;
95
+ const shutDown = async (): Promise<void> => {
96
+ if (stopping) return;
97
+ stopping = true;
98
+ const child = gateway ?? (await ready.catch(() => null));
99
+ if (child) await stopGateway(child, port, drainToken);
100
+ else if (runningAttached) await stopAttachedGateway(runningAttached, drainToken);
101
+ };
102
+ const detachAttached = (): void => {
103
+ if (runningAttached !== null) stopping = true;
104
+ };
105
+ // Ctrl-C has to stop the gateway, and the drain endpoint cannot be called
106
+ // from an exit path: it is async, and enquirer's own Ctrl-C handler calls
107
+ // process.exit(130) while a prompt is live. So the gateway is a child in this
108
+ // process group — a terminal's Ctrl-C signals the whole group, and the
109
+ // gateway drains through the SIGINT handler it already has in src/main.ts —
110
+ // and `process.on("exit")` is the synchronous backstop for every other way
111
+ // this process can end (a closed terminal, a crash, a signal Bun cannot
112
+ // deliver on Windows). That handler can only call synchronous APIs, which is
113
+ // why it signals the child rather than awaiting the drain endpoint.
114
+ // `handedOff` is set by "Hide to tray": the gateway is being given to a tray
115
+ // that will own it, so this process must not kill it on the way out.
116
+ process.on("exit", () => {
117
+ if (stopping || handedOff || gateway === null || runningAttached !== null) return;
118
+ try {
119
+ gateway.kill();
120
+ } catch {
121
+ // Already gone; nothing to stop.
122
+ }
123
+ });
124
+ const interrupt = async (): Promise<void> => {
125
+ if (runningAttached !== null) {
126
+ detachAttached();
127
+ process.exit(0);
128
+ }
129
+ process.stdout.write("\u001b[2J\u001b[H");
130
+ console.log("Stopping Cartethyia…");
131
+ await shutDown();
132
+ process.exit(0);
133
+ };
134
+ process.on("SIGTERM", () => void interrupt());
135
+ process.on("SIGINT", () => void interrupt());
136
+
137
+ let latestVersion = await readLatestPublishedVersion();
138
+ let running = true;
139
+
140
+ while (running) {
141
+ const upToDate = latestVersion === null || !isNewerRelease(currentVersion, latestVersion);
142
+ // Header-line version checker. When something newer is published the line
143
+ // calls it out and the menu adds an `Update to X.Y.Z` row that the arrow
144
+ // keys land on by default — the operator still has to press Enter, so a
145
+ // reflex Enter cannot run an update by accident, but attention is on the
146
+ // action that matters.
147
+ const versionCheckerLine =
148
+ latestVersion === null
149
+ ? `Version Checker: ${currentVersion} \u00b7 could not reach the registry`
150
+ : upToDate
151
+ ? `Version Checker: ${currentVersion} \u00b7 up to date`
152
+ : `Version Checker: ${currentVersion} \u2192 ${latestVersion} available`;
153
+ const header = [
154
+ ...renderWordmark(),
155
+ `Cartethyia ${currentVersion} \u00b7 ${dashboardUrl}`,
156
+ versionCheckerLine,
157
+ "",
158
+ "Section menu",
159
+ ];
160
+
161
+ // Anything that talks to the gateway waits for it to be listening; the menu
162
+ // itself does not.
163
+ const whenReady = async (): Promise<void> => {
164
+ await ready.catch(() => undefined);
165
+ };
166
+
167
+ const actions: readonly (() => Promise<void>)[] = [
168
+ async () => openUrl(dashboardUrl),
169
+ async () => {
170
+ // Drain first, then start the tray.
171
+ //
172
+ // The tray's own startup probe refuses to boot when the port is busy,
173
+ // so starting it before this process has let go made it fail with
174
+ // "already running on port" every time — while the menu still printed
175
+ // that everything was running, because a detached child with no stdio
176
+ // cannot report anything back. Releasing the port first is the fix, and
177
+ // waiting on the child's signal is what stops the menu from claiming
178
+ // success for a child that died.
179
+ console.log("Stopping the gateway to free the port…");
180
+ running = false;
181
+ stopping = true;
182
+ handedOff = true;
183
+ await shutDown();
184
+ console.log("Starting the tray in the background…");
185
+ const signalPath = join(tmpdir(), `cartethyia-tray-menu-${process.pid}-${randomUUID()}.json`);
186
+ try {
187
+ const url = await launchBackgroundWithStatus(
188
+ ["run", resolvePackagePath("scripts", "cli", "main.ts"), "tray"],
189
+ { signalPath },
190
+ );
191
+ console.log(`Cartethyia is running in the background at ${url || dashboardUrl}.`);
192
+ console.log("The tray icon owns it; use Exit there to stop it.");
193
+ } catch (error) {
194
+ handedOff = false;
195
+ console.error(
196
+ `Could not hand off to the tray: ${error instanceof Error ? error.message : "unknown error"}`,
197
+ );
198
+ console.error("Cartethyia is stopped. Start it again from this menu.");
199
+ }
200
+ },
201
+ async () => {
202
+ // Export straight to the download directory. The console page asks for
203
+ // the operator password, which is exactly the thing a locked-out
204
+ // operator does not have; the CLI already runs as the OS user who owns
205
+ // the database, so the loopback token is the whole gate.
206
+ await whenReady();
207
+ const result = await exportBackup(port, drainToken);
208
+ if (result === null) return;
209
+ console.log(
210
+ `Backup written to ${result.path} (${(result.bytes / 1024).toFixed(1)} KiB, ${Object.keys(result.counts).length} tables).`,
211
+ );
212
+ console.log("Telemetry is not included: it is per-request history, not configuration.");
213
+ },
214
+ async () => {
215
+ // Deleting the console account is the only real password recovery:
216
+ // /change-password needs the current password, and first-boot setup
217
+ // only runs when no user exists. Removing the user puts the wizard
218
+ // back. Providers, keys, and routing are untouched.
219
+ console.log("");
220
+ console.log("This deletes every console account and its sessions.");
221
+ console.log("The next visit to /console asks you to create a new one.");
222
+ console.log("Providers, API keys, and routing are not touched.");
223
+ console.log("");
224
+ if (!(await confirmStep("Continue with the reset?"))) {
225
+ console.log("Cancelled.");
226
+ return;
227
+ }
228
+ if (!(await confirmByTyping("RESET", "Confirm deleting the console account"))) {
229
+ console.log("Cancelled.");
230
+ return;
231
+ }
232
+ await whenReady();
233
+ const status = await resetConsoleAccount(port, drainToken);
234
+ console.log(
235
+ status === 0
236
+ ? `Console account removed. Open ${dashboardUrl} to create a new one.`
237
+ : "Reset failed; see the gateway log.",
238
+ );
239
+ },
240
+ async () => {
241
+ running = false;
242
+ },
243
+ ];
244
+ // The Update action is only wired in when there is something newer to go
245
+ // to; otherwise the menu's up-to-date state is already told by the header
246
+ // line and an extra row would be noise.
247
+ const updateAction = async (): Promise<void> => {
248
+ if (upToDate || latestVersion === null) return;
249
+ // npm cannot replace this package's directory while this process is
250
+ // running out of it: on Windows the rename fails with EBUSY and npm
251
+ // exits 14. Even with the gateway stopped, the CLI itself is executing
252
+ // from that directory, so an in-process install can never succeed.
253
+ // Print the command and exit, the way 9router does.
254
+ await shutDown();
255
+ runDetachedUpdate();
256
+ console.log("");
257
+ console.log(`Update available: ${currentVersion} \u2192 ${latestVersion}`);
258
+ console.log("Detached update started; this process will exit now.");
259
+ console.log("Re-run `carte` after it finishes.");
260
+ console.log("");
261
+ running = false;
262
+ process.exit(0);
263
+ };
264
+ const extendedActions: readonly (() => Promise<void>)[] = upToDate
265
+ ? actions
266
+ : [...actions.slice(0, actions.length - 1), updateAction, actions[actions.length - 1] ?? (async () => undefined)];
267
+
268
+ const rows: MenuRow[] = [
269
+ { kind: "action", label: "Open Console", hint: `browser \u00b7 ${dashboardUrl}` },
270
+ { kind: "action", label: "Hide to Tray", hint: "keep the gateway running" },
271
+ { kind: "action", label: "Backup", hint: "export config to Downloads" },
272
+ { kind: "action", label: "Reset", hint: "deletes the console account" },
273
+ ];
274
+ if (!upToDate && latestVersion !== null) {
275
+ rows.push({ kind: "action", label: `Update to ${latestVersion}`, hint: "installs now and exits" });
276
+ }
277
+ rows.push({ kind: "rule" });
278
+ rows.push({ kind: "action", label: "Exit", hint: "stop the gateway" });
279
+
280
+ // Focus the Update row by default when it exists, so the operator who
281
+ // launched `carte` *because* they saw the version checker gets a one-key
282
+ // path to the fix.
283
+ const updateIndex = upToDate || latestVersion === null ? -1 : 4;
284
+ const initialActionIndex = updateIndex >= 0 ? updateIndex : 0;
285
+ const choice = await chooseFromMenu(header, rows, { initialIndex: initialActionIndex });
286
+ if (choice === -1) break;
287
+ const action = extendedActions[choice];
288
+ if (action) await action();
289
+ }
290
+ // "Hide to tray" has already given the gateway to the tray. Draining here
291
+ // would stop the very process the tray just adopted, which is why the menu
292
+ // appeared to hand over a gateway that was not listening.
293
+ if (handedOff) return;
294
+ if (runningAttached !== null) {
295
+ detachAttached();
296
+ return;
297
+ }
298
+ await shutDown();
299
+ }
@@ -1,6 +1,6 @@
1
1
  import { ENV_PATH } from "./env";
2
2
  import { getLocalPlatform } from "./platform";
3
- import { hasRequiredFailure, runHealthChecks, type CheckPhase } from "../health";
3
+ import { hasRequiredFailure, runHealthChecks, type CheckPhase } from "./health";
4
4
 
5
5
  const phases: readonly CheckPhase[] = ["preflight", "configuration", "runtime"];
6
6
 
@@ -7,8 +7,7 @@ import {
7
7
  writeInstanceLock,
8
8
  } from "./instance";
9
9
  import { join } from "node:path";
10
- import { PACKAGE_ROOT, resolvePackagePath } from "../../src/config/package-paths";
11
- import { compiledBinaryPath } from "../build/compile";
10
+ import { PACKAGE_ROOT, compiledBinaryPath, resolvePackagePath } from "../../src/config/package-paths";
12
11
  import { spawn as spawnDetached, type ChildProcess } from "node:child_process";
13
12
  import {
14
13
  blockedPortMessage,
@@ -3,10 +3,10 @@ import { constants } from "node:fs";
3
3
  import { join, resolve } from "node:path";
4
4
  import { Client } from "pg";
5
5
  import Redis from "ioredis";
6
- import { hasPlaceholderSecrets, readEnvFile } from "./cli/env";
7
- import { parseServiceUrl, probeTcpService } from "./cli/services";
8
- import { resolveDataDir, resolveDbMode } from "../src/persistence/db-mode";
9
- import { bunVersionAtLeast, readRequiredBunVersion } from "./cli/version";
6
+ import { hasPlaceholderSecrets, readEnvFile } from "./env";
7
+ import { parseServiceUrl, probeTcpService } from "./services";
8
+ import { resolveDataDir, resolveDbMode } from "../../src/persistence/db-mode";
9
+ import { bunVersionAtLeast, readRequiredBunVersion } from "./version";
10
10
 
11
11
  export type CheckPhase = "preflight" | "configuration" | "runtime";
12
12
  export type CheckStatus = "pass" | "warn" | "fail" | "skip";
@@ -1,3 +1,6 @@
1
+ // dynamic-import-ok: subcommand dispatcher. Every branch lazy-loads only the
2
+ // module its command needs so `cartethyia --help` and `cartethyia stop` do
3
+ // not drag the gateway, dashboard, and database driver into memory.
1
4
  import { mkdirSync } from "node:fs";
2
5
  import { resolveUserConfigDir } from "../../src/config/package-paths";
3
6
  import { readRequiredBunVersion, assertBunVersion } from "./version";