larness 0.4.2 → 0.5.0

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 +704 -118
  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
@@ -1,14 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { closeSync, constants, existsSync, fsyncSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { z } from "zod";
6
- import { access, chmod, mkdir, readFile, stat } from "node:fs/promises";
6
+ import { readFile, unlink, writeFile } from "node:fs/promises";
7
7
  import { eq, sql } from "drizzle-orm";
8
8
  import { blob, check, index, integer, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
9
9
  import BetterSqlite3 from "better-sqlite3";
10
10
  import { migrate } from "drizzle-orm/better-sqlite3/migrator";
11
- import envPaths from "env-paths";
12
11
  // \0rolldown/runtime.js
13
12
  var __defProp = Object.defineProperty;
14
13
  var __exportAll = (all, flags) => {
@@ -2735,17 +2734,6 @@ function ensureInstanceId(db, now = Date.now()) {
2735
2734
  function deleteMeta(db, key) {
2736
2735
  db.delete(appMeta).where(eq(appMeta.key, key)).run();
2737
2736
  }
2738
- // src/version.ts
2739
- function readPackageMetadata() {
2740
- try {
2741
- return JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8")) ?? {};
2742
- } catch {
2743
- return {};
2744
- }
2745
- }
2746
- const metadata = readPackageMetadata();
2747
- const SERVER_VERSION = typeof metadata.version === "string" ? metadata.version : "0.0.0";
2748
- const SUPPORTED_NODE_RANGE = typeof metadata.engines?.node === "string" ? metadata.engines.node : "^22.22.0 || >=24";
2749
2737
  // src/db/migrate.ts
2750
2738
  const SERVER_PACKAGE_NAME = "@larness/server";
2751
2739
  function findServerRoot(startDirectory) {
@@ -2915,6 +2903,109 @@ function recoverInitialization(db, dataDir) {
2915
2903
  rmSync(temporary, { force: true });
2916
2904
  }
2917
2905
  }
2906
+ // src/bootstrap/lock.ts
2907
+ var InstanceLockedError = class extends Error {
2908
+ pid;
2909
+ constructor(pid, message) {
2910
+ super(message ?? `another Larness instance is already running (pid ${pid ?? "unknown"})`);
2911
+ this.name = "InstanceLockedError";
2912
+ this.pid = pid;
2913
+ }
2914
+ };
2915
+ function lockFilePath(dataDir) {
2916
+ return path.join(dataDir, "larness.lock");
2917
+ }
2918
+ function isProcessAlive(pid) {
2919
+ if (!Number.isInteger(pid) || pid <= 0) return false;
2920
+ try {
2921
+ process.kill(pid, 0);
2922
+ return true;
2923
+ } catch (error) {
2924
+ return error.code === "EPERM";
2925
+ }
2926
+ }
2927
+ function parseRecord(text) {
2928
+ try {
2929
+ const value = JSON.parse(text);
2930
+ if (typeof value !== "object" || value === null || !("pid" in value) || !("startedAt" in value) || !("version" in value)) return null;
2931
+ const { pid, startedAt, version, mode, dev } = value;
2932
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || typeof startedAt !== "number" || typeof version !== "string") return null;
2933
+ const record = {
2934
+ pid,
2935
+ startedAt,
2936
+ version
2937
+ };
2938
+ if (mode === "foreground" || mode === "background") record.mode = mode;
2939
+ if (typeof dev === "boolean") record.dev = dev;
2940
+ return record;
2941
+ } catch {
2942
+ return null;
2943
+ }
2944
+ }
2945
+ async function readRecord(lockPath) {
2946
+ try {
2947
+ return parseRecord(await readFile(lockPath, "utf8"));
2948
+ } catch {
2949
+ return null;
2950
+ }
2951
+ }
2952
+ async function inspectInstanceLock(dataDir) {
2953
+ const lockPath = lockFilePath(dataDir);
2954
+ try {
2955
+ await readFile(lockPath);
2956
+ } catch {
2957
+ return null;
2958
+ }
2959
+ const record = await readRecord(lockPath);
2960
+ return {
2961
+ path: lockPath,
2962
+ record,
2963
+ alive: record !== null && isProcessAlive(record.pid)
2964
+ };
2965
+ }
2966
+ async function removeIfUnchanged(lockPath, expected) {
2967
+ try {
2968
+ const current = parseRecord(await readFile(lockPath, "utf8"));
2969
+ if (current === null || current.pid !== expected.pid || current.startedAt !== expected.startedAt) return;
2970
+ await unlink(lockPath);
2971
+ } catch {}
2972
+ }
2973
+ async function acquireInstanceLock(dataDir, options) {
2974
+ const lockPath = lockFilePath(dataDir);
2975
+ const record = {
2976
+ pid: options.pid ?? process.pid,
2977
+ startedAt: (options.now ?? Date.now)(),
2978
+ version: options.version,
2979
+ ...options.mode === void 0 ? {} : { mode: options.mode },
2980
+ ...options.dev === void 0 ? {} : { dev: options.dev }
2981
+ };
2982
+ for (let attempt = 0; attempt < 2; attempt += 1) try {
2983
+ await writeFile(lockPath, `${JSON.stringify(record)}\n`, {
2984
+ flag: "wx",
2985
+ mode: 384
2986
+ });
2987
+ return {
2988
+ ...record,
2989
+ path: lockPath
2990
+ };
2991
+ } catch (error) {
2992
+ if (error.code !== "EEXIST") throw error;
2993
+ const existing = await readRecord(lockPath);
2994
+ if (existing === null) throw new InstanceLockedError(null, `lock file is unreadable: ${lockPath}; verify no server is running before removing it`);
2995
+ if (isProcessAlive(existing.pid)) throw new InstanceLockedError(existing.pid);
2996
+ await removeIfUnchanged(lockPath, existing);
2997
+ }
2998
+ throw new InstanceLockedError(null, "failed to acquire the instance lock after a stale-lock retry");
2999
+ }
3000
+ async function releaseInstanceLock(lock) {
3001
+ const current = await readRecord(lock.path);
3002
+ if (current === null || current.pid !== lock.pid) return;
3003
+ try {
3004
+ await unlink(lock.path);
3005
+ } catch (error) {
3006
+ if (error.code !== "ENOENT") throw error;
3007
+ }
3008
+ }
2918
3009
  // src/db/inspect.ts
2919
3010
  function hasAuthSettings(sqlite) {
2920
3011
  try {
@@ -2971,76 +3062,4 @@ function inspectPendingInitialization(file) {
2971
3062
  sqlite.close();
2972
3063
  }
2973
3064
  }
2974
- // src/platform/paths.ts
2975
- const DATA_SUBDIRS = [
2976
- "logs",
2977
- "backups",
2978
- "tmp",
2979
- "sessions",
2980
- "artifacts",
2981
- "secrets",
2982
- "ipc"
2983
- ];
2984
- var DataDirError = class extends Error {
2985
- constructor(message) {
2986
- super(message);
2987
- this.name = "DataDirError";
2988
- }
2989
- };
2990
- function defaultDataDir() {
2991
- return envPaths("larness", { suffix: "" }).data;
2992
- }
2993
- function resolveDataDir(env = process.env) {
2994
- const override = env.LARNESS_DATA_DIR?.trim();
2995
- return override ? path.resolve(override) : defaultDataDir();
2996
- }
2997
- async function ensureDir(dir) {
2998
- try {
2999
- const info = await stat(dir);
3000
- if (!info.isDirectory()) throw new DataDirError(`data directory path is not a directory: ${dir}`);
3001
- let hardened = false;
3002
- if (process.platform !== "win32" && (info.mode & 63) !== 0) try {
3003
- await chmod(dir, 448);
3004
- hardened = true;
3005
- } catch (error) {
3006
- throw new DataDirError(`cannot restrict permissions on ${dir}: ${error.code}`);
3007
- }
3008
- return {
3009
- created: false,
3010
- hardened
3011
- };
3012
- } catch (error) {
3013
- if (error instanceof DataDirError) throw error;
3014
- if (error.code !== "ENOENT") throw new DataDirError(`cannot access data directory ${dir}: ${error.code}`);
3015
- try {
3016
- await mkdir(dir, {
3017
- recursive: true,
3018
- mode: 448
3019
- });
3020
- } catch (mkdirError) {
3021
- throw new DataDirError(`cannot create data directory ${dir}: ${mkdirError.code}`);
3022
- }
3023
- return {
3024
- created: true,
3025
- hardened: false
3026
- };
3027
- }
3028
- }
3029
- async function ensureDataDirs(dataDir) {
3030
- const root = await ensureDir(dataDir);
3031
- let hardened = root.hardened;
3032
- for (const name of DATA_SUBDIRS) {
3033
- const result = await ensureDir(path.join(dataDir, name));
3034
- hardened = hardened || result.hardened;
3035
- }
3036
- try {
3037
- await access(dataDir, constants.W_OK);
3038
- } catch {
3039
- throw new DataDirError(`data directory is not writable: ${dataDir}`);
3040
- }
3041
- return {
3042
- created: root.created,
3043
- hardened
3044
- };
3045
- }
3046
- export { secrets as $, FileSaveSchema as $n, GitActionSchema as $t, deploymentArtifacts as A, DEFAULT_APP_CONFIG as An, TerminalInputSchema as At, modelCatalogCache as B, CommandRequestSchema as Bn, ProcessIdSchema as Bt, approvals as C, ServiceActionAuthorizationDtoSchema as Cn, ServiceRegisterInputSchema as Ct, commandExecutions as D, ServiceOpsSubscriptionSchema as Dn, TerminalCreateSchema as Dt, browserSessions as E, ServiceOpsEventPayloadSchema as En, TERMINAL_LEASE_TTL_MS as Et, deviceRequests as F, CommandCancelSchema as Fn, TerminalResizeSchema as Ft, resourceActions as G, normalizeCommandRequest as Gn, MemoryKeySchema as Gt, modelProfiles as H, CommandSubscriptionSchema as Hn, ProcessStatusSchema as Ht, fileVersions as I, CommandIdSchema as In, TerminalSubscriptionSchema as It, resourceOperations as J, FileListQuerySchema as Jn, ReadMemoryInputSchema as Jt, resourceEvents as K, FileActionResultSchema as Kn, MemoryKindSchema as Kt, memories as L, CommandOutputChunkSchema as Ln, TerminalTakeoverSchema as Lt, deploymentBuilds as M, deriveWebAuthn as Mn, TerminalOutputChunkSchema as Mt, deploymentPlans as N, COMMAND_OUTPUT_RETENTION_MS as Nn, TerminalPayloadSchema as Nt, credentialProfiles as O, hasControlCharacters as On, TerminalDevSchema as Ot, deploymentTargets as P, COMMAND_RETENTION_MS as Pn, TerminalRenameSchema as Pt, schema_exports as Q, FileSaveResultSchema as Qn, GitActionDecisionSchema as Qt, memoryRevisions as R, CommandOutputQuerySchema as Rn, PROCESS_OUTPUT_MAX_BYTES as Rt, agentEvents as S, DeploymentTargetRefSchema as Sn, ServiceIdSchema as St, authSettings as T, ServiceControlInputSchema as Tn, ServiceSubscriptionSchema as Tt, modelVisibility as U, MAX_COMMAND_TIMEOUT_MS as Un, StartProcessParamsSchema as Ut, modelDefaults as V, CommandStatusPayloadSchema as Vn, ProcessOutputQuerySchema as Vt, projects as W, ShellCommandParamsSchema as Wn, PlanParamsSchema as Wt, scheduledJobRuns as X, FileReadQuerySchema as Xn, ScheduledJobInputSchema as Xt, resourceStreams as Y, FilePathSchema as Yn, RememberToolInputSchema as Yt, scheduledJobs as Z, FileResultTargetSchema as Zn, ScheduledJobPatchSchema as Zt, getMeta as _, DeploymentPlanDocumentSchema as _n, FileStreamIdSchema as _t, inspectPendingInitialization as a, WORKSPACE_MEMORY_CHANGED as an, isSecretAttachmentName as ar, sessionContextSummaries as at, WEB_SEARCH_PROVIDER_IDS as b, DeploymentTargetIdSchema as bn, ResourceEventsQuerySchema as bt, loadConfig as c, DEPLOYMENT_APPROVAL_TTL_MS as cn, terminals as ct, expectedMigrationCount as d, DEPLOYMENT_ARTIFACT_MAX_PATH as dn, webSearchConnections as dt, GitBranchesQuerySchema as en, FileScopeSchema as er, serviceActionAuthorizations as et, findServerRoot as f, DEPLOYMENT_BUILD_LOG_MAX_BYTES as fn, webauthnChallenges as ft, ensureInstanceId as g, DeploymentAuthorizationScopeSchema as gn, FileResyncPayloadSchema as gt, SUPPORTED_NODE_RANGE as h, DeploymentAuthorizationContextSchema as hn, FileChangedPayloadSchema as ht, inspectDatabase as i, WORKSPACE_JOBS_CHANGED as in, isBlockedAttachmentName as ir, sessionAttachments as it, deploymentAuthorizations as j, OriginUrlSchema as jn, TerminalLeaseSchema as jt, deploymentApprovals as k, AppConfigSchema as kn, TerminalIdSchema as kt, resolveConfig as l, DEPLOYMENT_ARTIFACT_MAX_BYTES as ln, trustedDevices as lt, SERVER_VERSION as m, DeploymentArtifactManifestSchema as mn, newId as mt, ensureDataDirs as n, GitLogQuerySchema as nn, MAX_EDITABLE_FILE_BYTES as nr, serviceOpsServices as nt, recoverInitialization as o, WORKSPACE_SESSIONS_CHANGED as on, isSourceViewMime as or, sessions as ot, runMigrations as p, DEPLOYMENT_PLAN_TTL_MS as pn, webauthnCredentials as pt, resourceLocks as q, FileActionSchema as qn, MemoryStatusSchema as qt, resolveDataDir as r, GitRemoteActionRequestSchema as rn, isAcceptedAttachmentName as rr, services as rt, configFilePath as s, DEFAULT_PROJECT_ID as sn, terminalLeases as st, DATA_SUBDIRS as t, GitDiffQuerySchema as tn, FileSearchQuerySchema as tr, serviceOpsDeployments as tt, appliedMigrationCount as u, DEPLOYMENT_ARTIFACT_MAX_FILES as un, turns as ut, setMeta as v, DeploymentSourceSchema as vn, FileSubscriptionSchema as vt, auditLogs as w, ServiceActionScopeSchema as wn, ServiceStatusSchema as wt, WEB_SEARCH_REGIONS as x, DeploymentTargetNameSchema as xn, ServiceEventPayloadSchema as xt, MODEL_PROVIDER_IDS as y, DeploymentSpecSchema as yn, RESOURCE_EVENT_RETENTION_MS as yt, memorySuppressions as z, CommandParamsSchema as zn, PROCESS_OUTPUT_MAX_CHUNKS as zt };
3065
+ export { serviceActionAuthorizations as $, FileScopeSchema as $n, GitBranchesQuerySchema as $t, deploymentAuthorizations as A, OriginUrlSchema as An, TerminalLeaseSchema as At, modelDefaults as B, CommandStatusPayloadSchema as Bn, ProcessOutputQuerySchema as Bt, auditLogs as C, ServiceActionScopeSchema as Cn, ServiceStatusSchema as Ct, credentialProfiles as D, hasControlCharacters as Dn, TerminalDevSchema as Dt, commandExecutions as E, ServiceOpsSubscriptionSchema as En, TerminalCreateSchema as Et, fileVersions as F, CommandIdSchema as Fn, TerminalSubscriptionSchema as Ft, resourceEvents as G, FileActionResultSchema as Gn, MemoryKindSchema as Gt, modelVisibility as H, MAX_COMMAND_TIMEOUT_MS as Hn, StartProcessParamsSchema as Ht, memories as I, CommandOutputChunkSchema as In, TerminalTakeoverSchema as It, resourceStreams as J, FilePathSchema as Jn, RememberToolInputSchema as Jt, resourceLocks as K, FileActionSchema as Kn, MemoryStatusSchema as Kt, memoryRevisions as L, CommandOutputQuerySchema as Ln, PROCESS_OUTPUT_MAX_BYTES as Lt, deploymentPlans as M, COMMAND_OUTPUT_RETENTION_MS as Mn, TerminalPayloadSchema as Mt, deploymentTargets as N, COMMAND_RETENTION_MS as Nn, TerminalRenameSchema as Nt, deploymentApprovals as O, AppConfigSchema as On, TerminalIdSchema as Ot, deviceRequests as P, CommandCancelSchema as Pn, TerminalResizeSchema as Pt, secrets as Q, FileSaveSchema as Qn, GitActionSchema as Qt, memorySuppressions as R, CommandParamsSchema as Rn, PROCESS_OUTPUT_MAX_CHUNKS as Rt, approvals as S, ServiceActionAuthorizationDtoSchema as Sn, ServiceRegisterInputSchema as St, browserSessions as T, ServiceOpsEventPayloadSchema as Tn, TERMINAL_LEASE_TTL_MS as Tt, projects as U, ShellCommandParamsSchema as Un, PlanParamsSchema as Ut, modelProfiles as V, CommandSubscriptionSchema as Vn, ProcessStatusSchema as Vt, resourceActions as W, normalizeCommandRequest as Wn, MemoryKeySchema as Wt, scheduledJobs as X, FileResultTargetSchema as Xn, ScheduledJobPatchSchema as Xt, scheduledJobRuns as Y, FileReadQuerySchema as Yn, ScheduledJobInputSchema as Yt, schema_exports as Z, FileSaveResultSchema as Zn, GitActionDecisionSchema as Zt, setMeta as _, DeploymentSourceSchema as _n, FileSubscriptionSchema as _t, isProcessAlive as a, WORKSPACE_SESSIONS_CHANGED as an, isSourceViewMime as ar, sessions as at, WEB_SEARCH_REGIONS as b, DeploymentTargetNameSchema as bn, ServiceEventPayloadSchema as bt, configFilePath as c, DEPLOYMENT_ARTIFACT_MAX_BYTES as cn, trustedDevices as ct, appliedMigrationCount as d, DEPLOYMENT_BUILD_LOG_MAX_BYTES as dn, webauthnChallenges as dt, GitDiffQuerySchema as en, FileSearchQuerySchema as er, serviceOpsDeployments as et, expectedMigrationCount as f, DEPLOYMENT_PLAN_TTL_MS as fn, webauthnCredentials as ft, getMeta as g, DeploymentPlanDocumentSchema as gn, FileStreamIdSchema as gt, ensureInstanceId as h, DeploymentAuthorizationScopeSchema as hn, FileResyncPayloadSchema as ht, inspectInstanceLock as i, WORKSPACE_MEMORY_CHANGED as in, isSecretAttachmentName as ir, sessionContextSummaries as it, deploymentBuilds as j, deriveWebAuthn as jn, TerminalOutputChunkSchema as jt, deploymentArtifacts as k, DEFAULT_APP_CONFIG as kn, TerminalInputSchema as kt, loadConfig as l, DEPLOYMENT_ARTIFACT_MAX_FILES as ln, turns as lt, runMigrations as m, DeploymentAuthorizationContextSchema as mn, FileChangedPayloadSchema as mt, inspectPendingInitialization as n, GitRemoteActionRequestSchema as nn, isAcceptedAttachmentName as nr, services as nt, releaseInstanceLock as o, DEFAULT_PROJECT_ID as on, terminalLeases as ot, findServerRoot as p, DeploymentArtifactManifestSchema as pn, newId as pt, resourceOperations as q, FileListQuerySchema as qn, ReadMemoryInputSchema as qt, acquireInstanceLock as r, WORKSPACE_JOBS_CHANGED as rn, isBlockedAttachmentName as rr, sessionAttachments as rt, recoverInitialization as s, DEPLOYMENT_APPROVAL_TTL_MS as sn, terminals as st, inspectDatabase as t, GitLogQuerySchema as tn, MAX_EDITABLE_FILE_BYTES as tr, serviceOpsServices as tt, resolveConfig as u, DEPLOYMENT_ARTIFACT_MAX_PATH as un, webSearchConnections as ut, MODEL_PROVIDER_IDS as v, DeploymentSpecSchema as vn, RESOURCE_EVENT_RETENTION_MS as vt, authSettings as w, ServiceControlInputSchema as wn, ServiceSubscriptionSchema as wt, agentEvents as x, DeploymentTargetRefSchema as xn, ServiceIdSchema as xt, WEB_SEARCH_PROVIDER_IDS as y, DeploymentTargetIdSchema as yn, ResourceEventsQuerySchema as yt, modelCatalogCache as z, CommandRequestSchema as zn, ProcessIdSchema as zt };
@@ -0,0 +1,263 @@
1
+ import { a as isProcessAlive, i as inspectInstanceLock, p as findServerRoot } from "./inspect-XgAc84F9.js";
2
+ import { t as ipcTokenPath } from "./address-D0ZG5qR4.js";
3
+ import { n as connectIpc } from "./client-D_Ni3Zpx.js";
4
+ import { r as resolveDataDir } from "./paths-BhVn34MT.js";
5
+ import { t as loadManagedConfig } from "./supervisor-IYDKL4iU.js";
6
+ import { createRequire } from "node:module";
7
+ import { existsSync } from "node:fs";
8
+ import path from "node:path";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { spawn } from "node:child_process";
11
+ import { chmod, mkdir, open, rename, stat } from "node:fs/promises";
12
+ // src/cli/lifecycle.ts
13
+ const READY_TIMEOUT_MS = 9e4;
14
+ const STOP_TIMEOUT_MS = 15e3;
15
+ const DAEMON_LOG_LIMIT_BYTES = 5242880;
16
+ function serverRoot() {
17
+ return findServerRoot(path.dirname(fileURLToPath(import.meta.url)));
18
+ }
19
+ function daemonLogPath(dataDir) {
20
+ return path.join(dataDir, "logs", "daemon.log");
21
+ }
22
+ async function httpOk(url, timeoutMs = 1500) {
23
+ try {
24
+ const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
25
+ await response.arrayBuffer();
26
+ return response.ok;
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+ async function waitUntil(check, timeoutMs, intervalMs = 150) {
32
+ const deadline = Date.now() + timeoutMs;
33
+ while (Date.now() < deadline) {
34
+ if (await check()) return true;
35
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
36
+ }
37
+ return false;
38
+ }
39
+ async function rotateDaemonLog(file) {
40
+ try {
41
+ if ((await stat(file)).size < DAEMON_LOG_LIMIT_BYTES) return;
42
+ await rename(file, `${file}.1`);
43
+ } catch (error) {
44
+ if (error.code !== "ENOENT") throw error;
45
+ }
46
+ }
47
+ async function openDaemonLog(dataDir) {
48
+ const logsDir = path.join(dataDir, "logs");
49
+ await mkdir(logsDir, {
50
+ recursive: true,
51
+ mode: 448
52
+ });
53
+ const file = daemonLogPath(dataDir);
54
+ await rotateDaemonLog(file);
55
+ const handle = await open(file, "a", 384);
56
+ if (process.platform !== "win32") await chmod(file, 384);
57
+ return handle;
58
+ }
59
+ function webDistDir(root, env) {
60
+ return env.LARNESS_WEB_DIST ?? path.resolve(root, "../../apps/web/dist");
61
+ }
62
+ function tuiEntry(root) {
63
+ const dist = path.join(root, "dist", "tui.js");
64
+ if (existsSync(dist)) return {
65
+ command: process.execPath,
66
+ args: [dist, "--attach"]
67
+ };
68
+ const source = path.join(root, "src", "tui", "main.ts");
69
+ if (!existsSync(source)) return null;
70
+ const require = createRequire(path.join(root, "package.json"));
71
+ const loader = pathToFileURL(require.resolve("tsx/esm")).href;
72
+ return {
73
+ command: process.execPath,
74
+ args: [
75
+ "--import",
76
+ loader,
77
+ source,
78
+ "--attach"
79
+ ]
80
+ };
81
+ }
82
+ async function requestShutdown(dataDir) {
83
+ try {
84
+ const client = await connectIpc({
85
+ dataDir,
86
+ client: "cli",
87
+ timeoutMs: 2e3
88
+ });
89
+ try {
90
+ await client.request("server.shutdown", {
91
+ confirm: true,
92
+ source: "cli"
93
+ }, 5e3);
94
+ return true;
95
+ } finally {
96
+ client.close();
97
+ }
98
+ } catch {
99
+ return false;
100
+ }
101
+ }
102
+ async function startCommand(io, options = {}) {
103
+ const dataDir = resolveDataDir(io.env);
104
+ const loaded = await loadManagedConfig(dataDir, io.env);
105
+ const port = loaded.config.server.port;
106
+ const health = `http://127.0.0.1:${port}/api/health`;
107
+ if (await httpOk(health)) {
108
+ const lock = await inspectInstanceLock(dataDir);
109
+ const pid = lock?.record?.pid;
110
+ const mode = lock?.record?.mode ?? "unknown";
111
+ const dev = lock?.record?.dev === true ? " dev" : "";
112
+ io.stdout(`[larness] already running (${mode}${dev})${pid ? `, pid ${pid}` : ""}\n`);
113
+ io.stdout(`[larness] web ${loaded.config.server.publicUrl ?? `http://localhost:${port}`}\n`);
114
+ return 0;
115
+ }
116
+ const root = options.root ?? serverRoot();
117
+ const entry = path.join(root, "dist", "index.js");
118
+ if (!existsSync(entry)) {
119
+ io.stderr("[larness] start needs a built server: apps/server/dist/index.js is missing.\n");
120
+ io.stderr("[larness] run `pnpm build` for a packaged run, or `pnpm dev` for development.\n");
121
+ return 1;
122
+ }
123
+ const webDist = options.webDist ?? webDistDir(root, io.env);
124
+ if (io.env.LARNESS_SERVE_WEB !== "0" && !existsSync(path.join(webDist, "index.html"))) {
125
+ io.stderr("[larness] the built web app is missing: apps/web/dist/index.html not found.\n");
126
+ io.stderr("[larness] run `pnpm build` before `larness start`.\n");
127
+ return 1;
128
+ }
129
+ let logHandle;
130
+ try {
131
+ logHandle = await openDaemonLog(dataDir);
132
+ } catch (error) {
133
+ io.stderr(`[larness] cannot open ${daemonLogPath(dataDir)}: ${error instanceof Error ? error.message : String(error)}\n`);
134
+ return 1;
135
+ }
136
+ let child;
137
+ try {
138
+ child = spawn(process.execPath, [entry], {
139
+ cwd: root,
140
+ detached: true,
141
+ stdio: [
142
+ "ignore",
143
+ logHandle.fd,
144
+ logHandle.fd
145
+ ],
146
+ env: {
147
+ ...io.env,
148
+ LARNESS_LIFECYCLE_MODE: "background",
149
+ LARNESS_LOG_STDERR: "0",
150
+ LARNESS_PM2_AUTO_INSTALL: io.env.LARNESS_PM2_AUTO_INSTALL ?? "1"
151
+ }
152
+ });
153
+ } finally {
154
+ await logHandle.close();
155
+ }
156
+ child.unref();
157
+ if (child.pid === void 0) {
158
+ io.stderr("[larness] failed to spawn the server process.\n");
159
+ return 1;
160
+ }
161
+ const pid = child.pid;
162
+ const token = ipcTokenPath(dataDir);
163
+ if (!await waitUntil(async () => {
164
+ if (!isProcessAlive(pid)) return false;
165
+ if ((await inspectInstanceLock(dataDir))?.record?.pid !== pid) return false;
166
+ return existsSync(token) && await httpOk(health);
167
+ }, options.readyTimeoutMs ?? READY_TIMEOUT_MS)) {
168
+ if ((await inspectInstanceLock(dataDir))?.record?.pid === pid && await requestShutdown(dataDir)) await waitUntil(async () => !isProcessAlive(pid), 1e4);
169
+ io.stderr(`[larness] the server did not become ready in ${(options.readyTimeoutMs ?? READY_TIMEOUT_MS) / 1e3}s.\n`);
170
+ io.stderr(`[larness] pid ${pid}; see ${daemonLogPath(dataDir)}\n`);
171
+ return 1;
172
+ }
173
+ const webUrl = loaded.config.server.publicUrl ?? `http://localhost:${port}`;
174
+ io.stdout(`[larness] server started, pid ${pid}\n`);
175
+ io.stdout(`[larness] web ${webUrl}\n`);
176
+ io.stdout(`[larness] logs ${daemonLogPath(dataDir)}\n`);
177
+ return 0;
178
+ }
179
+ async function stopCommand(io) {
180
+ const dataDir = resolveDataDir(io.env);
181
+ const lock = await inspectInstanceLock(dataDir);
182
+ if (lock === null) {
183
+ io.stdout("[larness] not running\n");
184
+ return 0;
185
+ }
186
+ if (!lock.alive) {
187
+ io.stdout("[larness] not running (stale lock; it is replaced on the next start)\n");
188
+ return 0;
189
+ }
190
+ const pid = lock.record?.pid ?? null;
191
+ if (!await requestShutdown(dataDir)) {
192
+ io.stderr("[larness] the server is running but its IPC endpoint is unreachable.\n");
193
+ io.stderr(`[larness] pid ${pid ?? "unknown"}; data ${dataDir}\n`);
194
+ io.stderr("[larness] no signal was sent and the lock was left untouched.\n");
195
+ return 1;
196
+ }
197
+ if (!await waitUntil(async () => {
198
+ const current = await inspectInstanceLock(dataDir);
199
+ return current === null || !current.alive;
200
+ }, STOP_TIMEOUT_MS)) {
201
+ io.stderr(`[larness] the server did not stop within ${STOP_TIMEOUT_MS / 1e3}s.\n`);
202
+ io.stderr(`[larness] pid ${pid ?? "unknown"}; it may still be running.\n`);
203
+ return 1;
204
+ }
205
+ io.stdout("[larness] management server stopped.\n");
206
+ io.stdout("[larness] PM2 services and deployments keep running.\n");
207
+ return 0;
208
+ }
209
+ async function restartCommand(io) {
210
+ const dataDir = resolveDataDir(io.env);
211
+ const lock = await inspectInstanceLock(dataDir);
212
+ const record = lock?.alive === true ? lock.record : null;
213
+ if (record?.mode === "foreground" || record?.dev === true) {
214
+ io.stderr("[larness] this is a foreground dev instance started by `pnpm dev`.\n");
215
+ io.stderr("[larness] restart it in that terminal; `larness restart` will not take it over.\n");
216
+ return 1;
217
+ }
218
+ const stopped = await stopCommand(io);
219
+ if (stopped !== 0) return stopped;
220
+ return startCommand(io);
221
+ }
222
+ async function tuiCommand(io) {
223
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
224
+ io.stderr("[larness] the TUI needs an interactive terminal (TTY).\n");
225
+ return 1;
226
+ }
227
+ const dataDir = resolveDataDir(io.env);
228
+ const lock = await inspectInstanceLock(dataDir);
229
+ if (lock === null || !lock.alive) {
230
+ io.stderr("[larness] not running; run `larness start` first.\n");
231
+ return 3;
232
+ }
233
+ const root = serverRoot();
234
+ const entry = tuiEntry(root);
235
+ if (entry === null) {
236
+ io.stderr("[larness] apps/server/dist/tui.js is missing; run `pnpm build`.\n");
237
+ return 1;
238
+ }
239
+ return await new Promise((resolve) => {
240
+ const child = spawn(entry.command, entry.args, {
241
+ cwd: root,
242
+ stdio: "inherit",
243
+ env: io.env
244
+ });
245
+ const swallowInterrupt = () => void 0;
246
+ const forwardTerm = () => child.kill("SIGTERM");
247
+ process.on("SIGINT", swallowInterrupt);
248
+ process.on("SIGTERM", forwardTerm);
249
+ const finish = (code) => {
250
+ process.off("SIGINT", swallowInterrupt);
251
+ process.off("SIGTERM", forwardTerm);
252
+ resolve(code);
253
+ };
254
+ child.once("error", () => {
255
+ io.stderr("[larness] failed to start the TUI process.\n");
256
+ finish(1);
257
+ });
258
+ child.once("exit", (code, signal) => {
259
+ finish(code ?? (signal === null ? 1 : 1));
260
+ });
261
+ });
262
+ }
263
+ export { restartCommand, startCommand, stopCommand, tuiCommand };
@@ -0,0 +1,26 @@
1
+ import path from "node:path";
2
+ import { readdir, stat } from "node:fs/promises";
3
+ // src/log-files.ts
4
+ const MAIN_LOG_PATTERN = /^larness(\..+)?\.log$/;
5
+ async function findMainLogFile(dataDir) {
6
+ const logsDir = path.join(dataDir, "logs");
7
+ let entries;
8
+ try {
9
+ entries = await readdir(logsDir);
10
+ } catch {
11
+ return null;
12
+ }
13
+ let newest = null;
14
+ for (const entry of entries) {
15
+ if (!MAIN_LOG_PATTERN.test(entry)) continue;
16
+ try {
17
+ const info = await stat(path.join(logsDir, entry));
18
+ if (newest === null || info.mtimeMs > newest.mtime) newest = {
19
+ file: path.join(logsDir, entry),
20
+ mtime: info.mtimeMs
21
+ };
22
+ } catch {}
23
+ }
24
+ return newest?.file ?? null;
25
+ }
26
+ export { findMainLogFile as t };