larness 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +6 -5
  2. package/app.js +22 -105
  3. package/apps/server/dist/{address-BDs0FfMq.js → address-D0ZG5qR4.js} +5 -2
  4. package/apps/server/dist/args-CrKTPT06.js +92 -0
  5. package/apps/server/dist/cli.js +340 -0
  6. package/apps/server/dist/{client-D88ULjn9.js → client-D_Ni3Zpx.js} +21 -1
  7. package/apps/server/dist/code-B2JBoV4x.js +24 -0
  8. package/apps/server/dist/{doctor-dwTQiTef.js → doctor-CE6cONuz.js} +3 -2
  9. package/apps/server/dist/doctor-sPRlI92N.js +1 -0
  10. package/apps/server/dist/doctor.js +1 -1
  11. package/apps/server/dist/index.js +724 -126
  12. package/apps/server/dist/{paths-DUfwiH2X.js → inspect-XgAc84F9.js} +106 -87
  13. package/apps/server/dist/lifecycle-C3KV3-Ax.js +263 -0
  14. package/apps/server/dist/log-files-CFOaEy6O.js +26 -0
  15. package/apps/server/dist/{managed-Br7VqQiP.js → managed-Cw3MVilO.js} +221 -71
  16. package/apps/server/dist/paths-BhVn34MT.js +77 -0
  17. package/apps/server/dist/{status-D2oSIMoj.js → status-CV_zWfs6.js} +16 -3
  18. package/apps/server/dist/status.js +37 -9
  19. package/apps/server/dist/supervisor-IYDKL4iU.js +297 -0
  20. package/apps/server/dist/tui.js +167 -333
  21. package/apps/server/dist/version-ui_X8H2k.js +13 -0
  22. package/apps/server/drizzle/0001_auth.sql +109 -109
  23. package/apps/server/drizzle/0002_projects.sql +12 -12
  24. package/apps/server/drizzle/0003_workspace.sql +80 -80
  25. package/apps/server/drizzle/0004_models.sql +30 -30
  26. package/apps/server/drizzle/0005_resources.sql +54 -54
  27. package/apps/server/drizzle/0006_commands.sql +23 -23
  28. package/apps/server/drizzle/0007_terminals.sql +41 -41
  29. package/apps/server/drizzle/0008_resource_actions.sql +23 -23
  30. package/apps/server/drizzle/0010_services.sql +31 -31
  31. package/apps/web/dist/assets/{FileEditor-JaazRNUl.js → FileEditor-DnQa6Owc.js} +1 -1
  32. package/apps/web/dist/assets/{FileViewer-DzJpg82J.js → FileViewer-DKlF-CWF.js} +1 -1
  33. package/apps/web/dist/assets/{cssMode-B8mOf4OC.js → cssMode-C9KmpsHc.js} +1 -1
  34. package/apps/web/dist/assets/{editor.api-BQ-DCb9F.js → editor.api-BwfHyHQ6.js} +1 -1
  35. package/apps/web/dist/assets/{freemarker2-C1ckA1My.js → freemarker2-D41RlIQ5.js} +1 -1
  36. package/apps/web/dist/assets/{handlebars-suElsFdc.js → handlebars-D-7R6ic0.js} +1 -1
  37. package/apps/web/dist/assets/{html-CvWl95vU.js → html-CUME4rt-.js} +1 -1
  38. package/apps/web/dist/assets/{htmlMode-CrdRQhj8.js → htmlMode-8w7WLhnL.js} +1 -1
  39. package/apps/web/dist/assets/{index-C6uOTgh6.js → index-BOS3UrP1.js} +2 -2
  40. package/apps/web/dist/assets/{javascript-DmE3KPeg.js → javascript-_3pdDG34.js} +1 -1
  41. package/apps/web/dist/assets/{jsonMode-TuNjADgG.js → jsonMode-DiqocFCf.js} +1 -1
  42. package/apps/web/dist/assets/{liquid-C_Ceyr5s.js → liquid-j0FoiTXN.js} +1 -1
  43. package/apps/web/dist/assets/{lspLanguageFeatures-DZfo74cL.js → lspLanguageFeatures-Zj7K2sG4.js} +1 -1
  44. package/apps/web/dist/assets/main-DZIruO5x.js +157 -0
  45. package/apps/web/dist/assets/main-gq3n_vn8.css +1 -0
  46. package/apps/web/dist/assets/{mdx-D8eqTMYQ.js → mdx-CGQ8Cw6J.js} +1 -1
  47. package/apps/web/dist/assets/{monaco-BGhTlUO7.js → monaco-CyMA3azg.js} +3 -3
  48. package/apps/web/dist/assets/{python-Cx6dqJ-u.js → python-BtY34Z9A.js} +1 -1
  49. package/apps/web/dist/assets/{razor-u7rb64U6.js → razor-CzYHpLv5.js} +1 -1
  50. package/apps/web/dist/assets/{tsMode-Cu3GDz4d.js → tsMode-GZx3VEv9.js} +1 -1
  51. package/apps/web/dist/assets/{typescript-H0OSh9BN.js → typescript-CAfvuTDQ.js} +1 -1
  52. package/apps/web/dist/assets/{workers-DJ7JInlW.js → workers-C5BOxOmH.js} +1 -1
  53. package/apps/web/dist/assets/{xml-C_rrJhqX.js → xml-BGX4mtH7.js} +1 -1
  54. package/apps/web/dist/assets/{yaml-Cub5doLg.js → yaml-B2AgBtJB.js} +1 -1
  55. package/apps/web/dist/favicon.svg +4 -4
  56. package/apps/web/dist/index.html +1 -1
  57. package/docs/README.md +8 -1
  58. package/docs/guides/install.md +23 -7
  59. package/package.json +3 -1
  60. package/apps/server/dist/lock-DyEoZgG_.js +0 -101
  61. package/apps/web/dist/assets/main-C3xYrJa1.js +0 -157
  62. package/apps/web/dist/assets/main-ptChOROf.css +0 -1
@@ -0,0 +1,297 @@
1
+ import { a as DevWebControl, c as EntryConfigError, d as devWebCache, i as DevWebAttachedSchema, it as terminateProcessTree, r as waitChildMessage } from "./managed-Cw3MVilO.js";
2
+ import { c as configFilePath, l as loadConfig, n as inspectPendingInitialization, p as findServerRoot, u as resolveConfig } from "./inspect-XgAc84F9.js";
3
+ import { r as resolveDataDir } from "./paths-BhVn34MT.js";
4
+ import { createRequire } from "node:module";
5
+ import { randomUUID } from "node:crypto";
6
+ import { existsSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { spawn } from "node:child_process";
10
+ import { rm } from "node:fs/promises";
11
+ import pc from "picocolors";
12
+ // src/tui/supervisor.ts
13
+ const READY_TIMEOUT_MS = 9e4;
14
+ const LOG_LIMIT = 300;
15
+ function isLoopbackHostname(hostname) {
16
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
17
+ }
18
+ function originPort(origin) {
19
+ const parsed = new URL(origin);
20
+ return Number(parsed.port || (parsed.protocol === "https:" ? "443" : "80"));
21
+ }
22
+ function resolveWebUrl(options) {
23
+ const localUrl = `http://localhost:${options.serverPort}`;
24
+ const canonical = new URL(options.canonicalOrigin);
25
+ if (canonical.protocol === "http:" && isLoopbackHostname(canonical.hostname) && originPort(options.canonicalOrigin) !== options.serverPort) throw new EntryConfigError(options.canonicalOrigin, options.serverPort);
26
+ return options.publicUrl ?? localUrl;
27
+ }
28
+ function serverRoot() {
29
+ return findServerRoot(path.dirname(fileURLToPath(import.meta.url)));
30
+ }
31
+ function managedCommands(options) {
32
+ const nodePath = options.nodePath ?? process.execPath;
33
+ if (!options.dev) return {
34
+ serverCommand: nodePath,
35
+ serverArgs: [path.join(options.serverRoot, "dist", "index.js")],
36
+ serverCwd: options.serverRoot,
37
+ webCommand: null,
38
+ webArgs: [],
39
+ webCwd: null
40
+ };
41
+ const serverRequire = createRequire(path.join(options.serverRoot, "package.json"));
42
+ const tsxLoader = pathToFileURL(serverRequire.resolve("tsx/esm")).href;
43
+ return {
44
+ serverCommand: nodePath,
45
+ serverArgs: [
46
+ "--import",
47
+ tsxLoader,
48
+ path.join(options.serverRoot, "src", "index.ts"),
49
+ "--managed-dev-web"
50
+ ],
51
+ serverCwd: options.serverRoot,
52
+ webCommand: nodePath,
53
+ webArgs: [
54
+ "--import",
55
+ tsxLoader,
56
+ path.join(options.repoRoot, "apps", "web", "scripts", "managed-vite.ts")
57
+ ],
58
+ webCwd: path.join(options.repoRoot, "apps", "web")
59
+ };
60
+ }
61
+ function delay(ms) {
62
+ return new Promise((resolve) => setTimeout(resolve, ms));
63
+ }
64
+ async function httpOk(url, requireHtml = false, host) {
65
+ try {
66
+ const response = await fetch(url, {
67
+ signal: AbortSignal.timeout(5e3),
68
+ ...host ? { headers: { host } } : {}
69
+ });
70
+ const ready = response.ok && (!requireHtml || (response.headers.get("content-type") ?? "").includes("text/html"));
71
+ await response.arrayBuffer();
72
+ return ready;
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+ async function waitForHttp(url, child, options = {}) {
78
+ const deadline = Date.now() + (options.timeoutMs ?? READY_TIMEOUT_MS);
79
+ while (Date.now() < deadline) {
80
+ if (child.exitCode !== null || child.signalCode !== null || options.failed?.() === true || options.signal?.aborted === true) return false;
81
+ if (await httpOk(url, options.requireHtml, options.host)) return true;
82
+ await delay(200);
83
+ }
84
+ return false;
85
+ }
86
+ function waitForExit(child, timeoutMs) {
87
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
88
+ return new Promise((resolve) => {
89
+ const timer = setTimeout(() => resolve(false), timeoutMs);
90
+ child.once("exit", () => {
91
+ clearTimeout(timer);
92
+ resolve(true);
93
+ });
94
+ });
95
+ }
96
+ async function stopChild(child, timeoutMs, graceful = "signal") {
97
+ if (child === null || child.exitCode !== null || child.signalCode !== null) return;
98
+ if (process.platform === "win32" && child.pid) {
99
+ if (graceful === "message" && child.connected) child.send({ type: "larness.shutdown" });
100
+ else if (graceful === "disconnect" && child.connected) child.disconnect();
101
+ if (await waitForExit(child, timeoutMs)) return;
102
+ await terminateProcessTree(child.pid, 2e3);
103
+ await waitForExit(child, 2e3);
104
+ return;
105
+ }
106
+ child.kill("SIGTERM");
107
+ if (await waitForExit(child, timeoutMs)) return;
108
+ child.kill("SIGKILL");
109
+ await waitForExit(child, 2e3);
110
+ }
111
+ async function loadManagedConfig(dataDir, env = process.env) {
112
+ const pending = inspectPendingInitialization(path.join(dataDir, "larness.db"));
113
+ return pending === null ? loadConfig({
114
+ dataDir,
115
+ env
116
+ }) : {
117
+ ...resolveConfig(pending, env),
118
+ source: "file",
119
+ path: configFilePath(dataDir)
120
+ };
121
+ }
122
+ async function startManagedRuntime(options) {
123
+ options.signal?.throwIfAborted();
124
+ const out = options.out ?? console.log;
125
+ const root = serverRoot();
126
+ const repoRoot = path.resolve(root, "../..");
127
+ const dataDir = resolveDataDir();
128
+ const loaded = await loadManagedConfig(dataDir);
129
+ const port = loaded.config.server.port;
130
+ const localBase = `http://127.0.0.1:${port}`;
131
+ const serverUrl = `http://localhost:${port}`;
132
+ const canonicalOrigin = loaded.webAuthn.origin;
133
+ const webUrl = resolveWebUrl({
134
+ dev: options.dev,
135
+ serverPort: port,
136
+ publicUrl: loaded.config.server.publicUrl,
137
+ canonicalOrigin
138
+ });
139
+ if (await httpOk(`${localBase}/api/health`)) throw new Error(`已有 Larness Server 在 ${serverUrl} 运行;请先关闭原 TUI。`);
140
+ const commands = managedCommands({
141
+ dev: options.dev,
142
+ serverRoot: root,
143
+ repoRoot
144
+ });
145
+ const logs = [];
146
+ const appendLog = (prefix, chunk) => {
147
+ for (const line of chunk.toString("utf8").split(/\r?\n/)) if (line.trim()) logs.push(`${prefix} ${line}`);
148
+ if (logs.length > LOG_LIMIT) logs.splice(0, logs.length - LOG_LIMIT);
149
+ };
150
+ let server = null;
151
+ let web = null;
152
+ let stopped = false;
153
+ let ownedCache = null;
154
+ let stopping = null;
155
+ let resolveServerExit = () => void 0;
156
+ const serverExited = new Promise((resolve) => {
157
+ resolveServerExit = resolve;
158
+ });
159
+ let resolveDevFailure = () => void 0;
160
+ const devFailed = new Promise((resolve) => {
161
+ resolveDevFailure = resolve;
162
+ });
163
+ const forceKill = () => {
164
+ server?.kill("SIGKILL");
165
+ web?.kill("SIGKILL");
166
+ };
167
+ process.once("exit", forceKill);
168
+ const stop = () => {
169
+ stopped = true;
170
+ stopping ??= (async () => {
171
+ try {
172
+ await stopChild(server, 1e4, "message");
173
+ } finally {
174
+ try {
175
+ await stopChild(web, 5e3, "disconnect");
176
+ } finally {
177
+ try {
178
+ if (ownedCache) await rm(ownedCache, {
179
+ recursive: true,
180
+ force: true
181
+ });
182
+ } finally {
183
+ process.off("exit", forceKill);
184
+ }
185
+ }
186
+ }
187
+ })();
188
+ return stopping;
189
+ };
190
+ const observe = (child, prefix) => {
191
+ child.stdout?.on("data", (chunk) => appendLog(prefix, chunk));
192
+ child.stderr?.on("data", (chunk) => appendLog(prefix, chunk));
193
+ child.on("error", () => {
194
+ if (options.dev && !stopped) resolveDevFailure();
195
+ });
196
+ child.on("exit", () => {
197
+ if (options.dev && !stopped) resolveDevFailure();
198
+ });
199
+ if (options.dev) child.on("disconnect", () => {
200
+ if (!stopped) resolveDevFailure();
201
+ });
202
+ };
203
+ try {
204
+ const generation = randomUUID();
205
+ let target = null;
206
+ if (options.dev) {
207
+ options.signal?.throwIfAborted();
208
+ web = spawn(commands.webCommand ?? process.execPath, commands.webArgs, {
209
+ cwd: commands.webCwd ?? repoRoot,
210
+ env: process.env,
211
+ stdio: [
212
+ "ignore",
213
+ "pipe",
214
+ "pipe",
215
+ "ipc"
216
+ ]
217
+ });
218
+ observe(web, "[web]");
219
+ const control = new DevWebControl(web, generation);
220
+ const child = web;
221
+ const ready = waitChildMessage(child, (message) => control.accept(child, message) ? control.target : null, options.signal, "Vite");
222
+ child.send({
223
+ type: "dev-web.start",
224
+ generation,
225
+ origin: canonicalOrigin
226
+ });
227
+ target = await ready;
228
+ ownedCache = devWebCache(target.generation);
229
+ }
230
+ options.signal?.throwIfAborted();
231
+ server = spawn(commands.serverCommand, commands.serverArgs, {
232
+ cwd: commands.serverCwd,
233
+ env: {
234
+ ...process.env,
235
+ LARNESS_LOG_STDERR: "0",
236
+ LARNESS_TUI_CHILD: "1",
237
+ LARNESS_LIFECYCLE_MODE: "foreground",
238
+ LARNESS_RUNTIME_DEV: options.dev ? "1" : "0",
239
+ LARNESS_PM2_AUTO_INSTALL: process.env.LARNESS_PM2_AUTO_INSTALL ?? "1",
240
+ ...options.dev ? { LARNESS_SERVE_WEB: "0" } : {}
241
+ },
242
+ stdio: [
243
+ "ignore",
244
+ "pipe",
245
+ "pipe",
246
+ "ipc"
247
+ ]
248
+ });
249
+ observe(server, "[server]");
250
+ server.once("exit", resolveServerExit);
251
+ if (target) {
252
+ const attached = waitChildMessage(server, (message) => {
253
+ const parsed = DevWebAttachedSchema.safeParse(message);
254
+ return parsed.success && parsed.data.generation === generation ? true : null;
255
+ }, options.signal);
256
+ server.send({
257
+ type: "dev-web.attach",
258
+ ...target
259
+ });
260
+ await attached;
261
+ }
262
+ const serverReady = await waitForHttp(`${localBase}/api/health`, server, { signal: options.signal });
263
+ const host = new URL(canonicalOrigin).host;
264
+ const webReady = serverReady && await waitForHttp(`${localBase}/`, server, {
265
+ requireHtml: true,
266
+ signal: options.signal,
267
+ host,
268
+ timeoutMs: options.dev ? READY_TIMEOUT_MS : 5e3
269
+ });
270
+ const resourcesReady = !options.dev || await waitForHttp(`${localBase}/@vite/client`, server, {
271
+ signal: options.signal,
272
+ host
273
+ });
274
+ if (!serverReady || !webReady || !resourcesReady || web?.exitCode !== null && web !== null || web?.signalCode !== null && web !== null) throw new Error("Server 或 Web 未就绪;请查看本机日志,打包模式请先运行 pnpm build。");
275
+ if (!existsSync(path.join(dataDir, "ipc", "token"))) throw new Error("IPC 尚未就绪");
276
+ } catch (error) {
277
+ await stop();
278
+ throw error;
279
+ }
280
+ out(pc.bold("Larness"));
281
+ out(`${pc.green("✓")} 数据目录 ${dataDir}`);
282
+ out(`${pc.green("✓")} Server ${serverUrl}`);
283
+ out(`${pc.green("✓")} Web ${webUrl}`);
284
+ out(`${pc.green("✓")} IPC ${path.join(dataDir, "ipc")}`);
285
+ return {
286
+ dataDir,
287
+ config: loaded,
288
+ dev: options.dev,
289
+ serverUrl,
290
+ webUrl,
291
+ logs: () => [...logs],
292
+ stop,
293
+ serverExited,
294
+ devFailed
295
+ };
296
+ }
297
+ export { startManagedRuntime as n, loadManagedConfig as t };