larness 0.0.0-stage → 0.1.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 (160) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +205 -2
  3. package/app.js +131 -0
  4. package/apps/server/dist/address-UO6lb2Hx.js +95 -0
  5. package/apps/server/dist/client-DGXcZxzL.js +121 -0
  6. package/apps/server/dist/doctor-CTealIcx.js +131 -0
  7. package/apps/server/dist/doctor.js +13 -0
  8. package/apps/server/dist/index.js +25481 -0
  9. package/apps/server/dist/lock-8kmtcopF.js +102 -0
  10. package/apps/server/dist/managed-CHal_mk1.js +216 -0
  11. package/apps/server/dist/paths-Bp1nTSw3.js +2434 -0
  12. package/apps/server/dist/status-Dyecl2ni.js +50 -0
  13. package/apps/server/dist/status.js +31 -0
  14. package/apps/server/dist/tui.js +1628 -0
  15. package/apps/server/drizzle/0001_auth.sql +110 -0
  16. package/apps/server/drizzle/0002_projects.sql +13 -0
  17. package/apps/server/drizzle/0003_workspace.sql +81 -0
  18. package/apps/server/drizzle/0004_models.sql +30 -0
  19. package/apps/server/drizzle/0005_resources.sql +54 -0
  20. package/apps/server/drizzle/0006_commands.sql +24 -0
  21. package/apps/server/drizzle/0007_terminals.sql +42 -0
  22. package/apps/server/drizzle/0008_resource_actions.sql +24 -0
  23. package/apps/server/drizzle/0009_terminal_title.sql +1 -0
  24. package/apps/server/drizzle/0010_services.sql +32 -0
  25. package/apps/server/drizzle/0011_deployments.sql +88 -0
  26. package/apps/server/drizzle/0012_deployment_authorizations.sql +67 -0
  27. package/apps/server/drizzle/0013_service_ops.sql +64 -0
  28. package/apps/server/drizzle/0014_service_actions.sql +36 -0
  29. package/apps/server/drizzle/0015_model_catalog.sql +17 -0
  30. package/apps/server/drizzle/0016_multi_provider.sql +2 -0
  31. package/apps/server/drizzle/0017_model_visibility.sql +10 -0
  32. package/apps/server/drizzle/0018_model_defaults.sql +9 -0
  33. package/apps/server/drizzle/0019_credential_endpoint.sql +1 -0
  34. package/apps/server/drizzle/0020_compatible_context.sql +1 -0
  35. package/apps/server/drizzle/0021_context_summaries.sql +13 -0
  36. package/apps/server/drizzle/0022_scheduler.sql +58 -0
  37. package/apps/server/drizzle/meta/0001_snapshot.json +705 -0
  38. package/apps/server/drizzle/meta/0002_snapshot.json +784 -0
  39. package/apps/server/drizzle/meta/0003_snapshot.json +1300 -0
  40. package/apps/server/drizzle/meta/0004_snapshot.json +1489 -0
  41. package/apps/server/drizzle/meta/0005_snapshot.json +1794 -0
  42. package/apps/server/drizzle/meta/0006_snapshot.json +1953 -0
  43. package/apps/server/drizzle/meta/0007_snapshot.json +2232 -0
  44. package/apps/server/drizzle/meta/0008_snapshot.json +2391 -0
  45. package/apps/server/drizzle/meta/0009_snapshot.json +2398 -0
  46. package/apps/server/drizzle/meta/0010_snapshot.json +2601 -0
  47. package/apps/server/drizzle/meta/0015_snapshot.json +4332 -0
  48. package/apps/server/drizzle/meta/0016_snapshot.json +4346 -0
  49. package/apps/server/drizzle/meta/0017_snapshot.json +4408 -0
  50. package/apps/server/drizzle/meta/0018_snapshot.json +4468 -0
  51. package/apps/server/drizzle/meta/0019_snapshot.json +4475 -0
  52. package/apps/server/drizzle/meta/0020_snapshot.json +4482 -0
  53. package/apps/server/drizzle/meta/0021_snapshot.json +4565 -0
  54. package/apps/server/drizzle/meta/0022_snapshot.json +4960 -0
  55. package/apps/server/drizzle/meta/_journal.json +160 -0
  56. package/apps/server/package.json +57 -0
  57. package/apps/web/dist/assets/FileEditor-DpVfk7t3.js +1 -0
  58. package/apps/web/dist/assets/FileViewer-Bv5VYaA3.js +1 -0
  59. package/apps/web/dist/assets/abap-DLDM7-KI.js +1 -0
  60. package/apps/web/dist/assets/apex-DNDY2TF8.js +1 -0
  61. package/apps/web/dist/assets/azcli-Y6nb8tq_.js +1 -0
  62. package/apps/web/dist/assets/bat-BwHxbl9M.js +1 -0
  63. package/apps/web/dist/assets/bicep-CFznDFnq.js +2 -0
  64. package/apps/web/dist/assets/cameligo-Bf6VGUru.js +1 -0
  65. package/apps/web/dist/assets/clojure-Dnu-v4kV.js +1 -0
  66. package/apps/web/dist/assets/codicon-DF1abBS2.ttf +0 -0
  67. package/apps/web/dist/assets/coffee-Bd8akH9Z.js +1 -0
  68. package/apps/web/dist/assets/cpp-BbWJElDN.js +1 -0
  69. package/apps/web/dist/assets/csharp-Co3qMtFm.js +1 -0
  70. package/apps/web/dist/assets/csp-D-4FJmMZ.js +1 -0
  71. package/apps/web/dist/assets/css-DdJfP1eB.js +3 -0
  72. package/apps/web/dist/assets/css.worker-C_6RgliQ.js +97 -0
  73. package/apps/web/dist/assets/cssMode-EHCHSzzL.js +1 -0
  74. package/apps/web/dist/assets/cypher-cTPe9QuQ.js +1 -0
  75. package/apps/web/dist/assets/dart-BOtBlQCF.js +1 -0
  76. package/apps/web/dist/assets/dockerfile-BG73LgW2.js +1 -0
  77. package/apps/web/dist/assets/ecl-BEgZUVRK.js +1 -0
  78. package/apps/web/dist/assets/editor.worker-D1TDBLlL.js +30 -0
  79. package/apps/web/dist/assets/elixir-BkW5O-1t.js +1 -0
  80. package/apps/web/dist/assets/flow9-BeJ5waoc.js +1 -0
  81. package/apps/web/dist/assets/freemarker2-CYDUi4bR.js +3 -0
  82. package/apps/web/dist/assets/fsharp-PahG7c26.js +1 -0
  83. package/apps/web/dist/assets/go-acbASCJo.js +1 -0
  84. package/apps/web/dist/assets/graphql-BxJiqAUM.js +1 -0
  85. package/apps/web/dist/assets/handlebars-Bl5r-XBz.js +1 -0
  86. package/apps/web/dist/assets/hcl-DtV1sZF8.js +1 -0
  87. package/apps/web/dist/assets/html-Dimr8AuT.js +1 -0
  88. package/apps/web/dist/assets/html.worker-CLyYFd_g.js +474 -0
  89. package/apps/web/dist/assets/htmlMode-DbKEQN5e.js +1 -0
  90. package/apps/web/dist/assets/index-CiO_U1kt.js +158 -0
  91. package/apps/web/dist/assets/index-Cn8Mc6ux.css +1 -0
  92. package/apps/web/dist/assets/ini-Kd9XrMLS.js +1 -0
  93. package/apps/web/dist/assets/java-CXBNlu9o.js +1 -0
  94. package/apps/web/dist/assets/javascript-CAsmnqI3.js +1 -0
  95. package/apps/web/dist/assets/json.worker-BggoxaER.js +62 -0
  96. package/apps/web/dist/assets/jsonMode-FAO7KTW2.js +7 -0
  97. package/apps/web/dist/assets/julia-cl7-CwDS.js +1 -0
  98. package/apps/web/dist/assets/kotlin-s7OhZKlX.js +1 -0
  99. package/apps/web/dist/assets/less-9HpZscsL.js +2 -0
  100. package/apps/web/dist/assets/lexon-OrD6JF1K.js +1 -0
  101. package/apps/web/dist/assets/liquid-5H_43_EZ.js +1 -0
  102. package/apps/web/dist/assets/lspLanguageFeatures-DnuYc3pX.js +4 -0
  103. package/apps/web/dist/assets/lua-Cyyb5UIc.js +1 -0
  104. package/apps/web/dist/assets/m3-B8OfTtLu.js +1 -0
  105. package/apps/web/dist/assets/markdown-BFxVWTOG.js +1 -0
  106. package/apps/web/dist/assets/mdx-DJvtDn95.js +1 -0
  107. package/apps/web/dist/assets/mips-CiqrrVzr.js +1 -0
  108. package/apps/web/dist/assets/monaco-BEZSi3GX.js +1005 -0
  109. package/apps/web/dist/assets/monaco-Ced-qlZg.css +1 -0
  110. package/apps/web/dist/assets/msdax-DmeGPVcC.js +1 -0
  111. package/apps/web/dist/assets/mysql-C_tMU-Nz.js +1 -0
  112. package/apps/web/dist/assets/objective-c-BDtDVThU.js +1 -0
  113. package/apps/web/dist/assets/pascal-vHIfCaH5.js +1 -0
  114. package/apps/web/dist/assets/pascaligo-DtZ0uQbO.js +1 -0
  115. package/apps/web/dist/assets/perl-Ub6l9XKa.js +1 -0
  116. package/apps/web/dist/assets/pgsql-BlNEE0v7.js +1 -0
  117. package/apps/web/dist/assets/php-BBUBE1dy.js +1 -0
  118. package/apps/web/dist/assets/pla-DSh2-awV.js +1 -0
  119. package/apps/web/dist/assets/postiats-CocnycG-.js +1 -0
  120. package/apps/web/dist/assets/powerquery-tScXyioY.js +1 -0
  121. package/apps/web/dist/assets/powershell-COWaemsV.js +1 -0
  122. package/apps/web/dist/assets/protobuf-Brw8urJB.js +2 -0
  123. package/apps/web/dist/assets/pug-8SOpv6rk.js +1 -0
  124. package/apps/web/dist/assets/python-D4581wh8.js +1 -0
  125. package/apps/web/dist/assets/qsharp-Bw9ernYp.js +1 -0
  126. package/apps/web/dist/assets/r-j7ic8hl3.js +1 -0
  127. package/apps/web/dist/assets/razor-Cob92s3y.js +1 -0
  128. package/apps/web/dist/assets/redis-Bu5POkcn.js +1 -0
  129. package/apps/web/dist/assets/redshift-Bs9aos_-.js +1 -0
  130. package/apps/web/dist/assets/restructuredtext-CqXO7rUv.js +1 -0
  131. package/apps/web/dist/assets/ruby-zBfavPgS.js +1 -0
  132. package/apps/web/dist/assets/rust-BzKRNQWT.js +1 -0
  133. package/apps/web/dist/assets/sb-BBc9UKZt.js +1 -0
  134. package/apps/web/dist/assets/scala-D9hQfWCl.js +1 -0
  135. package/apps/web/dist/assets/scheme-BPhDTwHR.js +1 -0
  136. package/apps/web/dist/assets/scss-CBJaRo0y.js +3 -0
  137. package/apps/web/dist/assets/shell-DiJ1NA_G.js +1 -0
  138. package/apps/web/dist/assets/solidity-Db0IVjzk.js +1 -0
  139. package/apps/web/dist/assets/sophia-CnS9iZB_.js +1 -0
  140. package/apps/web/dist/assets/sparql-CJmd_6j2.js +1 -0
  141. package/apps/web/dist/assets/sql-ClhHkBeG.js +1 -0
  142. package/apps/web/dist/assets/st-CHwy0fLd.js +1 -0
  143. package/apps/web/dist/assets/swift-CnmFD0ga.js +1 -0
  144. package/apps/web/dist/assets/systemverilog-Bs9z6M-B.js +1 -0
  145. package/apps/web/dist/assets/tcl-Dm6ycUr_.js +1 -0
  146. package/apps/web/dist/assets/ts.worker-BrLZGe_E.js +67722 -0
  147. package/apps/web/dist/assets/tsMode-WJsr57wC.js +11 -0
  148. package/apps/web/dist/assets/twig-Csy3S7wG.js +1 -0
  149. package/apps/web/dist/assets/typescript-8M7GiCNW.js +1 -0
  150. package/apps/web/dist/assets/typespec-Btyra-wh.js +1 -0
  151. package/apps/web/dist/assets/vb-Db0cS2oM.js +1 -0
  152. package/apps/web/dist/assets/wgsl-BTesnYfV.js +298 -0
  153. package/apps/web/dist/assets/workers-FOC7l7Wh.js +1 -0
  154. package/apps/web/dist/assets/xml-Hm5ZZqOZ.js +1 -0
  155. package/apps/web/dist/assets/yaml-E7sEyvM5.js +1 -0
  156. package/apps/web/dist/favicon.svg +4 -0
  157. package/apps/web/dist/index.html +15 -0
  158. package/docs/README.md +26 -0
  159. package/docs/guides/install.md +63 -0
  160. package/package.json +94 -4
@@ -0,0 +1,2434 @@
1
+ import "node:module";
2
+ import { closeSync, constants, existsSync, fsyncSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { randomUUID } from "node:crypto";
6
+ import { access, chmod, mkdir, readFile, stat } from "node:fs/promises";
7
+ import { z } from "zod";
8
+ import { eq, sql } from "drizzle-orm";
9
+ import { check, index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
10
+ import BetterSqlite3 from "better-sqlite3";
11
+ import { migrate } from "drizzle-orm/better-sqlite3/migrator";
12
+ import envPaths from "env-paths";
13
+ //#region \0rolldown/runtime.js
14
+ var __defProp = Object.defineProperty;
15
+ var __exportAll = (all, no_symbols) => {
16
+ let target = {};
17
+ for (var name in all) __defProp(target, name, {
18
+ get: all[name],
19
+ enumerable: true
20
+ });
21
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
22
+ return target;
23
+ };
24
+ z.enum([
25
+ "project",
26
+ "default",
27
+ "session"
28
+ ]);
29
+ const MAX_EDITABLE_FILE_BYTES = 512 * 1024;
30
+ const resourceId = z.string().min(1).max(128);
31
+ const FileScopeSchema = z.union([
32
+ z.object({ workspace: z.literal("default") }).strict(),
33
+ z.object({ projectId: resourceId }).strict(),
34
+ z.object({ sessionId: resourceId }).strict()
35
+ ]);
36
+ const FilePathSchema = z.string().min(1).max(4096).refine((value) => {
37
+ const normalized = value.replaceAll("\\", "/");
38
+ return !normalized.startsWith("/") && !normalized.includes("\0") && normalized.split("/").every((part) => part !== ".." && !part.includes(":"));
39
+ }, "Expected a relative path inside the authorized root").transform((value) => value.replaceAll("\\", "/"));
40
+ const FileVersionSchema = z.string().regex(/^[a-f0-9]{64}$/);
41
+ const FileSaveSchema = z.object({
42
+ scope: FileScopeSchema,
43
+ path: FilePathSchema,
44
+ content: z.string().max(1024 * 1024),
45
+ expectedVersion: FileVersionSchema
46
+ }).strict();
47
+ const FileReadQuerySchema = z.union([
48
+ z.object({
49
+ workspace: z.literal("default"),
50
+ path: FilePathSchema,
51
+ version: FileVersionSchema.optional()
52
+ }).strict(),
53
+ z.object({
54
+ projectId: resourceId,
55
+ path: FilePathSchema,
56
+ version: FileVersionSchema.optional()
57
+ }).strict(),
58
+ z.object({
59
+ sessionId: resourceId,
60
+ path: FilePathSchema,
61
+ version: FileVersionSchema.optional()
62
+ }).strict()
63
+ ]);
64
+ const FileListQuerySchema = z.object({
65
+ path: FilePathSchema.default("."),
66
+ limit: z.coerce.number().int().min(1).max(200).default(50),
67
+ cursor: z.string().min(1).max(2048).optional()
68
+ }).strict();
69
+ const FileSaveResultSchema = z.object({
70
+ path: z.string(),
71
+ realPath: z.string(),
72
+ content: z.string(),
73
+ version: FileVersionSchema,
74
+ size: z.number().int().nonnegative(),
75
+ encoding: z.literal("utf-8")
76
+ }).omit({
77
+ content: true,
78
+ encoding: true
79
+ }).extend({ previousVersion: FileVersionSchema });
80
+ const FileEntrySchema = z.object({
81
+ path: z.string(),
82
+ name: z.string(),
83
+ type: z.enum(["file", "directory"]),
84
+ size: z.number().int().nonnegative().optional()
85
+ });
86
+ z.object({
87
+ items: z.array(FileEntrySchema),
88
+ nextCursor: z.string().nullable(),
89
+ revision: FileVersionSchema
90
+ });
91
+ const FileResultTargetSchema = z.object({
92
+ kind: z.literal("file"),
93
+ scope: FileScopeSchema,
94
+ path: FilePathSchema,
95
+ version: FileVersionSchema.optional()
96
+ }).strict();
97
+ //#endregion
98
+ //#region ../../packages/shared/src/commands.ts
99
+ const CommandParamsSchema = z.object({
100
+ executable: z.string().min(1).max(4096).refine((value) => !value.includes("\0")),
101
+ args: z.array(z.string().max(8192).refine((value) => !value.includes("\0"))).max(256),
102
+ cwd: FilePathSchema.default("."),
103
+ timeoutMs: z.number().int().min(1).max(6e5).default(12e4)
104
+ }).strict().refine((value) => value.args.reduce((size, arg) => size + arg.length, value.executable.length) <= 65536);
105
+ const CommandStatusSchema = z.enum([
106
+ "CREATED",
107
+ "RUNNING",
108
+ "CANCELLING",
109
+ "COMPLETED",
110
+ "FAILED",
111
+ "CANCELLED",
112
+ "TIMED_OUT",
113
+ "INTERRUPTED"
114
+ ]);
115
+ const CommandOutputQuerySchema = z.object({
116
+ after: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
117
+ limit: z.coerce.number().int().min(1).max(500).default(100)
118
+ }).strict();
119
+ const CommandOutputChunkSchema = z.object({
120
+ cursor: z.number().int().positive(),
121
+ data: z.string().max(16 * 1024).refine((data) => new TextEncoder().encode(data).byteLength <= 16 * 1024),
122
+ channel: z.enum(["stdout", "stderr"]),
123
+ timestamp: z.number().int()
124
+ }).strict();
125
+ const CommandStatusPayloadSchema = z.object({
126
+ status: CommandStatusSchema,
127
+ exitCode: z.number().int().nullable(),
128
+ reasonCode: z.string().nullable(),
129
+ truncated: z.boolean(),
130
+ startedAt: z.number().nullable(),
131
+ endedAt: z.number().nullable()
132
+ });
133
+ const CommandCancelSchema = z.object({}).strict();
134
+ const COMMAND_OUTPUT_RETENTION_MS = 10080 * 6e4;
135
+ const COMMAND_RETENTION_MS = 720 * 60 * 6e4;
136
+ const CommandIdSchema = z.string().regex(/^cmd_[a-f0-9-]{36}$/);
137
+ const CommandSubscriptionSchema = z.object({
138
+ topic: z.literal("command"),
139
+ resourceId: CommandIdSchema,
140
+ after: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0)
141
+ }).strict();
142
+ const CommandStatusEventSchema = z.object({
143
+ kind: z.literal("event"),
144
+ protocolVersion: z.literal(1),
145
+ topic: z.literal("command"),
146
+ eventId: z.string(),
147
+ streamId: CommandIdSchema,
148
+ resourceId: CommandIdSchema,
149
+ sequence: z.number().int().nonnegative(),
150
+ timestamp: z.number(),
151
+ type: z.literal("command.status"),
152
+ payload: CommandStatusPayloadSchema
153
+ });
154
+ z.object({
155
+ id: CommandIdSchema,
156
+ scope: z.object({ projectId: z.string() }).strict().or(z.object({ sessionId: z.string() }).strict()),
157
+ status: CommandStatusSchema,
158
+ exitCode: z.number().nullable(),
159
+ reasonCode: z.string().nullable(),
160
+ truncated: z.boolean(),
161
+ startedAt: z.number().nullable(),
162
+ endedAt: z.number().nullable(),
163
+ currentSequence: z.number().int().nonnegative()
164
+ });
165
+ z.object({
166
+ chunks: z.array(CommandOutputChunkSchema).max(500),
167
+ oldestCursor: z.number().int().positive(),
168
+ nextCursor: z.number().int().nonnegative(),
169
+ truncated: z.boolean(),
170
+ resyncRequired: z.boolean()
171
+ });
172
+ CommandOutputChunkSchema.extend({
173
+ kind: z.literal("command.output"),
174
+ resourceId: CommandIdSchema
175
+ }).strict();
176
+ //#endregion
177
+ //#region ../../packages/shared/src/config.ts
178
+ const LOG_LEVELS = [
179
+ "trace",
180
+ "debug",
181
+ "info",
182
+ "warn",
183
+ "error",
184
+ "fatal"
185
+ ];
186
+ const UPDATE_CHANNELS = ["stable", "beta"];
187
+ const LogLevelSchema = z.enum(LOG_LEVELS);
188
+ const UpdateChannelSchema = z.enum(UPDATE_CHANNELS);
189
+ function isOriginUrl(value) {
190
+ let url;
191
+ try {
192
+ url = new URL(value);
193
+ } catch {
194
+ return false;
195
+ }
196
+ return (url.protocol === "http:" || url.protocol === "https:") && url.username === "" && url.password === "" && url.pathname === "/" && url.search === "" && url.hash === "";
197
+ }
198
+ const OriginUrlSchema = z.string().max(2048).refine(isOriginUrl, "must be an http(s) origin without path, query or credentials");
199
+ const ServerConfigSchema = z.strictObject({
200
+ host: z.string().min(1).max(255),
201
+ port: z.int().min(1).max(65535),
202
+ publicUrl: OriginUrlSchema.nullable(),
203
+ trustedProxies: z.array(z.string().min(1)).max(64)
204
+ });
205
+ const AuthConfigSchema = z.strictObject({
206
+ sessionTtlMinutes: z.int().min(1).max(43200),
207
+ idleTtlMinutes: z.int().min(1).max(43200),
208
+ requireHttpsForRemote: z.boolean()
209
+ });
210
+ const WebAuthnConfigSchema = z.strictObject({
211
+ rpId: z.string().min(1).max(253),
212
+ rpName: z.string().min(1).max(128),
213
+ origin: OriginUrlSchema
214
+ });
215
+ const LoggingConfigSchema = z.strictObject({
216
+ level: LogLevelSchema,
217
+ retentionDays: z.int().min(1).max(3650)
218
+ });
219
+ const UpdatesConfigSchema = z.strictObject({
220
+ channel: UpdateChannelSchema,
221
+ autoCheck: z.boolean(),
222
+ autoInstall: z.boolean()
223
+ });
224
+ const PreviewConfigSchema = z.strictObject({
225
+ enabled: z.boolean(),
226
+ port: z.number().int().min(1).max(65535).default(3211)
227
+ });
228
+ const AppConfigSchema = z.strictObject({
229
+ version: z.literal(1),
230
+ server: ServerConfigSchema,
231
+ auth: AuthConfigSchema,
232
+ webauthn: WebAuthnConfigSchema,
233
+ logging: LoggingConfigSchema,
234
+ updates: UpdatesConfigSchema,
235
+ preview: PreviewConfigSchema
236
+ });
237
+ const DEFAULT_APP_CONFIG = {
238
+ version: 1,
239
+ server: {
240
+ host: "127.0.0.1",
241
+ port: 3210,
242
+ publicUrl: null,
243
+ trustedProxies: []
244
+ },
245
+ auth: {
246
+ sessionTtlMinutes: 720,
247
+ idleTtlMinutes: 30,
248
+ requireHttpsForRemote: true
249
+ },
250
+ webauthn: {
251
+ rpId: "localhost",
252
+ rpName: "Larness",
253
+ origin: "http://localhost:3210"
254
+ },
255
+ logging: {
256
+ level: "info",
257
+ retentionDays: 14
258
+ },
259
+ updates: {
260
+ channel: "stable",
261
+ autoCheck: true,
262
+ autoInstall: false
263
+ },
264
+ preview: {
265
+ enabled: false,
266
+ port: 3211
267
+ }
268
+ };
269
+ function isIpHostname(hostname) {
270
+ const host = hostname.replace(/^\[/, "").replace(/\]$/, "");
271
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true;
272
+ return host.includes(":") && /^[0-9a-f:]+$/i.test(host);
273
+ }
274
+ function deriveWebAuthn(server, rpName) {
275
+ const url = new URL(server.publicUrl ?? `http://localhost:${server.port}`);
276
+ const rpId = url.hostname;
277
+ const reason = isIpHostname(rpId) ? "rp_id_is_ip" : url.protocol === "http:" && rpId !== "localhost" ? "remote_http" : null;
278
+ return {
279
+ enabled: reason === null,
280
+ origin: url.origin,
281
+ rpId,
282
+ rpName,
283
+ reason
284
+ };
285
+ }
286
+ //#endregion
287
+ //#region ../../packages/shared/src/deployments.ts
288
+ const ServiceControlInputSchema = z.object({
289
+ action: z.enum([
290
+ "start",
291
+ "stop",
292
+ "restart"
293
+ ]),
294
+ expectedPm2Name: z.string().min(1).max(256),
295
+ requestKey: z.string().min(1).max(256),
296
+ confirmed: z.literal(true)
297
+ }).strict();
298
+ const UUID = "[0-9a-f-]{36}";
299
+ const DeploymentTargetIdSchema = z.string().regex(new RegExp(`^tgt_${UUID}$`));
300
+ const DeploymentBuildIdSchema = z.string().regex(new RegExp(`^bld_${UUID}$`));
301
+ const DeploymentArtifactIdSchema = z.string().regex(new RegExp(`^art_${UUID}$`));
302
+ const DeploymentPlanIdSchema = z.string().regex(new RegExp(`^plan_${UUID}$`));
303
+ const DeploymentTargetNameSchema = z.string().trim().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "must be a simple service name");
304
+ const DeploymentVersionSchema = z.string().trim().min(1).max(64).regex(/^[A-Za-z0-9][A-Za-z0-9._+-]*$/, "must be a simple version label");
305
+ function hasControlCharacters(value) {
306
+ for (const character of value) {
307
+ const code = character.codePointAt(0) ?? 0;
308
+ if (code <= 31 || code === 127) return true;
309
+ }
310
+ return false;
311
+ }
312
+ const noControl = (value) => !hasControlCharacters(value);
313
+ function safeRelative(value, allowDot) {
314
+ if (!value || value.length > 1024 || hasControlCharacters(value) || value.includes("\\")) return false;
315
+ if (value === ".") return allowDot;
316
+ if (value.startsWith("/") || /^[A-Za-z]:/.test(value)) return false;
317
+ return value.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
318
+ }
319
+ const DeploymentCwdSchema = z.string().min(1).max(1024).refine((value) => safeRelative(value, true), "must be a relative path inside the project");
320
+ const DeploymentOutputDirSchema = z.string().min(1).max(1024).refine((value) => safeRelative(value, false), "must be a relative directory inside the project");
321
+ const DeploymentHealthPathSchema = z.string().min(1).max(1024).refine((value) => value.startsWith("/") && !value.includes("..") && !hasControlCharacters(value), "must be an absolute HTTP path without traversal");
322
+ const CommandSchema = z.array(z.string().min(1).max(4096).refine(noControl, "must not contain control characters")).min(1).max(64);
323
+ const DeploymentBuildSpecSchema = z.strictObject({
324
+ command: CommandSchema,
325
+ cwd: DeploymentCwdSchema.default("."),
326
+ outputDir: DeploymentOutputDirSchema,
327
+ timeoutMs: z.int().min(1e3).max(6e5).default(3e5)
328
+ });
329
+ const DeploymentStartSpecSchema = z.strictObject({
330
+ command: CommandSchema,
331
+ cwd: DeploymentCwdSchema.default(".")
332
+ });
333
+ const DeploymentHealthSchema = z.strictObject({
334
+ path: DeploymentHealthPathSchema,
335
+ port: z.int().min(1024).max(65535),
336
+ timeoutMs: z.int().min(1e3).max(12e4).default(3e4),
337
+ intervalMs: z.int().min(100).max(1e4).default(500)
338
+ });
339
+ const DeploymentRecoverySchema = z.strictObject({
340
+ strategy: z.enum(["restart", "none"]),
341
+ maxAttempts: z.int().min(0).max(10).default(3)
342
+ });
343
+ const DeploymentSpecSchema = z.strictObject({
344
+ version: DeploymentVersionSchema,
345
+ build: DeploymentBuildSpecSchema,
346
+ start: DeploymentStartSpecSchema,
347
+ health: DeploymentHealthSchema,
348
+ recovery: DeploymentRecoverySchema
349
+ });
350
+ const DeploymentTargetRefSchema = z.union([z.strictObject({ targetId: DeploymentTargetIdSchema }), z.strictObject({ name: DeploymentTargetNameSchema })]);
351
+ const DeploymentSourceSchema = z.strictObject({
352
+ branch: z.string().max(255).nullable(),
353
+ commit: z.string().max(128).nullable(),
354
+ dirty: z.boolean().nullable()
355
+ });
356
+ z.object({
357
+ id: DeploymentTargetIdSchema,
358
+ projectId: z.string().min(1).max(128),
359
+ name: DeploymentTargetNameSchema,
360
+ currentArtifactId: DeploymentArtifactIdSchema.nullable(),
361
+ currentVersion: DeploymentVersionSchema.nullable(),
362
+ createdAt: z.int(),
363
+ updatedAt: z.int()
364
+ });
365
+ const DeploymentBuildStatusSchema = z.enum([
366
+ "RUNNING",
367
+ "SUCCEEDED",
368
+ "FAILED",
369
+ "CANCELLED"
370
+ ]);
371
+ z.object({
372
+ id: DeploymentBuildIdSchema,
373
+ targetId: DeploymentTargetIdSchema,
374
+ projectId: z.string().min(1).max(128),
375
+ status: DeploymentBuildStatusSchema,
376
+ spec: DeploymentSpecSchema,
377
+ specHash: z.string().regex(/^[a-f0-9]{64}$/),
378
+ reasonCode: z.string().max(64).nullable(),
379
+ logRef: z.string().min(1).max(1024),
380
+ startedAt: z.int().nullable(),
381
+ endedAt: z.int().nullable(),
382
+ createdAt: z.int()
383
+ });
384
+ z.object({
385
+ id: DeploymentArtifactIdSchema,
386
+ buildId: DeploymentBuildIdSchema,
387
+ targetId: DeploymentTargetIdSchema,
388
+ projectId: z.string().min(1).max(128),
389
+ version: DeploymentVersionSchema,
390
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
391
+ sizeBytes: z.int().nonnegative(),
392
+ fileCount: z.int().nonnegative(),
393
+ source: DeploymentSourceSchema,
394
+ createdAt: z.int()
395
+ });
396
+ const DeploymentPlanStatusSchema = z.enum([
397
+ "READY",
398
+ "WAITING_APPROVAL",
399
+ "AUTHORIZED",
400
+ "APPLYING",
401
+ "HEALTH_CHECK",
402
+ "SUCCEEDED",
403
+ "FAILED",
404
+ "CANCELLED",
405
+ "EXPIRED",
406
+ "INVALIDATED",
407
+ "UNKNOWN"
408
+ ]);
409
+ const DeploymentRecoveryPlanSchema = z.strictObject({
410
+ strategy: z.enum(["restart", "none"]),
411
+ maxAttempts: z.int().min(0).max(10),
412
+ previousArtifactAvailable: z.boolean(),
413
+ databaseRollback: z.literal("unsupported")
414
+ });
415
+ const DeploymentImpactSchema = z.strictObject({
416
+ scope: z.literal("single-service"),
417
+ firstDeploy: z.boolean(),
418
+ restartRequired: z.literal(true),
419
+ downtime: z.literal("brief"),
420
+ replacesVersion: DeploymentVersionSchema.nullable(),
421
+ replacesArtifact: DeploymentArtifactIdSchema.nullable()
422
+ });
423
+ const DeploymentPlanDocumentSchema = z.strictObject({
424
+ version: z.literal(1),
425
+ targetId: DeploymentTargetIdSchema,
426
+ projectId: z.string().min(1).max(128),
427
+ artifactId: DeploymentArtifactIdSchema,
428
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
429
+ artifactVersion: DeploymentVersionSchema,
430
+ previousArtifactId: DeploymentArtifactIdSchema.nullable(),
431
+ previousVersion: DeploymentVersionSchema.nullable(),
432
+ specHash: z.string().regex(/^[a-f0-9]{64}$/),
433
+ source: DeploymentSourceSchema,
434
+ health: DeploymentHealthSchema,
435
+ recovery: DeploymentRecoveryPlanSchema,
436
+ impact: DeploymentImpactSchema,
437
+ expiresAt: z.int().positive()
438
+ });
439
+ z.object({
440
+ id: DeploymentPlanIdSchema,
441
+ targetId: DeploymentTargetIdSchema,
442
+ projectId: z.string().min(1).max(128),
443
+ artifactId: DeploymentArtifactIdSchema,
444
+ previousArtifactId: DeploymentArtifactIdSchema.nullable(),
445
+ previousVersion: DeploymentVersionSchema.nullable(),
446
+ version: DeploymentVersionSchema,
447
+ status: DeploymentPlanStatusSchema,
448
+ plan: DeploymentPlanDocumentSchema,
449
+ planHash: z.string().regex(/^[a-f0-9]{64}$/),
450
+ expiresAt: z.int(),
451
+ requestedBy: z.string().min(1).max(128),
452
+ createdAt: z.int()
453
+ });
454
+ const DeploymentAuthorizationIdSchema = z.string().regex(new RegExp(`^dauth_${UUID}$`));
455
+ const DeploymentApprovalIdSchema = z.string().regex(new RegExp(`^dapv_${UUID}$`));
456
+ const DeploymentActionSchema = z.enum([
457
+ "apply",
458
+ "start",
459
+ "stop",
460
+ "restart",
461
+ "recover"
462
+ ]);
463
+ const DeploymentPolicySchema = z.enum([
464
+ "standard",
465
+ "strict",
466
+ "readonly",
467
+ "autonomous"
468
+ ]);
469
+ const DeploymentActorSchema = z.strictObject({
470
+ type: z.enum(["human", "agent"]),
471
+ id: z.string().min(1).max(128)
472
+ });
473
+ const DeploymentAuthorizationContextSchema = z.strictObject({
474
+ domain: z.literal("service-ops"),
475
+ projectId: z.string().min(1).max(128),
476
+ targetId: DeploymentTargetIdSchema,
477
+ action: DeploymentActionSchema.default("apply"),
478
+ policy: DeploymentPolicySchema,
479
+ policySnapshotId: z.string().min(1).max(128),
480
+ actor: DeploymentActorSchema,
481
+ clientSessionId: z.string().min(1).max(128).nullable().default(null),
482
+ sessionId: z.string().min(1).max(128).nullable().default(null),
483
+ turnId: z.string().min(1).max(128).nullable().default(null)
484
+ });
485
+ const DeploymentAuthorizationScopeSchema = z.strictObject({
486
+ domain: z.literal("service-ops"),
487
+ projectId: z.string().min(1).max(128),
488
+ targetId: DeploymentTargetIdSchema,
489
+ planId: DeploymentPlanIdSchema,
490
+ action: DeploymentActionSchema,
491
+ planHash: z.string().regex(/^[a-f0-9]{64}$/),
492
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/)
493
+ });
494
+ const DeploymentAuthorizationStatusSchema = z.enum([
495
+ "PENDING",
496
+ "AUTHORIZED",
497
+ "DENIED",
498
+ "EXPIRED",
499
+ "REVOKED",
500
+ "CONSUMED",
501
+ "INVALIDATED"
502
+ ]);
503
+ const DeploymentApprovalStatusSchema = z.enum([
504
+ "PENDING",
505
+ "APPROVED",
506
+ "DENIED",
507
+ "EXPIRED",
508
+ "REVOKED"
509
+ ]);
510
+ z.object({
511
+ id: DeploymentAuthorizationIdSchema,
512
+ planId: DeploymentPlanIdSchema,
513
+ targetId: DeploymentTargetIdSchema,
514
+ projectId: z.string().min(1).max(128),
515
+ action: DeploymentActionSchema,
516
+ actorType: z.enum(["human", "agent"]),
517
+ actorId: z.string().min(1).max(128),
518
+ clientSessionId: z.string().min(1).max(128).nullable(),
519
+ sessionId: z.string().min(1).max(128).nullable(),
520
+ turnId: z.string().min(1).max(128).nullable(),
521
+ policy: DeploymentPolicySchema,
522
+ policySnapshotId: z.string().min(1).max(128),
523
+ status: DeploymentAuthorizationStatusSchema,
524
+ planHash: z.string().regex(/^[a-f0-9]{64}$/),
525
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
526
+ scope: DeploymentAuthorizationScopeSchema,
527
+ scopeHash: z.string().regex(/^[a-f0-9]{64}$/),
528
+ approvalId: DeploymentApprovalIdSchema.nullable(),
529
+ expiresAt: z.int(),
530
+ decidedAt: z.int().nullable(),
531
+ consumedAt: z.int().nullable(),
532
+ reasonCode: z.string().max(64).nullable(),
533
+ createdAt: z.int()
534
+ });
535
+ z.object({
536
+ id: DeploymentApprovalIdSchema,
537
+ authorizationId: DeploymentAuthorizationIdSchema,
538
+ planId: DeploymentPlanIdSchema,
539
+ targetId: DeploymentTargetIdSchema,
540
+ projectId: z.string().min(1).max(128),
541
+ status: DeploymentApprovalStatusSchema,
542
+ planHash: z.string().regex(/^[a-f0-9]{64}$/),
543
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
544
+ requestedBy: z.string().min(1).max(128),
545
+ decidedBy: z.string().min(1).max(128).nullable(),
546
+ expiresAt: z.int(),
547
+ decidedAt: z.int().nullable(),
548
+ createdAt: z.int()
549
+ });
550
+ const ServiceOpsDeploymentIdSchema = z.string().regex(new RegExp(`^dep_${UUID}$`));
551
+ const ServiceOpsDesiredStateSchema = z.enum(["running", "stopped"]);
552
+ const ServiceOpsObservedStateSchema = z.enum([
553
+ "stopped",
554
+ "starting",
555
+ "running",
556
+ "unhealthy",
557
+ "stopping",
558
+ "failed",
559
+ "unknown"
560
+ ]);
561
+ const ServiceOpsServiceDtoSchema = z.object({
562
+ targetId: DeploymentTargetIdSchema,
563
+ projectId: z.string().min(1).max(128),
564
+ name: DeploymentTargetNameSchema,
565
+ pm2Name: z.string().min(1).max(256),
566
+ projectName: z.string().nullable(),
567
+ source: z.enum(["pm2-cli", "deployment"]),
568
+ version: DeploymentVersionSchema.nullable(),
569
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/).nullable(),
570
+ desiredState: ServiceOpsDesiredStateSchema,
571
+ observedState: ServiceOpsObservedStateSchema,
572
+ pid: z.int().positive().nullable(),
573
+ lastHealthAt: z.int().nullable(),
574
+ reasonCode: z.string().max(64).nullable(),
575
+ updatedAt: z.int()
576
+ });
577
+ z.object({
578
+ pm2Home: z.string().min(1).max(4096).optional(),
579
+ items: z.array(ServiceOpsServiceDtoSchema),
580
+ unassociated: z.array(z.object({
581
+ pm2Name: z.string(),
582
+ reason: z.string()
583
+ }))
584
+ });
585
+ const ServiceOpsDeploymentStatusSchema = z.enum([
586
+ "APPLYING",
587
+ "HEALTH_CHECK",
588
+ "SUCCEEDED",
589
+ "FAILED",
590
+ "UNKNOWN"
591
+ ]);
592
+ z.object({
593
+ id: ServiceOpsDeploymentIdSchema,
594
+ targetId: DeploymentTargetIdSchema,
595
+ planId: DeploymentPlanIdSchema,
596
+ authorizationId: DeploymentAuthorizationIdSchema,
597
+ artifactId: DeploymentArtifactIdSchema,
598
+ previousArtifactId: DeploymentArtifactIdSchema.nullable(),
599
+ previousVersion: DeploymentVersionSchema.nullable(),
600
+ version: DeploymentVersionSchema,
601
+ status: ServiceOpsDeploymentStatusSchema,
602
+ planHash: z.string().regex(/^[a-f0-9]{64}$/),
603
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
604
+ reasonCode: z.string().max(64).nullable(),
605
+ startedAt: z.int(),
606
+ endedAt: z.int().nullable(),
607
+ createdAt: z.int()
608
+ });
609
+ const ServiceOpsSubscriptionSchema = z.object({
610
+ topic: z.literal("service-ops"),
611
+ resourceId: DeploymentTargetIdSchema,
612
+ after: z.int().min(0).max(Number.MAX_SAFE_INTEGER).default(0)
613
+ }).strict();
614
+ const ServiceOpsEventPayloadSchema = z.object({
615
+ observedState: ServiceOpsObservedStateSchema,
616
+ desiredState: ServiceOpsDesiredStateSchema,
617
+ version: DeploymentVersionSchema.nullable(),
618
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/).nullable(),
619
+ pid: z.int().positive().nullable(),
620
+ deploymentId: ServiceOpsDeploymentIdSchema.nullable(),
621
+ reasonCode: z.string().max(64).nullable()
622
+ });
623
+ const ServiceActionAuthorizationIdSchema = z.string().regex(new RegExp(`^sauth_${UUID}$`));
624
+ const ServiceActionSchema = z.enum([
625
+ "start",
626
+ "stop",
627
+ "restart",
628
+ "recover"
629
+ ]);
630
+ const ServiceActionStatusSchema = z.enum([
631
+ "PENDING",
632
+ "AUTHORIZED",
633
+ "DENIED",
634
+ "EXPIRED",
635
+ "REVOKED",
636
+ "CONSUMED"
637
+ ]);
638
+ const ServiceActionScopeSchema = z.strictObject({
639
+ domain: z.literal("service-ops"),
640
+ projectId: z.string().min(1).max(128),
641
+ targetId: DeploymentTargetIdSchema,
642
+ action: ServiceActionSchema,
643
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
644
+ version: DeploymentVersionSchema
645
+ });
646
+ const ServiceActionAuthorizationDtoSchema = z.object({
647
+ id: ServiceActionAuthorizationIdSchema,
648
+ targetId: DeploymentTargetIdSchema,
649
+ projectId: z.string().min(1).max(128),
650
+ action: ServiceActionSchema,
651
+ actorType: z.enum(["human", "agent"]),
652
+ actorId: z.string().min(1).max(128),
653
+ clientSessionId: z.string().min(1).max(128).nullable(),
654
+ sessionId: z.string().min(1).max(128).nullable(),
655
+ turnId: z.string().min(1).max(128).nullable(),
656
+ policy: DeploymentPolicySchema,
657
+ policySnapshotId: z.string().min(1).max(128),
658
+ status: ServiceActionStatusSchema,
659
+ artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
660
+ version: DeploymentVersionSchema,
661
+ scopeHash: z.string().regex(/^[a-f0-9]{64}$/),
662
+ expiresAt: z.int(),
663
+ decidedAt: z.int().nullable(),
664
+ decidedBy: z.string().min(1).max(128).nullable(),
665
+ consumedAt: z.int().nullable(),
666
+ reasonCode: z.string().max(64).nullable(),
667
+ createdAt: z.int()
668
+ });
669
+ const DEPLOYMENT_APPROVAL_TTL_MS = 5 * 6e4;
670
+ const DeploymentArtifactManifestSchema = z.strictObject({
671
+ version: z.literal(1),
672
+ artifactId: DeploymentArtifactIdSchema,
673
+ targetId: DeploymentTargetIdSchema,
674
+ hash: z.string().regex(/^[a-f0-9]{64}$/),
675
+ files: z.array(z.strictObject({
676
+ path: z.string().min(1).max(1024),
677
+ size: z.int().nonnegative(),
678
+ hash: z.string().regex(/^[a-f0-9]{64}$/)
679
+ }))
680
+ });
681
+ const DEPLOYMENT_PLAN_TTL_MS = 30 * 6e4;
682
+ const DEPLOYMENT_ARTIFACT_MAX_BYTES = 512 * 1024 * 1024;
683
+ const DEPLOYMENT_ARTIFACT_MAX_FILES = 2e4;
684
+ const DEPLOYMENT_ARTIFACT_MAX_PATH = 1024;
685
+ const DEPLOYMENT_BUILD_LOG_MAX_BYTES = 1024 * 1024;
686
+ z.object({
687
+ available: z.boolean(),
688
+ nodeExecutable: z.string(),
689
+ entry: z.string().nullable(),
690
+ version: z.string().nullable(),
691
+ home: z.string(),
692
+ namespace: z.literal("larness"),
693
+ serviceNamePattern: z.literal("larness:<projectId>:<serviceKey>"),
694
+ project: z.object({
695
+ id: z.string(),
696
+ name: z.string(),
697
+ root: z.string(),
698
+ releaseRoot: z.string()
699
+ }).nullable(),
700
+ unassociatedServices: z.array(z.object({
701
+ pm2Name: z.string(),
702
+ reason: z.string()
703
+ })).optional(),
704
+ services: z.array(z.object({
705
+ projectId: z.string(),
706
+ projectName: z.string(),
707
+ name: z.string(),
708
+ pm2Name: z.string(),
709
+ observedState: ServiceOpsObservedStateSchema,
710
+ pid: z.int().nullable(),
711
+ updatedAt: z.int()
712
+ }))
713
+ });
714
+ //#endregion
715
+ //#region ../../packages/shared/src/domain.ts
716
+ const DEFAULT_PROJECT_ID = "prj_default";
717
+ z.boolean().default(false);
718
+ //#endregion
719
+ //#region ../../packages/shared/src/errors.ts
720
+ const ERROR_CODES = {
721
+ validation: "VALIDATION_ERROR",
722
+ unauthenticated: "UNAUTHENTICATED",
723
+ forbidden: "FORBIDDEN",
724
+ originInvalid: "ORIGIN_INVALID",
725
+ httpsRequired: "HTTPS_REQUIRED",
726
+ csrfInvalid: "CSRF_INVALID",
727
+ notFound: "NOT_FOUND",
728
+ notInitialized: "NOT_INITIALIZED",
729
+ conflict: "CONFLICT",
730
+ turnInProgress: "TURN_IN_PROGRESS",
731
+ resourceLocked: "RESOURCE_LOCKED",
732
+ versionConflict: "VERSION_CONFLICT",
733
+ fileNotEditable: "FILE_NOT_EDITABLE",
734
+ payloadTooLarge: "PAYLOAD_TOO_LARGE",
735
+ resourceUnavailable: "RESOURCE_UNAVAILABLE",
736
+ terminalLeaseRequired: "TERMINAL_LEASE_REQUIRED",
737
+ gitUnavailable: "GIT_UNAVAILABLE",
738
+ gitConflict: "GIT_CONFLICT",
739
+ gitAuthRequired: "GIT_AUTH_REQUIRED",
740
+ pairingDenied: "PAIRING_DENIED",
741
+ pairingExpired: "PAIRING_EXPIRED",
742
+ codeInvalid: "CODE_INVALID",
743
+ enrollmentExpired: "ENROLLMENT_EXPIRED",
744
+ challengeExpired: "CHALLENGE_EXPIRED",
745
+ passkeyRegistrationFailed: "PASSKEY_REGISTRATION_FAILED",
746
+ passkeyAuthFailed: "PASSKEY_AUTH_FAILED",
747
+ webauthnNotConfigured: "WEBAUTHN_NOT_CONFIGURED",
748
+ rateLimited: "RATE_LIMITED",
749
+ pathOutsideProject: "PATH_OUTSIDE_PROJECT",
750
+ approvalInvalid: "APPROVAL_INVALID",
751
+ previewTargetInvalid: "PREVIEW_TARGET_INVALID",
752
+ previewUnavailable: "PREVIEW_UNAVAILABLE",
753
+ previewDisabled: "PREVIEW_DISABLED",
754
+ previewGrantInvalid: "PREVIEW_GRANT_INVALID",
755
+ deployTargetInvalid: "DEPLOY_TARGET_INVALID",
756
+ deploySpecInvalid: "DEPLOY_SPEC_INVALID",
757
+ deployBuildFailed: "DEPLOY_BUILD_FAILED",
758
+ deployArtifactInvalid: "DEPLOY_ARTIFACT_INVALID",
759
+ deployPlanInvalid: "DEPLOY_PLAN_INVALID",
760
+ deployPlanExpired: "DEPLOY_PLAN_EXPIRED",
761
+ deployAuthRequired: "DEPLOY_AUTH_REQUIRED",
762
+ deployAuthInvalid: "DEPLOY_AUTH_INVALID",
763
+ deployApprovalInvalid: "DEPLOY_APPROVAL_INVALID",
764
+ deployApprovalExpired: "DEPLOY_APPROVAL_EXPIRED",
765
+ deployConflict: "DEPLOY_CONFLICT",
766
+ deployUnavailable: "DEPLOY_UNAVAILABLE",
767
+ providerUnavailable: "PROVIDER_UNAVAILABLE",
768
+ providerAuthFailed: "PROVIDER_AUTH_FAILED",
769
+ providerRateLimited: "PROVIDER_RATE_LIMITED",
770
+ providerQuotaExhausted: "PROVIDER_QUOTA_EXHAUSTED",
771
+ providerContextLimit: "PROVIDER_CONTEXT_LIMIT",
772
+ providerContentFiltered: "PROVIDER_CONTENT_FILTERED",
773
+ providerUnknown: "PROVIDER_UNKNOWN",
774
+ modelCredentialMissing: "MODEL_CREDENTIAL_MISSING",
775
+ modelCatalogInvalid: "MODEL_CATALOG_INVALID",
776
+ modelUnsupported: "MODEL_UNSUPPORTED",
777
+ devWebUnavailable: "DEV_WEB_UNAVAILABLE",
778
+ internal: "INTERNAL"
779
+ };
780
+ const ERROR_HTTP_STATUS = {
781
+ VALIDATION_ERROR: 400,
782
+ UNAUTHENTICATED: 401,
783
+ FORBIDDEN: 403,
784
+ ORIGIN_INVALID: 403,
785
+ HTTPS_REQUIRED: 403,
786
+ CSRF_INVALID: 403,
787
+ NOT_FOUND: 404,
788
+ NOT_INITIALIZED: 409,
789
+ CONFLICT: 409,
790
+ TURN_IN_PROGRESS: 409,
791
+ RESOURCE_LOCKED: 409,
792
+ VERSION_CONFLICT: 409,
793
+ FILE_NOT_EDITABLE: 422,
794
+ PAYLOAD_TOO_LARGE: 413,
795
+ RESOURCE_UNAVAILABLE: 409,
796
+ TERMINAL_LEASE_REQUIRED: 409,
797
+ GIT_UNAVAILABLE: 503,
798
+ GIT_CONFLICT: 409,
799
+ GIT_AUTH_REQUIRED: 409,
800
+ PAIRING_DENIED: 403,
801
+ PAIRING_EXPIRED: 410,
802
+ CODE_INVALID: 400,
803
+ ENROLLMENT_EXPIRED: 410,
804
+ CHALLENGE_EXPIRED: 410,
805
+ PASSKEY_REGISTRATION_FAILED: 400,
806
+ PASSKEY_AUTH_FAILED: 401,
807
+ WEBAUTHN_NOT_CONFIGURED: 409,
808
+ RATE_LIMITED: 429,
809
+ PATH_OUTSIDE_PROJECT: 403,
810
+ APPROVAL_INVALID: 409,
811
+ PREVIEW_TARGET_INVALID: 403,
812
+ PREVIEW_UNAVAILABLE: 503,
813
+ PREVIEW_DISABLED: 503,
814
+ PREVIEW_GRANT_INVALID: 401,
815
+ DEPLOY_TARGET_INVALID: 400,
816
+ DEPLOY_SPEC_INVALID: 400,
817
+ DEPLOY_BUILD_FAILED: 422,
818
+ DEPLOY_ARTIFACT_INVALID: 409,
819
+ DEPLOY_PLAN_INVALID: 409,
820
+ DEPLOY_PLAN_EXPIRED: 410,
821
+ DEPLOY_AUTH_REQUIRED: 409,
822
+ DEPLOY_AUTH_INVALID: 409,
823
+ DEPLOY_APPROVAL_INVALID: 409,
824
+ DEPLOY_APPROVAL_EXPIRED: 410,
825
+ DEPLOY_CONFLICT: 409,
826
+ DEPLOY_UNAVAILABLE: 503,
827
+ PROVIDER_UNAVAILABLE: 503,
828
+ PROVIDER_AUTH_FAILED: 502,
829
+ PROVIDER_RATE_LIMITED: 429,
830
+ PROVIDER_QUOTA_EXHAUSTED: 402,
831
+ PROVIDER_CONTEXT_LIMIT: 413,
832
+ PROVIDER_CONTENT_FILTERED: 422,
833
+ PROVIDER_UNKNOWN: 502,
834
+ MODEL_CREDENTIAL_MISSING: 409,
835
+ MODEL_CATALOG_INVALID: 502,
836
+ MODEL_UNSUPPORTED: 400,
837
+ DEV_WEB_UNAVAILABLE: 503,
838
+ INTERNAL: 500
839
+ };
840
+ //#endregion
841
+ //#region ../../packages/shared/src/events.ts
842
+ const WORKSPACE_SESSIONS_CHANGED = "workspace.sessions.changed";
843
+ const WORKSPACE_JOBS_CHANGED = "workspace.jobs.changed";
844
+ z.discriminatedUnion("kind", [z.object({
845
+ kind: z.literal("subscribed"),
846
+ subscription: z.object({
847
+ topic: z.literal("system"),
848
+ resourceId: z.literal("system")
849
+ })
850
+ }), z.object({ kind: z.literal(WORKSPACE_SESSIONS_CHANGED) })]);
851
+ z.object({ kind: z.literal(WORKSPACE_JOBS_CHANGED) });
852
+ //#endregion
853
+ //#region ../../packages/shared/src/git.ts
854
+ const GitPathSchema = z.string().min(1).max(4096).refine((value) => !value.includes("\0"), "Git path cannot contain NUL");
855
+ const GitBranchNameSchema = z.string().min(1).max(255).refine((value) => !value.includes("\0") && !value.startsWith("-"), "Invalid branch name");
856
+ const GitAddActionSchema = z.object({
857
+ action: z.literal("add"),
858
+ paths: z.array(GitPathSchema).min(1).max(200)
859
+ }).strict();
860
+ const GitUnstageActionSchema = z.object({
861
+ action: z.literal("unstage"),
862
+ paths: z.array(GitPathSchema).min(1).max(200)
863
+ }).strict();
864
+ const GitDiscardActionSchema = z.object({
865
+ action: z.literal("discard"),
866
+ path: GitPathSchema,
867
+ confirmed: z.literal(true)
868
+ }).strict();
869
+ const GitCommitActionSchema = z.object({
870
+ action: z.literal("commit"),
871
+ message: z.string().min(1).max(4e3)
872
+ }).strict();
873
+ const GitCreateBranchActionSchema = z.object({
874
+ action: z.literal("createBranch"),
875
+ name: GitBranchNameSchema
876
+ }).strict();
877
+ const GitSwitchBranchActionSchema = z.object({
878
+ action: z.literal("switchBranch"),
879
+ name: GitBranchNameSchema
880
+ }).strict();
881
+ const GitPullActionSchema = z.object({ action: z.literal("pull") }).strict();
882
+ const GitPushActionSchema = z.object({ action: z.literal("push") }).strict();
883
+ const GitActionSchema = z.union([
884
+ GitAddActionSchema,
885
+ GitUnstageActionSchema,
886
+ GitDiscardActionSchema,
887
+ GitCommitActionSchema,
888
+ GitCreateBranchActionSchema,
889
+ GitSwitchBranchActionSchema,
890
+ GitPullActionSchema,
891
+ GitPushActionSchema
892
+ ]);
893
+ const GitActionDecisionSchema = z.object({ decision: z.enum(["approve", "reject"]) }).strict();
894
+ const GitDiffQuerySchema = z.object({
895
+ path: z.string().min(1).max(4096),
896
+ staged: z.enum(["true", "false"]).default("false")
897
+ }).strict();
898
+ const GitLogQuerySchema = z.object({
899
+ limit: z.coerce.number().int().min(1).max(100).default(50),
900
+ cursor: z.coerce.number().int().nonnegative().default(0)
901
+ }).strict();
902
+ const GitBranchesQuerySchema = z.object({
903
+ limit: z.coerce.number().int().min(1).max(200).default(100),
904
+ cursor: z.coerce.number().int().nonnegative().default(0)
905
+ }).strict();
906
+ z.enum(["script", "agent"]);
907
+ const ScheduledJobMissedPolicySchema = z.enum(["skip", "run_once"]);
908
+ const ScheduledJobApprovalPolicySchema = z.enum(["readonly", "autonomous"]);
909
+ z.enum([
910
+ "scheduled",
911
+ "manual",
912
+ "catch_up"
913
+ ]);
914
+ z.enum([
915
+ "queued",
916
+ "running",
917
+ "succeeded",
918
+ "failed",
919
+ "timed_out",
920
+ "cancelled",
921
+ "interrupted",
922
+ "skipped"
923
+ ]);
924
+ z.enum([
925
+ "JOB_SCRIPT_FAILED",
926
+ "JOB_TIMEOUT",
927
+ "JOB_RUN_CANCELLED",
928
+ "JOB_AGENT_FAILED",
929
+ "JOB_INTERRUPTED",
930
+ "JOB_OVERLAP"
931
+ ]);
932
+ const CronExpressionSchema = z.string().min(9).max(128).refine((value) => value.trim().split(/\s+/).length === 5, "Cron 必须是 5 字段");
933
+ const TimezoneSchema = z.string().min(1).max(64);
934
+ const ScheduledJobScheduleSchema = z.discriminatedUnion("type", [z.object({
935
+ type: z.literal("cron"),
936
+ expression: CronExpressionSchema,
937
+ timezone: TimezoneSchema
938
+ }).strict(), z.object({
939
+ type: z.literal("interval"),
940
+ seconds: z.number().int().min(60).max(604800),
941
+ timezone: TimezoneSchema
942
+ }).strict()]);
943
+ const BaseJobInput = {
944
+ name: z.string().trim().min(1).max(80),
945
+ projectId: z.string().min(1).max(128).nullable(),
946
+ schedule: ScheduledJobScheduleSchema,
947
+ enabled: z.boolean().default(true),
948
+ timeoutSeconds: z.number().int().min(60).max(3600).default(600),
949
+ missedPolicy: ScheduledJobMissedPolicySchema.default("skip")
950
+ };
951
+ const ScriptJobInputSchema = z.object({
952
+ ...BaseJobInput,
953
+ kind: z.literal("script"),
954
+ script: z.object({ source: z.string().min(1).max(65536) }).strict()
955
+ }).strict();
956
+ const AgentJobInputSchema = z.object({
957
+ ...BaseJobInput,
958
+ kind: z.literal("agent"),
959
+ agent: z.object({
960
+ prompt: z.string().trim().min(1).max(10240),
961
+ model: z.string().min(1).max(128).nullable().optional(),
962
+ credentialProfileId: z.string().min(1).max(128).nullable().optional(),
963
+ thinking: z.string().min(1).max(32).nullable().optional(),
964
+ approvalPolicy: ScheduledJobApprovalPolicySchema.default("readonly")
965
+ }).strict()
966
+ }).strict();
967
+ const ScheduledJobInputSchema = z.discriminatedUnion("kind", [ScriptJobInputSchema, AgentJobInputSchema]);
968
+ /** PATCH body: all mutable fields optional; kind/projectId retained from the existing job. */
969
+ const ScheduledJobPatchSchema = z.object({
970
+ name: z.string().trim().min(1).max(80).optional(),
971
+ enabled: z.boolean().optional(),
972
+ schedule: ScheduledJobScheduleSchema.optional(),
973
+ timeoutSeconds: z.number().int().min(60).max(3600).optional(),
974
+ missedPolicy: ScheduledJobMissedPolicySchema.optional(),
975
+ script: z.object({ source: z.string().min(1).max(65536) }).strict().optional(),
976
+ agent: z.object({
977
+ prompt: z.string().trim().min(1).max(10240).optional(),
978
+ model: z.string().min(1).max(128).nullable().optional(),
979
+ credentialProfileId: z.string().min(1).max(128).nullable().optional(),
980
+ thinking: z.string().min(1).max(32).nullable().optional(),
981
+ approvalPolicy: ScheduledJobApprovalPolicySchema.optional()
982
+ }).strict().optional()
983
+ }).strict();
984
+ //#endregion
985
+ //#region ../../packages/shared/src/plans.ts
986
+ const PlanStepSchema = z.object({
987
+ id: z.string().min(1).max(80),
988
+ title: z.string().trim().min(1).max(200),
989
+ detail: z.string().max(500).optional(),
990
+ status: z.enum([
991
+ "pending",
992
+ "running",
993
+ "done",
994
+ "failed"
995
+ ])
996
+ }).strict();
997
+ const PlanParamsSchema = z.object({
998
+ title: z.string().trim().min(1).max(200),
999
+ steps: z.array(PlanStepSchema).min(1).max(12)
1000
+ }).strict().superRefine((plan, context) => {
1001
+ if (new Set(plan.steps.map((step) => step.id)).size !== plan.steps.length) context.addIssue({
1002
+ code: "custom",
1003
+ message: "Step IDs must be unique"
1004
+ });
1005
+ if (plan.steps.filter((step) => step.status === "running").length > 1) context.addIssue({
1006
+ code: "custom",
1007
+ message: "Only one step can be running"
1008
+ });
1009
+ });
1010
+ PlanParamsSchema.safeExtend({
1011
+ id: z.string().min(1),
1012
+ kind: z.literal("plan"),
1013
+ createdAt: z.number().int().nonnegative(),
1014
+ turnId: z.string().optional()
1015
+ });
1016
+ //#endregion
1017
+ //#region ../../packages/shared/src/terminals.ts
1018
+ const TerminalIdSchema = z.string().regex(/^term_[a-f0-9-]{36}$/);
1019
+ const TerminalRenameSchema = z.object({ title: z.string().min(1).max(80).refine((value) => [...value].every((char) => {
1020
+ const code = char.codePointAt(0) ?? 0;
1021
+ return code >= 32 && (code < 127 || code > 159);
1022
+ })).transform((value) => value.trim()).pipe(z.string().min(1)) }).strict();
1023
+ const TerminalRoleSchema = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
1024
+ const TerminalStatusSchema = z.enum([
1025
+ "CREATED",
1026
+ "RUNNING",
1027
+ "STOPPING",
1028
+ "EXITED",
1029
+ "TERMINATED",
1030
+ "INTERRUPTED"
1031
+ ]);
1032
+ const TerminalCreateSchema = z.object({
1033
+ scope: FileScopeSchema.optional(),
1034
+ cwd: FilePathSchema.default("."),
1035
+ sourceSessionId: z.string().min(1).max(128).optional(),
1036
+ riskAcknowledged: z.literal(true)
1037
+ }).strict();
1038
+ const TerminalDevSchema = z.object({
1039
+ role: TerminalRoleSchema,
1040
+ executable: z.string(),
1041
+ args: z.array(z.string()),
1042
+ cwd: FilePathSchema.default(".").describe("Project-relative working directory. Defaults to the project root (.). Use the package directory for a direct package command.")
1043
+ }).strict().superRefine((value, ctx) => {
1044
+ if (!CommandParamsSchema.safeParse(value && {
1045
+ executable: value.executable,
1046
+ args: value.args,
1047
+ cwd: value.cwd
1048
+ }).success) ctx.addIssue({
1049
+ code: "custom",
1050
+ message: "Invalid program parameters"
1051
+ });
1052
+ });
1053
+ const ReadTerminalOutputParamsSchema = z.object({
1054
+ terminalId: TerminalIdSchema,
1055
+ after: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
1056
+ limit: z.number().int().min(1).max(500).default(100)
1057
+ }).strict();
1058
+ const StopProjectTerminalParamsSchema = z.object({ terminalId: TerminalIdSchema }).strict();
1059
+ const TerminalResultTargetSchema = z.object({
1060
+ kind: z.literal("terminal"),
1061
+ projectId: z.string().min(1),
1062
+ terminalId: TerminalIdSchema,
1063
+ role: TerminalRoleSchema.nullable()
1064
+ }).strict();
1065
+ const PreviewResultTargetSchema = z.object({
1066
+ kind: z.literal("preview"),
1067
+ projectId: z.string().min(1).max(128),
1068
+ serviceId: z.string().regex(/^svc_[a-f0-9-]{36}$/),
1069
+ path: z.string().min(1).max(2048),
1070
+ name: z.string().min(1).max(128).optional()
1071
+ }).strict();
1072
+ z.union([
1073
+ FileResultTargetSchema,
1074
+ TerminalResultTargetSchema,
1075
+ PreviewResultTargetSchema
1076
+ ]);
1077
+ const TerminalTakeoverSchema = z.object({ connectionId: z.string().uuid() }).strict();
1078
+ const AcquireTerminalControlParamsSchema = z.object({ terminalId: TerminalIdSchema }).strict();
1079
+ const SendTerminalInputParamsSchema = z.object({
1080
+ terminalId: TerminalIdSchema,
1081
+ leaseGeneration: z.number().int().positive(),
1082
+ inputSequence: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
1083
+ data: z.string().min(1).max(8192).refine((data) => new TextEncoder().encode(data).length <= 8192)
1084
+ }).strict();
1085
+ const InterruptTerminalParamsSchema = z.object({
1086
+ terminalId: TerminalIdSchema,
1087
+ leaseGeneration: z.number().int().positive()
1088
+ }).strict();
1089
+ const ReleaseTerminalControlParamsSchema = z.object({
1090
+ terminalId: TerminalIdSchema,
1091
+ leaseGeneration: z.number().int().positive()
1092
+ }).strict();
1093
+ const TerminalLeaseSchema = z.object({
1094
+ action: z.enum([
1095
+ "acquire",
1096
+ "renew",
1097
+ "release"
1098
+ ]),
1099
+ connectionId: z.string().uuid(),
1100
+ leaseGeneration: z.number().int().positive().optional()
1101
+ }).strict();
1102
+ const TerminalResizeSchema = z.object({
1103
+ connectionId: z.string().uuid(),
1104
+ leaseGeneration: z.number().int().positive(),
1105
+ cols: z.number().int().min(2).max(500),
1106
+ rows: z.number().int().min(1).max(300)
1107
+ }).strict();
1108
+ const TerminalInputSchema = z.object({
1109
+ type: z.literal("terminal.input"),
1110
+ terminalId: TerminalIdSchema,
1111
+ leaseGeneration: z.number().int().positive(),
1112
+ inputSequence: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
1113
+ data: z.string().max(8192).refine((data) => new TextEncoder().encode(data).length <= 8192)
1114
+ }).strict();
1115
+ const TerminalSubscriptionSchema = z.object({
1116
+ topic: z.literal("terminal"),
1117
+ resourceId: TerminalIdSchema,
1118
+ after: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0)
1119
+ }).strict();
1120
+ const TerminalOutputChunkSchema = z.object({
1121
+ cursor: z.number().int().positive(),
1122
+ data: z.string().max(16384).refine((data) => new TextEncoder().encode(data).length <= 16384),
1123
+ timestamp: z.number().int()
1124
+ }).strict();
1125
+ TerminalOutputChunkSchema.extend({
1126
+ kind: z.literal("terminal.output"),
1127
+ resourceId: TerminalIdSchema
1128
+ }).strict();
1129
+ const TerminalLeaseViewSchema = z.object({
1130
+ ownerType: z.enum(["human", "agent"]),
1131
+ ownerClientSessionId: z.string(),
1132
+ ownerConnectionId: z.string().nullable(),
1133
+ ownerTurnId: z.string().nullable(),
1134
+ ownerExecutionId: z.string().nullable(),
1135
+ generation: z.number().int().positive(),
1136
+ expiresAt: z.number().int()
1137
+ });
1138
+ const TerminalPayloadSchema = z.object({
1139
+ status: TerminalStatusSchema,
1140
+ exitCode: z.number().int().nullable(),
1141
+ reasonCode: z.string().nullable(),
1142
+ lease: TerminalLeaseViewSchema.nullable()
1143
+ });
1144
+ const TerminalEventSchema = z.object({
1145
+ kind: z.literal("event"),
1146
+ protocolVersion: z.literal(1),
1147
+ topic: z.literal("terminal"),
1148
+ eventId: z.string(),
1149
+ streamId: TerminalIdSchema,
1150
+ resourceId: TerminalIdSchema,
1151
+ sequence: z.number().int().positive(),
1152
+ timestamp: z.number(),
1153
+ type: z.enum([
1154
+ "terminal.created",
1155
+ "terminal.status",
1156
+ "terminal.exit",
1157
+ "terminal.lease"
1158
+ ]),
1159
+ payload: TerminalPayloadSchema
1160
+ });
1161
+ const TERMINAL_LEASE_TTL_MS = 3e4;
1162
+ const TerminalSchema = z.object({
1163
+ writeBlocked: z.boolean(),
1164
+ id: TerminalIdSchema,
1165
+ projectId: z.string().nullable(),
1166
+ workspaceSessionId: z.string().nullable(),
1167
+ sourceSessionId: z.string().nullable(),
1168
+ cwd: z.string(),
1169
+ shell: z.string(),
1170
+ mode: z.enum(["shell", "dev"]),
1171
+ role: z.string().nullable(),
1172
+ title: z.string().nullable().default(null),
1173
+ status: TerminalStatusSchema,
1174
+ exitCode: z.number().nullable(),
1175
+ reasonCode: z.string().nullable(),
1176
+ currentSequence: z.number().int(),
1177
+ lease: TerminalLeaseViewSchema.nullable()
1178
+ });
1179
+ z.object({
1180
+ chunks: z.array(TerminalOutputChunkSchema).max(500),
1181
+ nextCursor: z.number().int(),
1182
+ oldestCursor: z.number().int(),
1183
+ truncated: z.boolean(),
1184
+ resyncRequired: z.boolean()
1185
+ });
1186
+ z.object({
1187
+ kind: z.literal("subscribed"),
1188
+ connectionId: z.string().uuid(),
1189
+ subscription: z.object({
1190
+ topic: z.literal("terminal"),
1191
+ resourceId: z.string()
1192
+ })
1193
+ });
1194
+ z.object({
1195
+ kind: z.literal("terminal.input.ack"),
1196
+ inputSequence: z.number().int(),
1197
+ accepted: z.boolean()
1198
+ });
1199
+ z.object({
1200
+ kind: z.literal("error"),
1201
+ code: z.string()
1202
+ });
1203
+ z.object({
1204
+ items: z.array(TerminalSchema),
1205
+ nextCursor: TerminalIdSchema.nullable()
1206
+ });
1207
+ //#endregion
1208
+ //#region ../../packages/shared/src/services.ts
1209
+ const ServiceIdSchema = z.string().regex(/^svc_[a-f0-9-]{36}$/);
1210
+ const ServiceStatusSchema = z.enum([
1211
+ "REGISTERING",
1212
+ "STARTING",
1213
+ "RUNNING",
1214
+ "UNKNOWN",
1215
+ "UNREGISTERED"
1216
+ ]);
1217
+ const ServiceKindSchema = z.literal("temporary");
1218
+ const ServiceEndpointSchema = z.object({
1219
+ host: z.enum(["127.0.0.1", "::1"]),
1220
+ port: z.number().int().min(1).max(65535),
1221
+ protocol: z.literal("http")
1222
+ }).strict();
1223
+ const ServiceRegisterInputSchema = z.object({
1224
+ kind: ServiceKindSchema.describe("temporary development preview only; registration does not create a persistent PM2 service"),
1225
+ terminalId: TerminalIdSchema.describe("Managed terminal owning the real listening process; not a PM2 targetId or pm2Name"),
1226
+ name: z.string().trim().min(1).max(80),
1227
+ endpoint: ServiceEndpointSchema.describe("Use the terminal listener's port and a loopback host value. The backend discovers the actual bind address, including wildcard listeners.")
1228
+ }).strict();
1229
+ const ServiceDtoSchema = z.object({
1230
+ id: ServiceIdSchema,
1231
+ projectId: z.string().min(1).max(128),
1232
+ sourceSessionId: z.string().min(1).max(128).nullable(),
1233
+ name: z.string().min(1).max(80),
1234
+ kind: ServiceKindSchema,
1235
+ status: ServiceStatusSchema,
1236
+ terminalId: TerminalIdSchema,
1237
+ terminalExecutionId: z.string().min(1).max(128),
1238
+ endpointGeneration: z.number().int().nonnegative(),
1239
+ endpoint: ServiceEndpointSchema,
1240
+ previewEligible: z.boolean(),
1241
+ reasonCode: z.string().nullable(),
1242
+ createdAt: z.number().int(),
1243
+ updatedAt: z.number().int(),
1244
+ endedAt: z.number().int().nullable()
1245
+ });
1246
+ z.object({
1247
+ items: z.array(ServiceDtoSchema),
1248
+ nextCursor: z.string().nullable()
1249
+ });
1250
+ z.object({
1251
+ id: z.string().min(1).max(128),
1252
+ projectId: z.string().min(1).max(128),
1253
+ kind: z.literal("service.register"),
1254
+ risk: z.literal("L2"),
1255
+ status: z.enum([
1256
+ "PREPARED",
1257
+ "WAITING_APPROVAL",
1258
+ "APPROVED",
1259
+ "RUNNING",
1260
+ "COMPLETED",
1261
+ "FAILED",
1262
+ "REJECTED",
1263
+ "EXPIRED",
1264
+ "INTERRUPTED"
1265
+ ]),
1266
+ params: ServiceRegisterInputSchema,
1267
+ paramsHash: z.string(),
1268
+ snapshotVersion: z.string(),
1269
+ requestedBy: z.string(),
1270
+ decidedBy: z.string().nullable(),
1271
+ expiresAt: z.number().int(),
1272
+ decidedAt: z.number().int().nullable(),
1273
+ startedAt: z.number().int().nullable(),
1274
+ endedAt: z.number().int().nullable(),
1275
+ result: z.unknown(),
1276
+ createdAt: z.number().int()
1277
+ });
1278
+ const ServiceEventPayloadSchema = z.object({
1279
+ status: ServiceStatusSchema,
1280
+ terminalId: TerminalIdSchema,
1281
+ terminalExecutionId: z.string().min(1).max(128),
1282
+ endpointGeneration: z.number().int().nonnegative(),
1283
+ reasonCode: z.string().nullable()
1284
+ });
1285
+ const ServiceSubscriptionSchema = z.object({
1286
+ topic: z.literal("service"),
1287
+ resourceId: ServiceIdSchema,
1288
+ after: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0)
1289
+ }).strict();
1290
+ //#endregion
1291
+ //#region ../../packages/shared/src/resources.ts
1292
+ const RESOURCE_EVENT_RETENTION_MS = 720 * 60 * 6e4;
1293
+ const FileResourceIdSchema = z.string().regex(/^(?:(?:project|session):[a-zA-Z0-9_-]{1,128}|workspace:default)$/);
1294
+ const FileStreamIdSchema = z.string().regex(/^file:(?:(?:project|session):[a-zA-Z0-9_-]{1,128}|workspace:default)$/);
1295
+ const FileSubscriptionSchema = z.object({
1296
+ topic: z.literal("file"),
1297
+ resourceId: FileResourceIdSchema,
1298
+ paths: z.array(FilePathSchema).min(1).max(128).default(["."]),
1299
+ after: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0)
1300
+ }).strict();
1301
+ const ServiceOpsStreamIdSchema = z.string().regex(/^ops:tgt_[0-9a-f-]{36}$/);
1302
+ const ResourceEventsQuerySchema = z.object({
1303
+ streamId: z.union([
1304
+ FileStreamIdSchema,
1305
+ CommandIdSchema,
1306
+ TerminalIdSchema,
1307
+ ServiceIdSchema,
1308
+ ServiceOpsStreamIdSchema
1309
+ ]),
1310
+ after: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
1311
+ limit: z.coerce.number().int().min(1).max(500).default(100)
1312
+ }).strict();
1313
+ const FileChangedPayloadSchema = z.object({
1314
+ path: FilePathSchema,
1315
+ version: FileVersionSchema.optional(),
1316
+ changeType: z.enum([
1317
+ "created",
1318
+ "modified",
1319
+ "deleted"
1320
+ ])
1321
+ });
1322
+ const FileResyncPayloadSchema = z.object({ reasonCode: z.enum([
1323
+ "WATCH_UNAVAILABLE",
1324
+ "WATCH_LIMIT",
1325
+ "SCAN_LIMIT",
1326
+ "QUEUE_OVERFLOW",
1327
+ "ROOT_UNAVAILABLE",
1328
+ "DIRECTORY_REPLACED",
1329
+ "RECOVERED",
1330
+ "SCAN_FAILED"
1331
+ ]) });
1332
+ const FileEventBase = z.object({
1333
+ kind: z.literal("event"),
1334
+ protocolVersion: z.literal(1),
1335
+ topic: z.literal("file"),
1336
+ eventId: z.string(),
1337
+ streamId: FileStreamIdSchema,
1338
+ sequence: z.number().int().nonnegative(),
1339
+ timestamp: z.number()
1340
+ });
1341
+ const FileNotificationSchema = z.union([FileEventBase.extend({
1342
+ type: z.literal("file.changed"),
1343
+ payload: FileChangedPayloadSchema
1344
+ }), FileEventBase.extend({
1345
+ type: z.literal("file.resync.required"),
1346
+ payload: FileResyncPayloadSchema
1347
+ })]);
1348
+ const ServiceEventBase = z.object({
1349
+ kind: z.literal("event"),
1350
+ protocolVersion: z.literal(1),
1351
+ topic: z.literal("service"),
1352
+ eventId: z.string(),
1353
+ streamId: ServiceIdSchema,
1354
+ sequence: z.number().int().nonnegative(),
1355
+ timestamp: z.number(),
1356
+ projectId: z.string().optional()
1357
+ });
1358
+ const ServiceNotificationSchema = z.union([ServiceEventBase.extend({
1359
+ type: z.enum([
1360
+ "service.registered",
1361
+ "service.status",
1362
+ "service.unregistered"
1363
+ ]),
1364
+ payload: ServiceEventPayloadSchema
1365
+ })]);
1366
+ z.object({
1367
+ items: z.array(z.union([
1368
+ FileNotificationSchema,
1369
+ CommandStatusEventSchema,
1370
+ TerminalEventSchema,
1371
+ ServiceNotificationSchema
1372
+ ])),
1373
+ currentSequence: z.number().int().nonnegative(),
1374
+ resyncRequired: z.boolean()
1375
+ });
1376
+ z.object({
1377
+ kind: z.literal("subscribed"),
1378
+ subscription: z.object({
1379
+ topic: z.literal("file"),
1380
+ resourceId: FileResourceIdSchema
1381
+ }),
1382
+ currentSequence: z.number().int().nonnegative(),
1383
+ resyncRequired: z.boolean(),
1384
+ partial: z.boolean()
1385
+ });
1386
+ z.object({
1387
+ kind: z.literal("error"),
1388
+ code: z.string(),
1389
+ message: z.string()
1390
+ });
1391
+ //#endregion
1392
+ //#region src/db/ids.ts
1393
+ function newId(prefix) {
1394
+ return `${prefix}_${randomUUID()}`;
1395
+ }
1396
+ //#endregion
1397
+ //#region src/db/schema.ts
1398
+ var schema_exports = /* @__PURE__ */ __exportAll({
1399
+ agentEvents: () => agentEvents,
1400
+ appMeta: () => appMeta,
1401
+ approvals: () => approvals,
1402
+ auditLogs: () => auditLogs,
1403
+ authSettings: () => authSettings,
1404
+ browserSessions: () => browserSessions,
1405
+ commandExecutions: () => commandExecutions,
1406
+ credentialProfiles: () => credentialProfiles,
1407
+ deploymentApprovals: () => deploymentApprovals,
1408
+ deploymentArtifacts: () => deploymentArtifacts,
1409
+ deploymentAuthorizations: () => deploymentAuthorizations,
1410
+ deploymentBuilds: () => deploymentBuilds,
1411
+ deploymentPlans: () => deploymentPlans,
1412
+ deploymentTargets: () => deploymentTargets,
1413
+ deviceRequests: () => deviceRequests,
1414
+ fileVersions: () => fileVersions,
1415
+ modelCatalogCache: () => modelCatalogCache,
1416
+ modelDefaults: () => modelDefaults,
1417
+ modelProfiles: () => modelProfiles,
1418
+ modelVisibility: () => modelVisibility,
1419
+ projects: () => projects,
1420
+ resourceActions: () => resourceActions,
1421
+ resourceEvents: () => resourceEvents,
1422
+ resourceLocks: () => resourceLocks,
1423
+ resourceOperations: () => resourceOperations,
1424
+ resourceStreams: () => resourceStreams,
1425
+ scheduledJobRuns: () => scheduledJobRuns,
1426
+ scheduledJobs: () => scheduledJobs,
1427
+ secrets: () => secrets,
1428
+ serviceActionAuthorizations: () => serviceActionAuthorizations,
1429
+ serviceOpsDeployments: () => serviceOpsDeployments,
1430
+ serviceOpsServices: () => serviceOpsServices,
1431
+ services: () => services,
1432
+ sessionContextSummaries: () => sessionContextSummaries,
1433
+ sessions: () => sessions,
1434
+ terminalLeases: () => terminalLeases,
1435
+ terminals: () => terminals,
1436
+ trustedDevices: () => trustedDevices,
1437
+ turns: () => turns,
1438
+ webauthnChallenges: () => webauthnChallenges,
1439
+ webauthnCredentials: () => webauthnCredentials
1440
+ });
1441
+ const appMeta = sqliteTable("app_meta", {
1442
+ key: text("key").primaryKey(),
1443
+ value: text("value").notNull(),
1444
+ updatedAt: integer("updated_at").notNull()
1445
+ });
1446
+ const projects = sqliteTable("projects", {
1447
+ id: text("id").primaryKey(),
1448
+ name: text("name").notNull(),
1449
+ rootPath: text("root_path").notNull(),
1450
+ realPath: text("real_path").notNull().unique(),
1451
+ settingsJson: text("settings_json").notNull().default("{}"),
1452
+ gitDetected: integer("git_detected", { mode: "boolean" }).notNull().default(false),
1453
+ createdAt: integer("created_at").notNull(),
1454
+ updatedAt: integer("updated_at").notNull()
1455
+ }, (table) => [index("idx_projects_updated").on(table.updatedAt)]);
1456
+ const sessions = sqliteTable("sessions", {
1457
+ id: text("id").primaryKey(),
1458
+ projectId: text("project_id").references(() => projects.id, { onDelete: "set null" }),
1459
+ workspacePath: text("workspace_path").notNull(),
1460
+ title: text("title").notNull(),
1461
+ status: text("status").$type().notNull().default("active"),
1462
+ origin: text("origin").$type().notNull().default("user"),
1463
+ modelProfileId: text("model_profile_id"),
1464
+ credentialProfileId: text("credential_profile_id"),
1465
+ model: text("model"),
1466
+ thinking: text("thinking"),
1467
+ approvalPolicyId: text("approval_policy_id").notNull().default("standard"),
1468
+ createdAt: integer("created_at").notNull(),
1469
+ updatedAt: integer("updated_at").notNull(),
1470
+ lastActivityAt: integer("last_activity_at").notNull()
1471
+ }, (table) => [
1472
+ index("idx_sessions_project_updated").on(table.projectId, table.updatedAt),
1473
+ index("idx_sessions_updated").on(table.updatedAt),
1474
+ index("idx_sessions_origin").on(table.origin, table.updatedAt)
1475
+ ]);
1476
+ const turns = sqliteTable("turns", {
1477
+ id: text("id").primaryKey(),
1478
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1479
+ modelProfileId: text("model_profile_id"),
1480
+ credentialProfileId: text("credential_profile_id"),
1481
+ provider: text("provider"),
1482
+ model: text("model"),
1483
+ thinking: text("thinking"),
1484
+ contextWindow: integer("context_window"),
1485
+ status: text("status").$type().notNull(),
1486
+ inputJson: text("input_json").notNull(),
1487
+ usageJson: text("usage_json"),
1488
+ errorJson: text("error_json"),
1489
+ idempotencyKey: text("idempotency_key"),
1490
+ createdAt: integer("created_at").notNull(),
1491
+ startedAt: integer("started_at"),
1492
+ endedAt: integer("ended_at")
1493
+ }, (table) => [
1494
+ uniqueIndex("turns_session_idempotency_unique").on(table.sessionId, table.idempotencyKey),
1495
+ index("idx_turns_session_created").on(table.sessionId, table.createdAt),
1496
+ index("idx_turns_session_status").on(table.sessionId, table.status)
1497
+ ]);
1498
+ const agentEvents = sqliteTable("agent_events", {
1499
+ id: text("id").primaryKey(),
1500
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1501
+ turnId: text("turn_id").references(() => turns.id, { onDelete: "cascade" }),
1502
+ seq: integer("seq").notNull(),
1503
+ type: text("type").notNull(),
1504
+ payloadJson: text("payload_json").notNull().default("{}"),
1505
+ createdAt: integer("created_at").notNull()
1506
+ }, (table) => [uniqueIndex("agent_events_session_seq_unique").on(table.sessionId, table.seq)]);
1507
+ const approvals = sqliteTable("approvals", {
1508
+ id: text("id").primaryKey(),
1509
+ turnId: text("turn_id").notNull().references(() => turns.id, { onDelete: "cascade" }),
1510
+ toolCallId: text("tool_call_id").notNull(),
1511
+ toolName: text("tool_name").notNull(),
1512
+ risk: text("risk").notNull(),
1513
+ status: text("status").$type().notNull().default("pending"),
1514
+ scopeJson: text("scope_json").notNull().default("{}"),
1515
+ paramsHash: text("params_hash").notNull(),
1516
+ expiresAt: integer("expires_at").notNull(),
1517
+ decidedAt: integer("decided_at"),
1518
+ decidedBy: text("decided_by"),
1519
+ createdAt: integer("created_at").notNull()
1520
+ }, (table) => [index("idx_approvals_turn_status").on(table.turnId, table.status), index("idx_approvals_expiry").on(table.expiresAt)]);
1521
+ const resourceLocks = sqliteTable("resource_locks", {
1522
+ id: text("id").primaryKey(),
1523
+ resourceType: text("resource_type").$type().notNull(),
1524
+ resourceId: text("resource_id").notNull(),
1525
+ rootRealPath: text("root_real_path"),
1526
+ owner: text("owner").notNull(),
1527
+ executionId: text("execution_id").notNull(),
1528
+ fencingToken: integer("fencing_token").notNull(),
1529
+ expiresAt: integer("expires_at").notNull(),
1530
+ heartbeatAt: integer("heartbeat_at").notNull(),
1531
+ createdAt: integer("created_at").notNull()
1532
+ }, (table) => [uniqueIndex("resource_locks_resource_unique").on(table.resourceType, table.resourceId), index("idx_resource_locks_expiry").on(table.expiresAt)]);
1533
+ const secrets = sqliteTable("secrets", {
1534
+ id: text("id").primaryKey(),
1535
+ ciphertext: text("ciphertext").notNull(),
1536
+ nonce: text("nonce").notNull(),
1537
+ tag: text("tag").notNull(),
1538
+ createdAt: integer("created_at").notNull()
1539
+ });
1540
+ const credentialProfiles = sqliteTable("credential_profiles", {
1541
+ id: text("id").primaryKey(),
1542
+ provider: text("provider").$type().notNull(),
1543
+ label: text("label").notNull(),
1544
+ secretRef: text("secret_ref").notNull().references(() => secrets.id, { onDelete: "cascade" }),
1545
+ endpoint: text("endpoint"),
1546
+ contextWindow: integer("context_window"),
1547
+ createdAt: integer("created_at").notNull()
1548
+ }, (table) => [index("idx_credential_profiles_provider").on(table.provider)]);
1549
+ const modelProfiles = sqliteTable("model_profiles", {
1550
+ id: text("id").primaryKey(),
1551
+ label: text("label").notNull(),
1552
+ provider: text("provider").$type().notNull(),
1553
+ model: text("model").notNull(),
1554
+ credentialProfileId: text("credential_profile_id").references(() => credentialProfiles.id, { onDelete: "set null" }),
1555
+ endpoint: text("endpoint"),
1556
+ capabilitiesJson: text("capabilities_json").notNull().default("{}"),
1557
+ createdAt: integer("created_at").notNull()
1558
+ }, (table) => [index("idx_model_profiles_provider").on(table.provider)]);
1559
+ const modelCatalogCache = sqliteTable("model_catalog_cache", {
1560
+ credentialProfileId: text("credential_profile_id").primaryKey().references(() => credentialProfiles.id, { onDelete: "cascade" }),
1561
+ provider: text("provider").$type().notNull(),
1562
+ endpoint: text("endpoint").notNull(),
1563
+ modelsJson: text("models_json").notNull().default("[]"),
1564
+ syncedAt: integer("synced_at"),
1565
+ lastAttemptAt: integer("last_attempt_at"),
1566
+ lastErrorCode: text("last_error_code")
1567
+ });
1568
+ const modelVisibility = sqliteTable("model_visibility", {
1569
+ id: text("id").primaryKey(),
1570
+ credentialProfileId: text("credential_profile_id").notNull().references(() => credentialProfiles.id, { onDelete: "cascade" }),
1571
+ modelId: text("model_id").notNull(),
1572
+ visible: integer("visible").notNull().default(1),
1573
+ updatedAt: integer("updated_at").notNull()
1574
+ }, (table) => [uniqueIndex("model_visibility_credential_model").on(table.credentialProfileId, table.modelId)]);
1575
+ const sessionContextSummaries = sqliteTable("session_context_summaries", {
1576
+ id: text("id").primaryKey(),
1577
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1578
+ coveredUpToSeq: integer("covered_up_to_seq").notNull(),
1579
+ summary: text("summary").notNull(),
1580
+ tokensBefore: integer("tokens_before").notNull(),
1581
+ tokensAfter: integer("tokens_after").notNull(),
1582
+ degraded: integer("degraded").notNull().default(0),
1583
+ createdAt: integer("created_at").notNull()
1584
+ }, (table) => [index("idx_context_summaries_session").on(table.sessionId, table.createdAt)]);
1585
+ const modelDefaults = sqliteTable("model_defaults", {
1586
+ id: text("id").primaryKey(),
1587
+ credentialProfileId: text("credential_profile_id").notNull().references(() => credentialProfiles.id, { onDelete: "cascade" }),
1588
+ model: text("model").notNull(),
1589
+ thinking: text("thinking").notNull(),
1590
+ updatedAt: integer("updated_at").notNull()
1591
+ }, (table) => [check("model_defaults_single_row", sql`${table.id} = 'default'`)]);
1592
+ const authSettings = sqliteTable("auth_settings", {
1593
+ id: integer("id").primaryKey(),
1594
+ adminHash: text("admin_hash").notNull(),
1595
+ adminUpdatedAt: integer("admin_updated_at").notNull(),
1596
+ initializedAt: integer("initialized_at").notNull()
1597
+ }, (table) => [check("auth_settings_single_row", sql`${table.id} = 1`)]);
1598
+ const deviceRequests = sqliteTable("device_requests", {
1599
+ id: text("id").primaryKey(),
1600
+ shortCode: text("short_code").notNull().unique(),
1601
+ status: text("status").$type().notNull(),
1602
+ decision: text("decision").$type(),
1603
+ clientLabel: text("client_label"),
1604
+ userAgent: text("user_agent"),
1605
+ ip: text("ip"),
1606
+ clientOrigin: text("client_origin"),
1607
+ pollTokenHash: text("poll_token_hash").notNull(),
1608
+ codeHash: text("code_hash"),
1609
+ codeExpiresAt: integer("code_expires_at"),
1610
+ attempts: integer("attempts").notNull().default(0),
1611
+ enrollmentTokenHash: text("enrollment_token_hash"),
1612
+ enrollmentExpiresAt: integer("enrollment_expires_at"),
1613
+ createdAt: integer("created_at").notNull(),
1614
+ expiresAt: integer("expires_at").notNull(),
1615
+ decidedAt: integer("decided_at"),
1616
+ redeemedAt: integer("redeemed_at")
1617
+ }, (table) => [index("idx_device_requests_status").on(table.status, table.expiresAt)]);
1618
+ const trustedDevices = sqliteTable("trusted_devices", {
1619
+ id: text("id").primaryKey(),
1620
+ label: text("label").notNull(),
1621
+ createdByRequestId: text("created_by_request_id").references(() => deviceRequests.id),
1622
+ userAgent: text("user_agent"),
1623
+ createdAt: integer("created_at").notNull(),
1624
+ lastSeenAt: integer("last_seen_at"),
1625
+ revokedAt: integer("revoked_at")
1626
+ });
1627
+ const webauthnCredentials = sqliteTable("webauthn_credentials", {
1628
+ id: text("id").primaryKey(),
1629
+ deviceId: text("device_id").notNull().references(() => trustedDevices.id),
1630
+ credentialId: text("credential_id").notNull().unique(),
1631
+ publicKey: text("public_key").notNull(),
1632
+ counter: integer("counter").notNull().default(0),
1633
+ transportsJson: text("transports_json").notNull().default("[]"),
1634
+ aaguid: text("aaguid"),
1635
+ backupEligible: integer("backup_eligible", { mode: "boolean" }).notNull().default(false),
1636
+ backupState: integer("backup_state", { mode: "boolean" }).notNull().default(false),
1637
+ createdAt: integer("created_at").notNull(),
1638
+ lastUsedAt: integer("last_used_at"),
1639
+ revokedAt: integer("revoked_at")
1640
+ }, (table) => [index("idx_webauthn_credentials_device").on(table.deviceId)]);
1641
+ const webauthnChallenges = sqliteTable("webauthn_challenges", {
1642
+ id: text("id").primaryKey(),
1643
+ type: text("type").$type().notNull(),
1644
+ challenge: text("challenge").notNull(),
1645
+ requestId: text("request_id").references(() => deviceRequests.id),
1646
+ deviceId: text("device_id").references(() => trustedDevices.id),
1647
+ createdAt: integer("created_at").notNull(),
1648
+ expiresAt: integer("expires_at").notNull(),
1649
+ consumedAt: integer("consumed_at")
1650
+ }, (table) => [index("idx_webauthn_challenges_expiry").on(table.expiresAt)]);
1651
+ const browserSessions = sqliteTable("browser_sessions", {
1652
+ id: text("id").primaryKey(),
1653
+ deviceId: text("device_id").references(() => trustedDevices.id),
1654
+ tokenHash: text("token_hash").notNull().unique(),
1655
+ kind: text("kind").$type().notNull(),
1656
+ ip: text("ip"),
1657
+ userAgent: text("user_agent"),
1658
+ createdAt: integer("created_at").notNull(),
1659
+ lastSeenAt: integer("last_seen_at").notNull(),
1660
+ expiresAt: integer("expires_at").notNull(),
1661
+ revokedAt: integer("revoked_at")
1662
+ }, (table) => [index("idx_browser_sessions_device").on(table.deviceId)]);
1663
+ const auditLogs = sqliteTable("audit_logs", {
1664
+ id: text("id").primaryKey(),
1665
+ clientSessionId: text("client_session_id"),
1666
+ sessionId: text("session_id"),
1667
+ action: text("action").notNull(),
1668
+ resourceType: text("resource_type"),
1669
+ resourceId: text("resource_id"),
1670
+ decision: text("decision").$type(),
1671
+ detailsJson: text("details_json").notNull().default("{}"),
1672
+ createdAt: integer("created_at").notNull()
1673
+ }, (table) => [index("idx_audit_created").on(table.createdAt), index("idx_audit_action").on(table.action, table.createdAt)]);
1674
+ const fileVersions = sqliteTable("file_versions", {
1675
+ scopeKey: text("scope_key").notNull(),
1676
+ path: text("path").notNull(),
1677
+ realPath: text("real_path").notNull(),
1678
+ versionHash: text("version_hash").notNull(),
1679
+ size: integer("size").notNull(),
1680
+ mtime: integer("mtime").notNull(),
1681
+ updatedAt: integer("updated_at").notNull()
1682
+ }, (table) => [uniqueIndex("file_versions_scope_path").on(table.scopeKey, table.path)]);
1683
+ const resourceStreams = sqliteTable("resource_streams", {
1684
+ streamId: text("stream_id").primaryKey(),
1685
+ lastSeq: integer("last_seq").notNull().default(0)
1686
+ });
1687
+ const resourceEvents = sqliteTable("resource_events", {
1688
+ id: text("id").primaryKey(),
1689
+ streamId: text("stream_id").notNull().references(() => resourceStreams.streamId),
1690
+ seq: integer("seq").notNull(),
1691
+ type: text("type").notNull(),
1692
+ payloadJson: text("payload_json").notNull(),
1693
+ createdAt: integer("created_at").notNull()
1694
+ }, (table) => [uniqueIndex("resource_events_stream_seq").on(table.streamId, table.seq)]);
1695
+ const resourceOperations = sqliteTable("resource_operations", {
1696
+ id: text("id").primaryKey(),
1697
+ scopeKey: text("scope_key").notNull(),
1698
+ rootRealPath: text("root_real_path").notNull(),
1699
+ kind: text("kind").notNull(),
1700
+ status: text("status").$type().notNull(),
1701
+ paramsHash: text("params_hash").notNull(),
1702
+ idempotencyKey: text("idempotency_key").notNull(),
1703
+ clientSessionId: text("client_session_id").notNull(),
1704
+ path: text("path").notNull(),
1705
+ expectedVersion: text("expected_version").notNull(),
1706
+ targetVersion: text("target_version").notNull(),
1707
+ lockId: text("lock_id").notNull(),
1708
+ fencingToken: integer("fencing_token").notNull(),
1709
+ resultJson: text("result_json"),
1710
+ errorCode: text("error_code"),
1711
+ createdAt: integer("created_at").notNull(),
1712
+ updatedAt: integer("updated_at").notNull()
1713
+ }, (table) => [uniqueIndex("resource_operations_client_kind_key").on(table.clientSessionId, table.kind, table.idempotencyKey), index("resource_operations_status").on(table.status)]);
1714
+ const commandExecutions = sqliteTable("command_executions", {
1715
+ id: text("id").primaryKey(),
1716
+ operationId: text("operation_id").notNull().references(() => resourceOperations.id),
1717
+ projectId: text("project_id"),
1718
+ workspaceSessionId: text("workspace_session_id"),
1719
+ sessionId: text("session_id").notNull(),
1720
+ turnId: text("turn_id").notNull(),
1721
+ toolCallId: text("tool_call_id").notNull(),
1722
+ policySnapshotId: text("policy_snapshot_id").notNull(),
1723
+ paramsHash: text("params_hash").notNull(),
1724
+ status: text("status").$type().notNull(),
1725
+ exitCode: integer("exit_code"),
1726
+ reasonCode: text("reason_code"),
1727
+ truncated: integer("truncated", { mode: "boolean" }).notNull().default(false),
1728
+ processIdentityJson: text("process_identity_json"),
1729
+ outputCursor: integer("output_cursor").notNull().default(0),
1730
+ createdAt: integer("created_at").notNull(),
1731
+ startedAt: integer("started_at"),
1732
+ endedAt: integer("ended_at")
1733
+ }, (table) => [uniqueIndex("command_executions_operation").on(table.operationId), index("command_executions_status").on(table.status)]);
1734
+ const terminals = sqliteTable("terminals", {
1735
+ id: text("id").primaryKey(),
1736
+ operationId: text("operation_id").notNull().references(() => resourceOperations.id),
1737
+ projectId: text("project_id"),
1738
+ workspaceSessionId: text("workspace_session_id"),
1739
+ sourceSessionId: text("source_session_id"),
1740
+ cwd: text("cwd").notNull(),
1741
+ shell: text("shell").notNull(),
1742
+ mode: text("mode").$type().notNull(),
1743
+ role: text("role"),
1744
+ title: text("title"),
1745
+ launchParamsJson: text("launch_params_json"),
1746
+ launchParamsHash: text("launch_params_hash"),
1747
+ createdByTurnId: text("created_by_turn_id"),
1748
+ status: text("status").$type().notNull(),
1749
+ processIdentityJson: text("process_identity_json"),
1750
+ reasonCode: text("reason_code"),
1751
+ outputCursor: integer("output_cursor").notNull().default(0),
1752
+ createdAt: integer("created_at").notNull(),
1753
+ startedAt: integer("started_at"),
1754
+ endedAt: integer("ended_at"),
1755
+ exitCode: integer("exit_code")
1756
+ }, (table) => [
1757
+ uniqueIndex("terminals_operation").on(table.operationId),
1758
+ index("terminals_status").on(table.status),
1759
+ uniqueIndex("terminals_active_role").on(table.projectId, table.role).where(sql`${table.mode} = 'dev' AND ${table.status} IN ('CREATED', 'RUNNING', 'STOPPING')`)
1760
+ ]);
1761
+ const services = sqliteTable("services", {
1762
+ id: text("id").primaryKey(),
1763
+ operationId: text("operation_id").notNull().references(() => resourceOperations.id),
1764
+ projectId: text("project_id").notNull().references(() => projects.id),
1765
+ sourceSessionId: text("source_session_id"),
1766
+ terminalId: text("terminal_id").notNull().references(() => terminals.id),
1767
+ name: text("name").notNull(),
1768
+ kind: text("kind").$type().notNull(),
1769
+ status: text("status").$type().notNull(),
1770
+ terminalExecutionId: text("terminal_execution_id").notNull(),
1771
+ endpointGeneration: integer("endpoint_generation").notNull(),
1772
+ endpointHost: text("endpoint_host").notNull(),
1773
+ endpointPort: integer("endpoint_port").notNull(),
1774
+ endpointProtocol: text("endpoint_protocol").$type().notNull(),
1775
+ identityJson: text("identity_json").notNull(),
1776
+ reasonCode: text("reason_code"),
1777
+ createdAt: integer("created_at").notNull(),
1778
+ updatedAt: integer("updated_at").notNull(),
1779
+ endedAt: integer("ended_at")
1780
+ }, (table) => [
1781
+ uniqueIndex("services_operation").on(table.operationId),
1782
+ index("services_project_status").on(table.projectId, table.status),
1783
+ index("services_terminal").on(table.terminalId),
1784
+ uniqueIndex("services_active_endpoint").on(table.terminalId, table.endpointHost, table.endpointPort).where(sql`${table.status} IN ('REGISTERING', 'STARTING', 'RUNNING')`),
1785
+ check("services_status", sql`${table.status} IN ('REGISTERING', 'STARTING', 'RUNNING', 'UNKNOWN', 'UNREGISTERED')`),
1786
+ check("services_host", sql`${table.endpointHost} IN ('127.0.0.1', '::1')`),
1787
+ check("services_port", sql`${table.endpointPort} BETWEEN 1 AND 65535`),
1788
+ check("services_protocol", sql`${table.endpointProtocol} = 'http'`)
1789
+ ]);
1790
+ const resourceActions = sqliteTable("resource_actions", {
1791
+ id: text("id").primaryKey(),
1792
+ operationId: text("operation_id").notNull().references(() => resourceOperations.id),
1793
+ projectId: text("project_id").notNull().references(() => projects.id),
1794
+ kind: text("kind").notNull(),
1795
+ risk: text("risk").$type().notNull(),
1796
+ status: text("status").$type().notNull(),
1797
+ paramsJson: text("params_json").notNull(),
1798
+ paramsHash: text("params_hash").notNull(),
1799
+ snapshotHash: text("snapshot_hash").notNull(),
1800
+ requestedBy: text("requested_by").notNull(),
1801
+ decidedBy: text("decided_by"),
1802
+ expiresAt: integer("expires_at").notNull(),
1803
+ decidedAt: integer("decided_at"),
1804
+ startedAt: integer("started_at"),
1805
+ endedAt: integer("ended_at"),
1806
+ resultJson: text("result_json"),
1807
+ createdAt: integer("created_at").notNull()
1808
+ }, (table) => [uniqueIndex("resource_actions_operation").on(table.operationId), index("resource_actions_project_status").on(table.projectId, table.status)]);
1809
+ const terminalLeases = sqliteTable("terminal_leases", {
1810
+ terminalId: text("terminal_id").primaryKey().references(() => terminals.id),
1811
+ generation: integer("generation").notNull().default(0),
1812
+ ownerType: text("owner_type").$type(),
1813
+ ownerClientSessionId: text("owner_client_session_id"),
1814
+ ownerConnectionId: text("owner_connection_id"),
1815
+ ownerSessionId: text("owner_session_id"),
1816
+ ownerTurnId: text("owner_turn_id"),
1817
+ ownerExecutionId: text("owner_execution_id"),
1818
+ expiresAt: integer("expires_at").notNull().default(0),
1819
+ heartbeatAt: integer("heartbeat_at").notNull().default(0),
1820
+ inputSequence: integer("input_sequence").notNull().default(0)
1821
+ });
1822
+ const deploymentTargets = sqliteTable("deployment_targets", {
1823
+ id: text("id").primaryKey(),
1824
+ projectId: text("project_id").notNull().references(() => projects.id),
1825
+ name: text("name").notNull(),
1826
+ currentArtifactId: text("current_artifact_id"),
1827
+ currentVersion: text("current_version"),
1828
+ createdAt: integer("created_at").notNull(),
1829
+ updatedAt: integer("updated_at").notNull()
1830
+ }, (table) => [
1831
+ uniqueIndex("deployment_targets_project_name").on(table.projectId, table.name),
1832
+ index("deployment_targets_project_updated").on(table.projectId, table.updatedAt),
1833
+ check("deployment_targets_current", sql`(${table.currentArtifactId} IS NULL) = (${table.currentVersion} IS NULL)`)
1834
+ ]);
1835
+ const deploymentBuilds = sqliteTable("deployment_builds", {
1836
+ id: text("id").primaryKey(),
1837
+ targetId: text("target_id").notNull().references(() => deploymentTargets.id),
1838
+ projectId: text("project_id").notNull().references(() => projects.id),
1839
+ requestKey: text("request_key").notNull(),
1840
+ requestedBy: text("requested_by").notNull(),
1841
+ status: text("status").$type().notNull(),
1842
+ specJson: text("spec_json").notNull(),
1843
+ specHash: text("spec_hash").notNull(),
1844
+ reasonCode: text("reason_code"),
1845
+ logRef: text("log_ref").notNull(),
1846
+ startedAt: integer("started_at"),
1847
+ endedAt: integer("ended_at"),
1848
+ createdAt: integer("created_at").notNull()
1849
+ }, (table) => [
1850
+ uniqueIndex("deployment_builds_request").on(table.requestKey),
1851
+ index("deployment_builds_target_created").on(table.targetId, table.createdAt),
1852
+ index("deployment_builds_status").on(table.status),
1853
+ check("deployment_builds_status", sql`${table.status} IN ('RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELLED')`)
1854
+ ]);
1855
+ const deploymentArtifacts = sqliteTable("deployment_artifacts", {
1856
+ id: text("id").primaryKey(),
1857
+ buildId: text("build_id").notNull().references(() => deploymentBuilds.id),
1858
+ targetId: text("target_id").notNull().references(() => deploymentTargets.id),
1859
+ projectId: text("project_id").notNull().references(() => projects.id),
1860
+ version: text("version").notNull(),
1861
+ artifactHash: text("artifact_hash").notNull(),
1862
+ artifactPath: text("artifact_path").notNull(),
1863
+ sizeBytes: integer("size_bytes").notNull(),
1864
+ fileCount: integer("file_count").notNull(),
1865
+ specJson: text("spec_json").notNull(),
1866
+ specHash: text("spec_hash").notNull(),
1867
+ sourceJson: text("source_json").notNull(),
1868
+ createdAt: integer("created_at").notNull()
1869
+ }, (table) => [
1870
+ uniqueIndex("deployment_artifacts_build").on(table.buildId),
1871
+ uniqueIndex("deployment_artifacts_target_version").on(table.targetId, table.version),
1872
+ index("deployment_artifacts_target_created").on(table.targetId, table.createdAt),
1873
+ check("deployment_artifacts_hash", sql`length(${table.artifactHash}) = 64`),
1874
+ check("deployment_artifacts_size", sql`${table.sizeBytes} >= 0`),
1875
+ check("deployment_artifacts_count", sql`${table.fileCount} >= 0`)
1876
+ ]);
1877
+ const deploymentPlans = sqliteTable("deployment_plans", {
1878
+ id: text("id").primaryKey(),
1879
+ targetId: text("target_id").notNull().references(() => deploymentTargets.id),
1880
+ projectId: text("project_id").notNull().references(() => projects.id),
1881
+ artifactId: text("artifact_id").notNull().references(() => deploymentArtifacts.id),
1882
+ previousArtifactId: text("previous_artifact_id").references(() => deploymentArtifacts.id),
1883
+ previousVersion: text("previous_version"),
1884
+ version: text("version").notNull(),
1885
+ planJson: text("plan_json").notNull(),
1886
+ planHash: text("plan_hash").notNull(),
1887
+ status: text("status").$type().notNull(),
1888
+ expiresAt: integer("expires_at").notNull(),
1889
+ requestKey: text("request_key").notNull(),
1890
+ requestedBy: text("requested_by").notNull(),
1891
+ createdAt: integer("created_at").notNull()
1892
+ }, (table) => [
1893
+ uniqueIndex("deployment_plans_request").on(table.requestKey),
1894
+ index("deployment_plans_target_created").on(table.targetId, table.createdAt),
1895
+ index("deployment_plans_status_expires").on(table.status, table.expiresAt),
1896
+ check("deployment_plans_status", sql`${table.status} IN ('READY', 'WAITING_APPROVAL', 'AUTHORIZED', 'APPLYING', 'HEALTH_CHECK', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'EXPIRED', 'INVALIDATED', 'UNKNOWN')`),
1897
+ check("deployment_plans_hash", sql`length(${table.planHash}) = 64`),
1898
+ check("deployment_plans_previous", sql`(${table.previousArtifactId} IS NULL) = (${table.previousVersion} IS NULL)`)
1899
+ ]);
1900
+ const deploymentAuthorizations = sqliteTable("deployment_authorizations", {
1901
+ id: text("id").primaryKey(),
1902
+ planId: text("plan_id").notNull().references(() => deploymentPlans.id),
1903
+ targetId: text("target_id").notNull().references(() => deploymentTargets.id),
1904
+ projectId: text("project_id").notNull().references(() => projects.id),
1905
+ action: text("action").$type().notNull(),
1906
+ actorType: text("actor_type").$type().notNull(),
1907
+ actorId: text("actor_id").notNull(),
1908
+ clientSessionId: text("client_session_id"),
1909
+ sessionId: text("session_id"),
1910
+ turnId: text("turn_id"),
1911
+ policy: text("policy").$type().notNull(),
1912
+ policySnapshotId: text("policy_snapshot_id").notNull(),
1913
+ status: text("status").$type().notNull(),
1914
+ planHash: text("plan_hash").notNull(),
1915
+ artifactHash: text("artifact_hash").notNull(),
1916
+ scopeJson: text("scope_json").notNull(),
1917
+ scopeHash: text("scope_hash").notNull(),
1918
+ approvalId: text("approval_id"),
1919
+ requestKey: text("request_key").notNull(),
1920
+ expiresAt: integer("expires_at").notNull(),
1921
+ decidedAt: integer("decided_at"),
1922
+ consumedAt: integer("consumed_at"),
1923
+ consumeKey: text("consume_key"),
1924
+ reasonCode: text("reason_code"),
1925
+ createdAt: integer("created_at").notNull()
1926
+ }, (table) => [
1927
+ uniqueIndex("deployment_authorizations_request").on(table.requestKey),
1928
+ index("deployment_authorizations_plan_status").on(table.planId, table.status),
1929
+ index("deployment_authorizations_target_status").on(table.targetId, table.status),
1930
+ index("deployment_authorizations_status_expires").on(table.status, table.expiresAt),
1931
+ check("deployment_authorizations_action", sql`${table.action} = 'apply'`),
1932
+ check("deployment_authorizations_actor", sql`${table.actorType} IN ('human', 'agent')`),
1933
+ check("deployment_authorizations_policy", sql`${table.policy} IN ('standard', 'strict', 'readonly', 'autonomous')`),
1934
+ check("deployment_authorizations_status", sql`${table.status} IN ('PENDING', 'AUTHORIZED', 'DENIED', 'EXPIRED', 'REVOKED', 'CONSUMED', 'INVALIDATED')`),
1935
+ check("deployment_authorizations_plan_hash", sql`length(${table.planHash}) = 64`),
1936
+ check("deployment_authorizations_artifact_hash", sql`length(${table.artifactHash}) = 64`),
1937
+ check("deployment_authorizations_scope_hash", sql`length(${table.scopeHash}) = 64`)
1938
+ ]);
1939
+ const deploymentApprovals = sqliteTable("deployment_approvals", {
1940
+ id: text("id").primaryKey(),
1941
+ authorizationId: text("authorization_id").notNull().references(() => deploymentAuthorizations.id),
1942
+ planId: text("plan_id").notNull().references(() => deploymentPlans.id),
1943
+ targetId: text("target_id").notNull().references(() => deploymentTargets.id),
1944
+ projectId: text("project_id").notNull().references(() => projects.id),
1945
+ status: text("status").$type().notNull(),
1946
+ planHash: text("plan_hash").notNull(),
1947
+ artifactHash: text("artifact_hash").notNull(),
1948
+ requestedBy: text("requested_by").notNull(),
1949
+ decidedBy: text("decided_by"),
1950
+ expiresAt: integer("expires_at").notNull(),
1951
+ decidedAt: integer("decided_at"),
1952
+ createdAt: integer("created_at").notNull()
1953
+ }, (table) => [
1954
+ uniqueIndex("deployment_approvals_authorization").on(table.authorizationId),
1955
+ index("deployment_approvals_status_expires").on(table.status, table.expiresAt),
1956
+ check("deployment_approvals_status", sql`${table.status} IN ('PENDING', 'APPROVED', 'DENIED', 'EXPIRED', 'REVOKED')`),
1957
+ check("deployment_approvals_plan_hash", sql`length(${table.planHash}) = 64`),
1958
+ check("deployment_approvals_artifact_hash", sql`length(${table.artifactHash}) = 64`)
1959
+ ]);
1960
+ const serviceOpsServices = sqliteTable("service_ops_services", {
1961
+ targetId: text("target_id").primaryKey().references(() => deploymentTargets.id),
1962
+ projectId: text("project_id").notNull().references(() => projects.id),
1963
+ name: text("name").notNull(),
1964
+ namespace: text("namespace").notNull(),
1965
+ pm2Name: text("pm2_name").notNull().unique(),
1966
+ desiredState: text("desired_state").$type().notNull(),
1967
+ observedState: text("observed_state").$type().notNull(),
1968
+ currentArtifactId: text("current_artifact_id").references(() => deploymentArtifacts.id),
1969
+ currentVersion: text("current_version"),
1970
+ configJson: text("config_json").notNull(),
1971
+ pid: integer("pid"),
1972
+ lastHealthAt: integer("last_health_at"),
1973
+ reasonCode: text("reason_code"),
1974
+ createdAt: integer("created_at").notNull(),
1975
+ updatedAt: integer("updated_at").notNull()
1976
+ }, (table) => [
1977
+ index("service_ops_services_project").on(table.projectId, table.updatedAt),
1978
+ check("service_ops_services_desired", sql`${table.desiredState} IN ('running', 'stopped')`),
1979
+ check("service_ops_services_observed", sql`${table.observedState} IN ('stopped', 'starting', 'running', 'unhealthy', 'stopping', 'failed', 'unknown')`)
1980
+ ]);
1981
+ const serviceOpsDeployments = sqliteTable("service_ops_deployments", {
1982
+ id: text("id").primaryKey(),
1983
+ targetId: text("target_id").notNull().references(() => deploymentTargets.id),
1984
+ projectId: text("project_id").notNull().references(() => projects.id),
1985
+ planId: text("plan_id").notNull().references(() => deploymentPlans.id),
1986
+ authorizationId: text("authorization_id").notNull().references(() => deploymentAuthorizations.id),
1987
+ artifactId: text("artifact_id").notNull().references(() => deploymentArtifacts.id),
1988
+ previousArtifactId: text("previous_artifact_id").references(() => deploymentArtifacts.id),
1989
+ previousVersion: text("previous_version"),
1990
+ version: text("version").notNull(),
1991
+ status: text("status").$type().notNull(),
1992
+ planHash: text("plan_hash").notNull(),
1993
+ artifactHash: text("artifact_hash").notNull(),
1994
+ actorType: text("actor_type").$type().notNull(),
1995
+ actorId: text("actor_id").notNull(),
1996
+ policy: text("policy").$type().notNull(),
1997
+ policySnapshotId: text("policy_snapshot_id").notNull(),
1998
+ reasonCode: text("reason_code"),
1999
+ healthJson: text("health_json"),
2000
+ resultJson: text("result_json"),
2001
+ startedAt: integer("started_at").notNull(),
2002
+ endedAt: integer("ended_at"),
2003
+ createdAt: integer("created_at").notNull()
2004
+ }, (table) => [
2005
+ uniqueIndex("service_ops_deployments_plan").on(table.planId),
2006
+ uniqueIndex("service_ops_deployments_authorization").on(table.authorizationId),
2007
+ index("service_ops_deployments_target_created").on(table.targetId, table.createdAt),
2008
+ index("service_ops_deployments_status").on(table.status),
2009
+ check("service_ops_deployments_status", sql`${table.status} IN ('APPLYING', 'HEALTH_CHECK', 'SUCCEEDED', 'FAILED', 'UNKNOWN')`),
2010
+ check("service_ops_deployments_plan_hash", sql`length(${table.planHash}) = 64`),
2011
+ check("service_ops_deployments_artifact_hash", sql`length(${table.artifactHash}) = 64`),
2012
+ check("service_ops_deployments_previous", sql`(${table.previousArtifactId} IS NULL) = (${table.previousVersion} IS NULL)`)
2013
+ ]);
2014
+ const serviceActionAuthorizations = sqliteTable("service_action_authorizations", {
2015
+ id: text("id").primaryKey(),
2016
+ targetId: text("target_id").notNull().references(() => deploymentTargets.id),
2017
+ projectId: text("project_id").notNull().references(() => projects.id),
2018
+ action: text("action").$type().notNull(),
2019
+ actorType: text("actor_type").$type().notNull(),
2020
+ actorId: text("actor_id").notNull(),
2021
+ clientSessionId: text("client_session_id"),
2022
+ sessionId: text("session_id"),
2023
+ turnId: text("turn_id"),
2024
+ policy: text("policy").$type().notNull(),
2025
+ policySnapshotId: text("policy_snapshot_id").notNull(),
2026
+ status: text("status").$type().notNull(),
2027
+ artifactHash: text("artifact_hash").notNull(),
2028
+ version: text("version").notNull(),
2029
+ scopeJson: text("scope_json").notNull(),
2030
+ scopeHash: text("scope_hash").notNull(),
2031
+ requestKey: text("request_key").notNull(),
2032
+ expiresAt: integer("expires_at").notNull(),
2033
+ decidedAt: integer("decided_at"),
2034
+ decidedBy: text("decided_by"),
2035
+ consumedAt: integer("consumed_at"),
2036
+ consumeKey: text("consume_key"),
2037
+ reasonCode: text("reason_code"),
2038
+ createdAt: integer("created_at").notNull()
2039
+ }, (table) => [
2040
+ uniqueIndex("service_action_authorizations_request").on(table.requestKey),
2041
+ index("service_action_authorizations_target_status").on(table.targetId, table.status),
2042
+ index("service_action_authorizations_status_expires").on(table.status, table.expiresAt),
2043
+ check("service_action_authorizations_action", sql`${table.action} IN ('start', 'stop', 'restart', 'recover')`),
2044
+ check("service_action_authorizations_status", sql`${table.status} IN ('PENDING', 'AUTHORIZED', 'DENIED', 'EXPIRED', 'REVOKED', 'CONSUMED')`),
2045
+ check("service_action_authorizations_artifact_hash", sql`length(${table.artifactHash}) = 64`),
2046
+ check("service_action_authorizations_scope_hash", sql`length(${table.scopeHash}) = 64`)
2047
+ ]);
2048
+ const scheduledJobs = sqliteTable("scheduled_jobs", {
2049
+ id: text("id").primaryKey(),
2050
+ name: text("name").notNull(),
2051
+ projectId: text("project_id").references(() => projects.id, { onDelete: "cascade" }),
2052
+ kind: text("kind").$type().notNull(),
2053
+ scheduleType: text("schedule_type").$type().notNull(),
2054
+ cronExpression: text("cron_expression"),
2055
+ intervalSeconds: integer("interval_seconds"),
2056
+ timezone: text("timezone").notNull(),
2057
+ enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
2058
+ overlapPolicy: text("overlap_policy").notNull().default("skip"),
2059
+ missedPolicy: text("missed_policy").notNull().default("skip"),
2060
+ timeoutSeconds: integer("timeout_seconds").notNull().default(600),
2061
+ scriptSource: text("script_source"),
2062
+ agentPrompt: text("agent_prompt"),
2063
+ agentModel: text("agent_model"),
2064
+ agentCredentialProfileId: text("agent_credential_profile_id").references(() => credentialProfiles.id, { onDelete: "set null" }),
2065
+ agentThinking: text("agent_thinking"),
2066
+ agentApprovalPolicy: text("agent_approval_policy").$type(),
2067
+ sessionId: text("session_id").references(() => sessions.id, { onDelete: "set null" }),
2068
+ nextRunAt: integer("next_run_at"),
2069
+ lastRunAt: integer("last_run_at"),
2070
+ lastStatus: text("last_status").$type(),
2071
+ createdAt: integer("created_at").notNull(),
2072
+ updatedAt: integer("updated_at").notNull(),
2073
+ archivedAt: integer("archived_at")
2074
+ }, (table) => [index("idx_scheduled_jobs_due").on(table.enabled, table.archivedAt, table.nextRunAt), index("idx_scheduled_jobs_project").on(table.projectId, table.updatedAt)]);
2075
+ const scheduledJobRuns = sqliteTable("scheduled_job_runs", {
2076
+ id: text("id").primaryKey(),
2077
+ jobId: text("job_id").notNull().references(() => scheduledJobs.id, { onDelete: "cascade" }),
2078
+ trigger: text("trigger").$type().notNull(),
2079
+ status: text("status").$type().notNull(),
2080
+ scheduledFor: integer("scheduled_for").notNull(),
2081
+ startedAt: integer("started_at"),
2082
+ endedAt: integer("ended_at"),
2083
+ durationMs: integer("duration_ms"),
2084
+ sessionId: text("session_id").references(() => sessions.id, { onDelete: "set null" }),
2085
+ turnId: text("turn_id").references(() => turns.id, { onDelete: "set null" }),
2086
+ exitCode: integer("exit_code"),
2087
+ output: text("output"),
2088
+ errorCode: text("error_code"),
2089
+ errorMessage: text("error_message"),
2090
+ createdAt: integer("created_at").notNull()
2091
+ }, (table) => [index("idx_scheduled_job_runs_job").on(table.jobId, table.createdAt), index("idx_scheduled_job_runs_status").on(table.status, table.createdAt)]);
2092
+ //#endregion
2093
+ //#region src/db/repositories/meta.ts
2094
+ function getMeta(db, key) {
2095
+ return db.select().from(appMeta).where(eq(appMeta.key, key)).get()?.value ?? null;
2096
+ }
2097
+ function setMeta(db, key, value, now = Date.now()) {
2098
+ db.insert(appMeta).values({
2099
+ key,
2100
+ value,
2101
+ updatedAt: now
2102
+ }).onConflictDoUpdate({
2103
+ target: appMeta.key,
2104
+ set: {
2105
+ value,
2106
+ updatedAt: now
2107
+ }
2108
+ }).run();
2109
+ }
2110
+ function ensureInstanceId(db, now = Date.now()) {
2111
+ const existing = getMeta(db, "instance_id");
2112
+ if (existing !== null) return existing;
2113
+ const instanceId = newId("inst");
2114
+ setMeta(db, "instance_id", instanceId, now);
2115
+ return instanceId;
2116
+ }
2117
+ function deleteMeta(db, key) {
2118
+ db.delete(appMeta).where(eq(appMeta.key, key)).run();
2119
+ }
2120
+ //#endregion
2121
+ //#region src/version.ts
2122
+ function readPackageVersion() {
2123
+ try {
2124
+ const raw = JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8"));
2125
+ return typeof raw.version === "string" ? raw.version : "0.0.0";
2126
+ } catch {
2127
+ return "0.0.0";
2128
+ }
2129
+ }
2130
+ const SERVER_VERSION = readPackageVersion();
2131
+ //#endregion
2132
+ //#region src/db/migrate.ts
2133
+ const SERVER_PACKAGE_NAME = "@larness/server";
2134
+ function findServerRoot(startDirectory) {
2135
+ let directory = startDirectory;
2136
+ for (;;) {
2137
+ const packageFile = path.join(directory, "package.json");
2138
+ if (existsSync(packageFile)) try {
2139
+ if (JSON.parse(readFileSync(packageFile, "utf8")).name === SERVER_PACKAGE_NAME) return directory;
2140
+ } catch {}
2141
+ const parent = path.dirname(directory);
2142
+ if (parent === directory) throw new Error(`cannot locate the ${SERVER_PACKAGE_NAME} package root`);
2143
+ directory = parent;
2144
+ }
2145
+ }
2146
+ function migrationsDirectory() {
2147
+ const here = fileURLToPath(new URL(".", import.meta.url));
2148
+ return path.join(findServerRoot(here), "drizzle");
2149
+ }
2150
+ function runMigrations(db, folder = migrationsDirectory()) {
2151
+ if (!existsSync(path.join(folder, "meta", "_journal.json"))) throw new Error(`migration directory is invalid or empty: ${folder}`);
2152
+ migrate(db, { migrationsFolder: folder });
2153
+ }
2154
+ function appliedMigrationCount(sqlite) {
2155
+ if (sqlite.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'").get() === void 0) return 0;
2156
+ return sqlite.prepare("SELECT count(*) AS count FROM __drizzle_migrations").get()?.count ?? 0;
2157
+ }
2158
+ function expectedMigrationCount(folder = migrationsDirectory()) {
2159
+ const journalFile = path.join(folder, "meta", "_journal.json");
2160
+ try {
2161
+ return JSON.parse(readFileSync(journalFile, "utf8")).entries?.length ?? 0;
2162
+ } catch {
2163
+ return 0;
2164
+ }
2165
+ }
2166
+ function quickCheck(sqlite) {
2167
+ return sqlite.pragma("quick_check", { simple: true }) === "ok";
2168
+ }
2169
+ //#endregion
2170
+ //#region src/bootstrap/config.ts
2171
+ var ConfigError = class extends Error {
2172
+ issues;
2173
+ constructor(message, issues = []) {
2174
+ super(message);
2175
+ this.name = "ConfigError";
2176
+ this.issues = issues;
2177
+ }
2178
+ };
2179
+ function configFilePath(dataDir) {
2180
+ return path.join(dataDir, "config.json");
2181
+ }
2182
+ function formatIssues(issues) {
2183
+ return issues.map((issue) => {
2184
+ return `${issue.path.length > 0 ? issue.path.map(String).join(".") : "(root)"}: ${issue.message}`;
2185
+ });
2186
+ }
2187
+ function applyEnvOverrides(config, env) {
2188
+ const host = env.LARNESS_HOST?.trim();
2189
+ if (host) config.server.host = host;
2190
+ const rawPort = env.LARNESS_PORT?.trim();
2191
+ if (rawPort) {
2192
+ const port = Number(rawPort);
2193
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new ConfigError(`LARNESS_PORT must be an integer between 1 and 65535, received "${rawPort}"`);
2194
+ config.server.port = port;
2195
+ }
2196
+ if (env.LARNESS_PUBLIC_URL !== void 0) {
2197
+ const value = env.LARNESS_PUBLIC_URL.trim();
2198
+ if (value === "") config.server.publicUrl = null;
2199
+ else {
2200
+ const parsed = OriginUrlSchema.safeParse(value);
2201
+ if (!parsed.success) throw new ConfigError(`LARNESS_PUBLIC_URL must be an http(s) origin, received "${value}"`);
2202
+ config.server.publicUrl = new URL(parsed.data).origin;
2203
+ }
2204
+ }
2205
+ const rawLevel = env.LARNESS_LOG_LEVEL?.trim();
2206
+ if (rawLevel) {
2207
+ const parsed = LogLevelSchema.safeParse(rawLevel);
2208
+ if (!parsed.success) throw new ConfigError(`LARNESS_LOG_LEVEL must be one of: ${LogLevelSchema.options.join(", ")}`);
2209
+ config.logging.level = parsed.data;
2210
+ }
2211
+ }
2212
+ async function loadConfig(options) {
2213
+ const env = options.env ?? process.env;
2214
+ const file = configFilePath(options.dataDir);
2215
+ let raw;
2216
+ let source = "defaults";
2217
+ let text = null;
2218
+ try {
2219
+ text = await readFile(file, "utf8");
2220
+ } catch (error) {
2221
+ if (error.code !== "ENOENT") throw new ConfigError(`cannot read config.json at ${file}: ${error.code}`);
2222
+ }
2223
+ if (text !== null) {
2224
+ source = "file";
2225
+ try {
2226
+ raw = JSON.parse(text);
2227
+ } catch {
2228
+ throw new ConfigError(`config.json is not valid JSON: ${file}`);
2229
+ }
2230
+ } else raw = structuredClone(DEFAULT_APP_CONFIG);
2231
+ return {
2232
+ ...resolveConfig(raw, env),
2233
+ source,
2234
+ path: file
2235
+ };
2236
+ }
2237
+ function resolveConfig(raw, env) {
2238
+ const parsed = AppConfigSchema.safeParse(raw);
2239
+ if (!parsed.success) {
2240
+ const issues = formatIssues(parsed.error.issues);
2241
+ throw new ConfigError(`invalid config.json: ${issues.join("; ")}`, issues);
2242
+ }
2243
+ const config = parsed.data;
2244
+ applyEnvOverrides(config, env);
2245
+ const validated = AppConfigSchema.safeParse(config);
2246
+ if (!validated.success) {
2247
+ const issues = formatIssues(validated.error.issues);
2248
+ throw new ConfigError(`invalid config after environment overrides: ${issues.join("; ")}`, issues);
2249
+ }
2250
+ const webAuthn = deriveWebAuthn(validated.data.server, validated.data.webauthn.rpName);
2251
+ return {
2252
+ config: {
2253
+ ...validated.data,
2254
+ webauthn: {
2255
+ rpId: webAuthn.rpId,
2256
+ rpName: webAuthn.rpName,
2257
+ origin: webAuthn.origin
2258
+ }
2259
+ },
2260
+ webAuthn
2261
+ };
2262
+ }
2263
+ //#endregion
2264
+ //#region src/init/recovery.ts
2265
+ const InitPendingSchema = z.strictObject({
2266
+ version: z.literal(1),
2267
+ config: AppConfigSchema
2268
+ });
2269
+ function recoverInitialization(db, dataDir) {
2270
+ const raw = getMeta(db, "init_pending");
2271
+ if (raw === null) return false;
2272
+ let pending;
2273
+ try {
2274
+ pending = InitPendingSchema.parse(JSON.parse(raw));
2275
+ } catch {
2276
+ throw new Error("invalid initialization recovery record; restore the database backup");
2277
+ }
2278
+ const target = configFilePath(dataDir);
2279
+ const temporary = `${target}.tmp-${randomUUID()}`;
2280
+ try {
2281
+ const fd = openSync(temporary, "wx", 384);
2282
+ try {
2283
+ writeFileSync(fd, `${JSON.stringify(pending.config, null, 2)}\n`);
2284
+ fsyncSync(fd);
2285
+ } finally {
2286
+ closeSync(fd);
2287
+ }
2288
+ renameSync(temporary, target);
2289
+ if (process.platform !== "win32") {
2290
+ const directory = openSync(dataDir, "r");
2291
+ try {
2292
+ fsyncSync(directory);
2293
+ } finally {
2294
+ closeSync(directory);
2295
+ }
2296
+ }
2297
+ deleteMeta(db, "init_pending");
2298
+ return true;
2299
+ } finally {
2300
+ rmSync(temporary, { force: true });
2301
+ }
2302
+ }
2303
+ //#endregion
2304
+ //#region src/db/inspect.ts
2305
+ function hasAuthSettings(sqlite) {
2306
+ try {
2307
+ const row = sqlite.prepare("SELECT count(*) AS count FROM auth_settings").get();
2308
+ const pending = sqlite.prepare("SELECT value FROM app_meta WHERE key = ?").get("init_pending");
2309
+ return (row?.count ?? 0) > 0 && pending === void 0;
2310
+ } catch {
2311
+ return false;
2312
+ }
2313
+ }
2314
+ function inspectDatabase(file) {
2315
+ if (!existsSync(file)) return null;
2316
+ let sqlite = null;
2317
+ try {
2318
+ sqlite = new BetterSqlite3(file, {
2319
+ readonly: true,
2320
+ fileMustExist: true
2321
+ });
2322
+ const schemaVersion = appliedMigrationCount(sqlite);
2323
+ const ok = quickCheck(sqlite);
2324
+ return {
2325
+ ok,
2326
+ schemaVersion,
2327
+ initialized: hasAuthSettings(sqlite),
2328
+ detail: ok ? "quick_check ok" : "quick_check failed"
2329
+ };
2330
+ } catch (error) {
2331
+ return {
2332
+ ok: false,
2333
+ schemaVersion: 0,
2334
+ initialized: false,
2335
+ detail: error instanceof Error ? error.message : String(error)
2336
+ };
2337
+ } finally {
2338
+ sqlite?.close();
2339
+ }
2340
+ }
2341
+ function inspectPendingInitialization(file) {
2342
+ if (!existsSync(file)) return null;
2343
+ const sqlite = new BetterSqlite3(file, {
2344
+ readonly: true,
2345
+ fileMustExist: true
2346
+ });
2347
+ try {
2348
+ if (!sqlite.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'app_meta'").get()) return null;
2349
+ const row = sqlite.prepare("SELECT value FROM app_meta WHERE key = ?").get("init_pending");
2350
+ if (!row) return null;
2351
+ try {
2352
+ return InitPendingSchema.parse(JSON.parse(row.value)).config;
2353
+ } catch {
2354
+ throw new Error("invalid initialization recovery record; restore the database backup");
2355
+ }
2356
+ } finally {
2357
+ sqlite.close();
2358
+ }
2359
+ }
2360
+ //#endregion
2361
+ //#region src/platform/paths.ts
2362
+ const DATA_SUBDIRS = [
2363
+ "logs",
2364
+ "backups",
2365
+ "tmp",
2366
+ "sessions",
2367
+ "artifacts",
2368
+ "secrets",
2369
+ "ipc"
2370
+ ];
2371
+ var DataDirError = class extends Error {
2372
+ constructor(message) {
2373
+ super(message);
2374
+ this.name = "DataDirError";
2375
+ }
2376
+ };
2377
+ function defaultDataDir() {
2378
+ return envPaths("larness", { suffix: "" }).data;
2379
+ }
2380
+ function resolveDataDir(env = process.env) {
2381
+ const override = env.LARNESS_DATA_DIR?.trim();
2382
+ return override ? path.resolve(override) : defaultDataDir();
2383
+ }
2384
+ async function ensureDir(dir) {
2385
+ try {
2386
+ const info = await stat(dir);
2387
+ if (!info.isDirectory()) throw new DataDirError(`data directory path is not a directory: ${dir}`);
2388
+ let hardened = false;
2389
+ if (process.platform !== "win32" && (info.mode & 63) !== 0) try {
2390
+ await chmod(dir, 448);
2391
+ hardened = true;
2392
+ } catch (error) {
2393
+ throw new DataDirError(`cannot restrict permissions on ${dir}: ${error.code}`);
2394
+ }
2395
+ return {
2396
+ created: false,
2397
+ hardened
2398
+ };
2399
+ } catch (error) {
2400
+ if (error instanceof DataDirError) throw error;
2401
+ if (error.code !== "ENOENT") throw new DataDirError(`cannot access data directory ${dir}: ${error.code}`);
2402
+ try {
2403
+ await mkdir(dir, {
2404
+ recursive: true,
2405
+ mode: 448
2406
+ });
2407
+ } catch (mkdirError) {
2408
+ throw new DataDirError(`cannot create data directory ${dir}: ${mkdirError.code}`);
2409
+ }
2410
+ return {
2411
+ created: true,
2412
+ hardened: false
2413
+ };
2414
+ }
2415
+ }
2416
+ async function ensureDataDirs(dataDir) {
2417
+ const root = await ensureDir(dataDir);
2418
+ let hardened = root.hardened;
2419
+ for (const name of DATA_SUBDIRS) {
2420
+ const result = await ensureDir(path.join(dataDir, name));
2421
+ hardened = hardened || result.hardened;
2422
+ }
2423
+ try {
2424
+ await access(dataDir, constants.W_OK);
2425
+ } catch {
2426
+ throw new DataDirError(`data directory is not writable: ${dataDir}`);
2427
+ }
2428
+ return {
2429
+ created: root.created,
2430
+ hardened
2431
+ };
2432
+ }
2433
+ //#endregion
2434
+ export { terminalLeases as $, DEPLOYMENT_ARTIFACT_MAX_PATH as $t, deploymentTargets as A, FilePathSchema as An, TerminalOutputChunkSchema as At, resourceLocks as B, GitActionDecisionSchema as Bt, commandExecutions as C, CommandIdSchema as Cn, StopProjectTerminalParamsSchema as Ct, deploymentAuthorizations as D, CommandStatusPayloadSchema as Dn, TerminalIdSchema as Dt, deploymentArtifacts as E, CommandParamsSchema as En, TerminalDevSchema as Et, modelProfiles as F, FileScopeSchema as Fn, TerminalSubscriptionSchema as Ft, schema_exports as G, WORKSPACE_JOBS_CHANGED as Gt, resourceStreams as H, GitBranchesQuerySchema as Ht, modelVisibility as I, MAX_EDITABLE_FILE_BYTES as In, TerminalTakeoverSchema as It, serviceOpsDeployments as J, ERROR_HTTP_STATUS as Jt, secrets as K, WORKSPACE_SESSIONS_CHANGED as Kt, projects as L, PlanParamsSchema as Lt, fileVersions as M, FileResultTargetSchema as Mn, TerminalRenameSchema as Mt, modelCatalogCache as N, FileSaveResultSchema as Nn, TerminalResizeSchema as Nt, deploymentBuilds as O, CommandSubscriptionSchema as On, TerminalInputSchema as Ot, modelDefaults as P, FileSaveSchema as Pn, TerminalResultTargetSchema as Pt, sessions as Q, DEPLOYMENT_ARTIFACT_MAX_FILES as Qt, resourceActions as R, ScheduledJobInputSchema as Rt, browserSessions as S, CommandCancelSchema as Sn, SendTerminalInputParamsSchema as St, deploymentApprovals as T, CommandOutputQuerySchema as Tn, TerminalCreateSchema as Tt, scheduledJobRuns as U, GitDiffQuerySchema as Ut, resourceOperations as V, GitActionSchema as Vt, scheduledJobs as W, GitLogQuerySchema as Wt, services as X, DEPLOYMENT_APPROVAL_TTL_MS as Xt, serviceOpsServices as Y, DEFAULT_PROJECT_ID as Yt, sessionContextSummaries as Z, DEPLOYMENT_ARTIFACT_MAX_BYTES as Zt, setMeta as _, DEFAULT_APP_CONFIG as _n, AcquireTerminalControlParamsSchema as _t, inspectPendingInitialization as a, DeploymentPlanDocumentSchema as an, newId as at, auditLogs as b, COMMAND_OUTPUT_RETENTION_MS as bn, ReadTerminalOutputParamsSchema as bt, loadConfig as c, DeploymentTargetNameSchema as cn, FileStreamIdSchema as ct, expectedMigrationCount as d, ServiceActionScopeSchema as dn, ResourceEventsQuerySchema as dt, DEPLOYMENT_BUILD_LOG_MAX_BYTES as en, terminals as et, findServerRoot as f, ServiceControlInputSchema as fn, ServiceEventPayloadSchema as ft, getMeta as g, AppConfigSchema as gn, ServiceSubscriptionSchema as gt, ensureInstanceId as h, hasControlCharacters as hn, ServiceStatusSchema as ht, inspectDatabase as i, DeploymentAuthorizationScopeSchema as in, webauthnCredentials as it, deviceRequests as j, FileReadQuerySchema as jn, TerminalPayloadSchema as jt, deploymentPlans as k, FileListQuerySchema as kn, TerminalLeaseSchema as kt, resolveConfig as l, DeploymentTargetRefSchema as ln, FileSubscriptionSchema as lt, SERVER_VERSION as m, ServiceOpsSubscriptionSchema as mn, ServiceRegisterInputSchema as mt, ensureDataDirs as n, DeploymentArtifactManifestSchema as nn, turns as nt, recoverInitialization as o, DeploymentSourceSchema as on, FileChangedPayloadSchema as ot, runMigrations as p, ServiceOpsEventPayloadSchema as pn, ServiceIdSchema as pt, serviceActionAuthorizations as q, ERROR_CODES as qt, resolveDataDir as r, DeploymentAuthorizationContextSchema as rn, webauthnChallenges as rt, configFilePath as s, DeploymentSpecSchema as sn, FileResyncPayloadSchema as st, DATA_SUBDIRS as t, DEPLOYMENT_PLAN_TTL_MS as tn, trustedDevices as tt, appliedMigrationCount as u, ServiceActionAuthorizationDtoSchema as un, RESOURCE_EVENT_RETENTION_MS as ut, agentEvents as v, OriginUrlSchema as vn, InterruptTerminalParamsSchema as vt, credentialProfiles as w, CommandOutputChunkSchema as wn, TERMINAL_LEASE_TTL_MS as wt, authSettings as x, COMMAND_RETENTION_MS as xn, ReleaseTerminalControlParamsSchema as xt, approvals as y, deriveWebAuthn as yn, PreviewResultTargetSchema as yt, resourceEvents as z, ScheduledJobPatchSchema as zt };