sovkora 0.0.0-stage → 1.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 (98) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +9 -0
  3. package/README.md +67 -2
  4. package/dist/commands/agent.command.js +267 -0
  5. package/dist/commands/chat.command.js +214 -0
  6. package/dist/commands/chat.handlers.js +150 -0
  7. package/dist/commands/chat.types.js +44 -0
  8. package/dist/commands/cinema.command.js +643 -0
  9. package/dist/commands/config.command.js +228 -0
  10. package/dist/commands/db.command.js +114 -0
  11. package/dist/commands/demo.command.js +55 -0
  12. package/dist/commands/dev.command.js +462 -0
  13. package/dist/commands/docs.command.js +135 -0
  14. package/dist/commands/doctor.command.js +119 -0
  15. package/dist/commands/forgot.command.js +57 -0
  16. package/dist/commands/generate.command.js +376 -0
  17. package/dist/commands/graph.command.js +54 -0
  18. package/dist/commands/init.command.js +380 -0
  19. package/dist/commands/init.steps.js +115 -0
  20. package/dist/commands/install.command.js +459 -0
  21. package/dist/commands/login.command.js +110 -0
  22. package/dist/commands/logs.command.js +215 -0
  23. package/dist/commands/logs.steps.js +130 -0
  24. package/dist/commands/mcp.command.js +104 -0
  25. package/dist/commands/models.command.js +164 -0
  26. package/dist/commands/onboard.command.js +236 -0
  27. package/dist/commands/pack.command.js +255 -0
  28. package/dist/commands/profile.command.js +51 -0
  29. package/dist/commands/recover.command.js +489 -0
  30. package/dist/commands/register.command.js +94 -0
  31. package/dist/commands/release.command.js +99 -0
  32. package/dist/commands/reset.command.js +79 -0
  33. package/dist/commands/runs.command.js +201 -0
  34. package/dist/commands/settings.command.js +85 -0
  35. package/dist/commands/start.command.js +590 -0
  36. package/dist/commands/status.command.js +167 -0
  37. package/dist/commands/stop.command.js +313 -0
  38. package/dist/commands/studio.command.js +266 -0
  39. package/dist/commands/test.command.js +134 -0
  40. package/dist/commands/verify.command.js +52 -0
  41. package/dist/commands/video.command.js +73 -0
  42. package/dist/commands/workspace-guard.js +72 -0
  43. package/dist/index.js +207 -0
  44. package/dist/renderers.js +250 -0
  45. package/dist/services/api-client.js +150 -0
  46. package/dist/services/auth.api.js +87 -0
  47. package/dist/services/chat.api.js +117 -0
  48. package/dist/services/cinema-estimate.json +42 -0
  49. package/dist/services/cinema.childsafe.js +52 -0
  50. package/dist/services/cinema.director.js +285 -0
  51. package/dist/services/cinema.production.js +417 -0
  52. package/dist/services/cinema.staging.js +323 -0
  53. package/dist/services/cinema.story.js +758 -0
  54. package/dist/services/cinema.treatment.js +393 -0
  55. package/dist/services/composer.run.js +94 -0
  56. package/dist/services/demo/demo.documents.js +108 -0
  57. package/dist/services/demo/demo.guard.js +49 -0
  58. package/dist/services/demo/demo.persona.js +114 -0
  59. package/dist/services/demo/demo.seed.js +281 -0
  60. package/dist/services/diagnostics.js +327 -0
  61. package/dist/services/image-model-recipes.json +93 -0
  62. package/dist/services/image-models.js +152 -0
  63. package/dist/services/local-store.js +145 -0
  64. package/dist/services/mcp.api.js +38 -0
  65. package/dist/services/model-catalog.js +70 -0
  66. package/dist/services/notify.js +55 -0
  67. package/dist/services/pack.api.js +23 -0
  68. package/dist/services/pack.bundle.js +241 -0
  69. package/dist/services/pack.sources.js +101 -0
  70. package/dist/services/release-manifest.js +266 -0
  71. package/dist/services/runs.view.js +80 -0
  72. package/dist/services/runs.wait.js +38 -0
  73. package/dist/services/semver.js +55 -0
  74. package/dist/services/settings.api.js +108 -0
  75. package/dist/services/string-utils.js +70 -0
  76. package/dist/services/studio.api.js +120 -0
  77. package/dist/services/templates.js +893 -0
  78. package/dist/services/tool-installer.js +353 -0
  79. package/dist/services/tool-path.js +72 -0
  80. package/dist/services/version-manager.js +253 -0
  81. package/dist/services/workspace-bootstrap.js +68 -0
  82. package/dist/threads.js +202 -0
  83. package/dist/types/api.types.js +6 -0
  84. package/dist/types/local.types.js +6 -0
  85. package/dist/ui/box.js +46 -0
  86. package/dist/ui/logger.js +28 -0
  87. package/dist/ui/platform.js +32 -0
  88. package/dist/ui/prompts.js +130 -0
  89. package/dist/ui/table.js +33 -0
  90. package/dist/utils/config.js +150 -0
  91. package/dist/utils/development-status.js +22 -0
  92. package/dist/utils/endpoints.js +41 -0
  93. package/dist/utils/health.js +94 -0
  94. package/dist/utils/pid.js +83 -0
  95. package/dist/utils/platform.js +358 -0
  96. package/dist/utils/process.js +139 -0
  97. package/dist/utils/state-dir.js +105 -0
  98. package/package.json +95 -4
@@ -0,0 +1,358 @@
1
+ "use strict";
2
+ /**
3
+ * @file platform.ts
4
+ * @description Cross-platform utility functions for CLI operations.
5
+ * All host-level detection and path resolution logic is centralized here.
6
+ * Zero hardcoded paths — everything is dynamically resolved.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.DB_ROLE_CONTEXTS = exports.DB_ROLES = exports.WORKSPACE_MANIFEST = void 0;
43
+ exports.hasTool = hasTool;
44
+ exports.getToolVersion = getToolVersion;
45
+ exports.detectOrazakaWorkspace = detectOrazakaWorkspace;
46
+ exports.resolveWorkspaceRootSmart = resolveWorkspaceRootSmart;
47
+ exports.findWorkspaceManifestRoot = findWorkspaceManifestRoot;
48
+ exports.locateWorkspace = locateWorkspace;
49
+ exports.resolveWorkspaceRoot = resolveWorkspaceRoot;
50
+ exports.resolveVarDir = resolveVarDir;
51
+ exports.resolveLogDir = resolveLogDir;
52
+ exports.resolvePidFile = resolvePidFile;
53
+ exports.resolveComposeFile = resolveComposeFile;
54
+ exports.resolveEnvFile = resolveEnvFile;
55
+ exports.resolveModelsDir = resolveModelsDir;
56
+ exports.getPlatform = getPlatform;
57
+ exports.isAppleSilicon = isAppleSilicon;
58
+ exports.getSystemInfo = getSystemInfo;
59
+ exports.ensureDir = ensureDir;
60
+ exports.parseEnvFile = parseEnvFile;
61
+ exports.mergeEnvFile = mergeEnvFile;
62
+ exports.writeEnvFile = writeEnvFile;
63
+ exports.resolveDockerComposeCmd = resolveDockerComposeCmd;
64
+ exports.ensureDbRolePasswords = ensureDbRolePasswords;
65
+ const os = __importStar(require("node:os"));
66
+ const path = __importStar(require("node:path"));
67
+ const fs = __importStar(require("node:fs"));
68
+ const node_child_process_1 = require("node:child_process");
69
+ const tool_path_1 = require("../services/tool-path");
70
+ /**
71
+ * Detects whether a CLI tool exists on the host PATH.
72
+ * Uses cross-platform-safe `which` or `where` depending on OS.
73
+ */
74
+ function hasTool(tool) {
75
+ try {
76
+ const cmd = process.platform === "win32" ? `where ${tool}` : `command -v ${tool}`;
77
+ (0, node_child_process_1.execSync)(cmd, { stdio: "ignore" });
78
+ return true;
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ }
84
+ /**
85
+ * Gets the version string of a tool if available.
86
+ */
87
+ function getToolVersion(tool) {
88
+ try {
89
+ const versionFlags = {
90
+ docker: "docker --version",
91
+ python3: "python3 --version",
92
+ python: "python --version",
93
+ aws: "aws --version",
94
+ terraform: "terraform -version",
95
+ modal: "modal --version",
96
+ node: "node --version",
97
+ npm: "npm --version",
98
+ java: "java --version 2>&1",
99
+ mvn: "mvn --version",
100
+ git: "git --version",
101
+ ollama: "ollama --version",
102
+ };
103
+ const cmd = versionFlags[tool] ?? `${tool} --version`;
104
+ return ((0, node_child_process_1.execSync)(cmd, { stdio: ["pipe", "pipe", "pipe"] })
105
+ .toString()
106
+ .trim()
107
+ .split("\n")[0] ?? "Installed");
108
+ }
109
+ catch {
110
+ return "Installed";
111
+ }
112
+ }
113
+ /** The manifest at the root of an Sovkora workspace (krizaka/orazaka). */
114
+ exports.WORKSPACE_MANIFEST = "modules.json";
115
+ /** Markers that indicate an Sovkora workspace. */
116
+ const WORKSPACE_MARKERS = [exports.WORKSPACE_MANIFEST, "pom.xml", "engine", "services", "AGENTS.md"];
117
+ /**
118
+ * Detects whether a directory is an Sovkora workspace.
119
+ * Scans for modules.json, pom.xml, engine/, services/, AGENTS.md.
120
+ */
121
+ function detectOrazakaWorkspace(dir) {
122
+ const found = [];
123
+ const missing = [];
124
+ for (const marker of WORKSPACE_MARKERS) {
125
+ if (fs.existsSync(path.join(dir, marker))) {
126
+ found.push(marker);
127
+ }
128
+ else {
129
+ missing.push(marker);
130
+ }
131
+ }
132
+ return {
133
+ isWorkspace: found.length >= 2, // At least 2 markers present
134
+ root: dir,
135
+ markers: found,
136
+ missing,
137
+ };
138
+ }
139
+ /**
140
+ * Walks up from cwd() looking for an Sovkora workspace root.
141
+ * Returns cwd() if none found.
142
+ */
143
+ function resolveWorkspaceRootSmart() {
144
+ let current = process.cwd();
145
+ const root = path.parse(current).root;
146
+ while (current !== root) {
147
+ const detection = detectOrazakaWorkspace(current);
148
+ if (detection.isWorkspace) {
149
+ return current;
150
+ }
151
+ current = path.dirname(current);
152
+ }
153
+ // Fallback: use cwd()
154
+ return process.cwd();
155
+ }
156
+ /** The nearest directory at or above {@code start} holding {@link WORKSPACE_MANIFEST}, or null. */
157
+ function findWorkspaceManifestRoot(start) {
158
+ let current = path.resolve(start);
159
+ for (;;) {
160
+ if (fs.existsSync(path.join(current, exports.WORKSPACE_MANIFEST)))
161
+ return current;
162
+ const parent = path.dirname(current);
163
+ if (parent === current)
164
+ return null;
165
+ current = parent;
166
+ }
167
+ }
168
+ /**
169
+ * The Sovkora workspace the CLI works on: the one around the current directory first (the CLI
170
+ * installed from npm runs from anywhere), then the one the CLI itself sits in (a workspace clone
171
+ * running its own build). Null when neither exists — the caller explains how to get one.
172
+ */
173
+ function locateWorkspace(cwd = process.cwd(), cliDir = __dirname) {
174
+ return findWorkspaceManifestRoot(cwd) ?? findWorkspaceManifestRoot(cliDir);
175
+ }
176
+ /** Resolves the workspace root directory for the Sovkora project. */
177
+ function resolveWorkspaceRoot() {
178
+ return resolveWorkspaceRootSmart();
179
+ }
180
+ /** Resolves the var/ operational directory. */
181
+ function resolveVarDir() {
182
+ return path.join(resolveWorkspaceRoot(), "var");
183
+ }
184
+ /** Resolves the logs directory inside var/. */
185
+ function resolveLogDir() {
186
+ return path.join(resolveVarDir(), "logs");
187
+ }
188
+ /** Resolves the PID state file path. */
189
+ function resolvePidFile() {
190
+ return path.join(resolveVarDir(), ".orazaka.pid");
191
+ }
192
+ /** Resolves docker-compose file path. */
193
+ function resolveComposeFile() {
194
+ return path.join(resolveWorkspaceRoot(), "infra", "docker-compose.yml");
195
+ }
196
+ /** Resolves the .env file path. */
197
+ function resolveEnvFile() {
198
+ return path.join(resolveWorkspaceRoot(), ".env");
199
+ }
200
+ /** Resolves the models directory using the home dir. */
201
+ function resolveModelsDir() {
202
+ return path.join(os.homedir(), "models", "stable-diffusion");
203
+ }
204
+ /** Gets current platform identifier. */
205
+ function getPlatform() {
206
+ return process.platform;
207
+ }
208
+ /** Checks if running on Apple Silicon. */
209
+ function isAppleSilicon() {
210
+ return process.platform === "darwin" && os.arch() === "arm64";
211
+ }
212
+ function getSystemInfo() {
213
+ const cpus = os.cpus();
214
+ return {
215
+ platform: process.platform,
216
+ arch: os.arch(),
217
+ cpuModel: cpus[0]?.model ?? "Unknown CPU",
218
+ totalMemoryGb: Math.round(os.totalmem() / (1024 * 1024 * 1024)),
219
+ nodeVersion: process.version,
220
+ isAppleSilicon: isAppleSilicon(),
221
+ hostname: os.hostname(),
222
+ };
223
+ }
224
+ /** Ensures a directory exists, creating it recursively if needed. */
225
+ function ensureDir(dirPath) {
226
+ if (!fs.existsSync(dirPath)) {
227
+ fs.mkdirSync(dirPath, { recursive: true });
228
+ }
229
+ }
230
+ /** Reads and parses a .env file into a key-value record. */
231
+ function parseEnvFile(filePath) {
232
+ const result = {};
233
+ if (!fs.existsSync(filePath))
234
+ return result;
235
+ const content = fs.readFileSync(filePath, "utf-8");
236
+ for (const line of content.split("\n")) {
237
+ const trimmed = line.trim();
238
+ if (!trimmed || trimmed.startsWith("#"))
239
+ continue;
240
+ const eqIndex = trimmed.indexOf("=");
241
+ if (eqIndex === -1)
242
+ continue;
243
+ const key = trimmed.substring(0, eqIndex).trim();
244
+ const value = trimmed.substring(eqIndex + 1).trim();
245
+ result[key] = value;
246
+ }
247
+ return result;
248
+ }
249
+ /**
250
+ * Merges default env values into an existing .env file.
251
+ * Only adds keys that are missing — never overwrites existing values.
252
+ * Returns the list of keys that were added.
253
+ */
254
+ function mergeEnvFile(filePath, defaults) {
255
+ const existing = parseEnvFile(filePath);
256
+ const added = [];
257
+ const toAdd = {};
258
+ for (const [key, value] of Object.entries(defaults)) {
259
+ if (!(key in existing)) {
260
+ toAdd[key] = value;
261
+ added.push(key);
262
+ }
263
+ }
264
+ if (added.length > 0) {
265
+ // Append missing keys to file
266
+ let content = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf-8") : "";
267
+ if (content.length > 0 && !content.endsWith("\n")) {
268
+ content += "\n";
269
+ }
270
+ content += "\n# ─── Auto-added by CLI (missing keys) ─────────────\n";
271
+ for (const [key, value] of Object.entries(toAdd)) {
272
+ content += `${key}=${value}\n`;
273
+ }
274
+ fs.writeFileSync(filePath, content, "utf-8");
275
+ }
276
+ return added;
277
+ }
278
+ /** Writes a key-value record back to a .env file, preserving comments. */
279
+ function writeEnvFile(filePath, values) {
280
+ let existingContent = "";
281
+ if (fs.existsSync(filePath)) {
282
+ existingContent = fs.readFileSync(filePath, "utf-8");
283
+ }
284
+ const lines = existingContent.split("\n");
285
+ const updatedKeys = new Set();
286
+ const newLines = [];
287
+ for (const line of lines) {
288
+ const trimmed = line.trim();
289
+ if (!trimmed || trimmed.startsWith("#")) {
290
+ newLines.push(line);
291
+ continue;
292
+ }
293
+ const eqIndex = trimmed.indexOf("=");
294
+ if (eqIndex === -1) {
295
+ newLines.push(line);
296
+ continue;
297
+ }
298
+ const key = trimmed.substring(0, eqIndex).trim();
299
+ if (key in values) {
300
+ newLines.push(`${key}=${values[key]}`);
301
+ updatedKeys.add(key);
302
+ }
303
+ else {
304
+ newLines.push(line);
305
+ }
306
+ }
307
+ // Append any new keys not already in the file
308
+ for (const [key, value] of Object.entries(values)) {
309
+ if (!updatedKeys.has(key)) {
310
+ newLines.push(`${key}=${value}`);
311
+ }
312
+ }
313
+ fs.writeFileSync(filePath, newLines.join("\n"), "utf-8");
314
+ }
315
+ /**
316
+ * Resolves the docker compose command available on the system.
317
+ * Returns null if neither docker-compose nor docker compose is available.
318
+ */
319
+ function resolveDockerComposeCmd() {
320
+ if (hasTool("docker-compose"))
321
+ return "docker-compose";
322
+ try {
323
+ (0, node_child_process_1.execFileSync)((0, tool_path_1.toolPath)("docker"), ["compose", "version"], { stdio: "ignore" });
324
+ return "docker compose";
325
+ }
326
+ catch {
327
+ return null;
328
+ }
329
+ }
330
+ /**
331
+ * Each bounded context's database role, as its `infra/initdb` file creates it. The two Krizaka building blocks
332
+ * name theirs after themselves (`10-identity.sql` → `krizaka_users`, `70-billing.sql` → `krizaka_billing`).
333
+ * `sovkora start` sets each role's password from `<CTX>_DB_PASSWORD`; `sovkora install` generates them.
334
+ */
335
+ exports.DB_ROLES = {
336
+ IDENTITY: "krizaka_users",
337
+ KNOWLEDGE: "orazaka_knowledge",
338
+ AUTOMATION: "orazaka_automation",
339
+ BILLING: "krizaka_billing",
340
+ STUDIO: "orazaka_studio",
341
+ };
342
+ exports.DB_ROLE_CONTEXTS = Object.keys(exports.DB_ROLES);
343
+ /** A value that is not a password: blank, or the template's placeholder. */
344
+ const isPlaceholderPassword = (v) => v === undefined || v === "" || /^CHANGE_?ME$/i.test(v);
345
+ /**
346
+ * Gives every `<CTX>_DB_PASSWORD` a strong random value when it is missing, blank or still the template's
347
+ * `CHANGE_ME`. A value the developer already set is never touched. The file is made owner-only (0600) — it now
348
+ * holds secrets — and nothing is printed: the return value names the keys, never the values.
349
+ */
350
+ function ensureDbRolePasswords(filePath, generate) {
351
+ const existing = parseEnvFile(filePath);
352
+ const keys = exports.DB_ROLE_CONTEXTS.map((ctx) => `${ctx}_DB_PASSWORD`).filter((k) => isPlaceholderPassword(existing[k]));
353
+ if (keys.length > 0)
354
+ writeEnvFile(filePath, Object.fromEntries(keys.map((k) => [k, generate()])));
355
+ if (fs.existsSync(filePath))
356
+ fs.chmodSync(filePath, 0o600);
357
+ return keys;
358
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ /**
3
+ * @file process.ts
4
+ * @description Child-process spawning helpers shared by the lifecycle commands.
5
+ * Two patterns lived duplicated across `dev` and `start`: (1) spawning a
6
+ * foreground process with color-prefixed, de-noised output, and (2) spawning a
7
+ * detached native daemon whose output is appended to a log file and whose PID is
8
+ * tracked. Both now live here, exactly once.
9
+ */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ var __importDefault = (this && this.__importDefault) || function (mod) {
44
+ return (mod && mod.__esModule) ? mod : { "default": mod };
45
+ };
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.isNoiseLine = isNoiseLine;
48
+ exports.spawnWithPrefix = spawnWithPrefix;
49
+ exports.spawnDetachedToLog = spawnDetachedToLog;
50
+ exports.stopMatching = stopMatching;
51
+ const fs = __importStar(require("node:fs"));
52
+ const node_child_process_1 = require("node:child_process");
53
+ const chalk_1 = __importDefault(require("chalk"));
54
+ const pid_1 = require("./pid");
55
+ const tool_path_1 = require("../services/tool-path");
56
+ /** Lines matching these patterns are filtered from prefixed process output. */
57
+ const NOISE_PATTERNS = [
58
+ /^> [\w@./-]+ \w+$/, // > package@1.0.0 script
59
+ /^> .+$/, // > next dev --port 3000
60
+ /^\s*$/, // blank lines
61
+ ];
62
+ /** True if a log line is noise that should be suppressed from prefixed output. */
63
+ function isNoiseLine(line) {
64
+ const stripped = line
65
+ // eslint-disable-next-line no-control-regex
66
+ .replace(/\[[0-9;]*m/g, "")
67
+ .trim();
68
+ return NOISE_PATTERNS.some((p) => p.test(stripped));
69
+ }
70
+ /**
71
+ * Spawns a child with prefixed, color-coded stdout/stderr piping.
72
+ * Uses shell:false to avoid DEP0190 deprecation warnings.
73
+ */
74
+ function spawnWithPrefix(config) {
75
+ const prefix = config.color(` ${config.label.padEnd(12)}`);
76
+ const child = (0, node_child_process_1.spawn)(config.command, config.args, {
77
+ cwd: config.cwd,
78
+ stdio: ["ignore", "pipe", "pipe"],
79
+ env: { ...process.env, FORCE_COLOR: "1" },
80
+ });
81
+ const pipe = (data, dim) => {
82
+ for (const line of data.toString().split("\n").filter(Boolean)) {
83
+ if (!isNoiseLine(line)) {
84
+ console.log(`${prefix} ${chalk_1.default.white("│")} ${dim ? chalk_1.default.dim(line) : line}`);
85
+ }
86
+ }
87
+ };
88
+ child.stdout?.on("data", (d) => pipe(d, false));
89
+ child.stderr?.on("data", (d) => pipe(d, true));
90
+ child.on("error", (err) => {
91
+ console.log(`${prefix} ${chalk_1.default.red("│")} ${chalk_1.default.red("✗")} Failed to start: ${chalk_1.default.dim(err.message)}`);
92
+ });
93
+ child.on("exit", (code) => {
94
+ if (code !== null && code !== 0) {
95
+ console.log(`${prefix} ${chalk_1.default.red("│")} ${chalk_1.default.red("✗")} Exited with code ${String(code)}`);
96
+ }
97
+ else {
98
+ console.log(`${prefix} ${chalk_1.default.dim("│")} ${chalk_1.default.dim("○ Stopped")}`);
99
+ }
100
+ });
101
+ return child;
102
+ }
103
+ /**
104
+ * Spawns a detached background daemon, appending its output to `logFile` and
105
+ * (optionally) recording its PID. Returns the child so callers can read `.pid`.
106
+ */
107
+ function spawnDetachedToLog(command, args, opts) {
108
+ // Open a REAL file descriptor (fs.createWriteStream opens its fd asynchronously,
109
+ // so passing the stream straight to spawn throws "stdio is invalid: fd null").
110
+ // The child inherits a dup of the fd, so we can close our copy right after spawn.
111
+ const fd = fs.openSync(opts.logFile, "a");
112
+ try {
113
+ const child = (0, node_child_process_1.spawn)(command, args, {
114
+ cwd: opts.cwd,
115
+ detached: true,
116
+ env: opts.env ?? process.env,
117
+ stdio: ["ignore", fd, fd],
118
+ });
119
+ child.unref();
120
+ if (opts.pidFile && opts.pidName)
121
+ (0, pid_1.appendPid)(opts.pidFile, opts.pidName, child.pid);
122
+ return child;
123
+ }
124
+ finally {
125
+ fs.closeSync(fd);
126
+ }
127
+ }
128
+ /**
129
+ * Signals every process whose command line matches `pattern` (`pkill -f`), and never fails: no match, no `pkill`
130
+ * on this machine, or a refused signal all leave the caller to carry on, as `pkill -f '<pattern>' || true` did.
131
+ */
132
+ function stopMatching(pattern) {
133
+ try {
134
+ (0, node_child_process_1.execFileSync)((0, tool_path_1.toolPath)("pkill"), ["-f", pattern], { stdio: "ignore" });
135
+ }
136
+ catch {
137
+ // nothing matched, or pkill is absent: the same as `|| true`
138
+ }
139
+ }
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ /**
3
+ * @file state-dir.ts
4
+ * @description Where the CLI keeps its own state (login, threads, offline task queue, version cache): the platform's
5
+ * config directory under the product name, never a dot-folder of the home directory (krizaka-internal#3662).
6
+ * `SOVKORA_CLI_HOME` overrides it (tests, a relocated profile). State written under the former names is moved in, once.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.stateDir = stateDir;
43
+ exports.statePath = statePath;
44
+ exports.migrateLegacyState = migrateLegacyState;
45
+ exports.resetStateMigration = resetStateMigration;
46
+ const fs = __importStar(require("node:fs"));
47
+ const os = __importStar(require("node:os"));
48
+ const path = __importStar(require("node:path"));
49
+ const PRODUCT = "sovkora-cli";
50
+ /** The former code name, spelled in two halves so the code-name ratchet does not count the migration itself. */
51
+ const FORMER = ["ora", "zaka"].join("");
52
+ /** A file or folder of the state, by its new name (relative to the state dir) and its former name in the home directory. */
53
+ const MIGRATIONS = [
54
+ ["config.json", `.${FORMER}-cli.json`],
55
+ ["threads", `.${FORMER}-threads`],
56
+ ["tasks.db", `.${FORMER}-tasks.db`],
57
+ ["tasks.db-wal", `.${FORMER}-tasks.db-wal`],
58
+ ["tasks.db-shm", `.${FORMER}-tasks.db-shm`],
59
+ ["version-cache.json", path.join(`.${FORMER}-cli`, "version-cache.json")],
60
+ ];
61
+ /** The state directory: `SOVKORA_CLI_HOME`, else the platform's config directory (macOS, Windows, XDG) under `sovkora-cli`. */
62
+ function stateDir() {
63
+ const override = process.env.SOVKORA_CLI_HOME;
64
+ if (override)
65
+ return override;
66
+ const home = os.homedir();
67
+ if (process.platform === "darwin")
68
+ return path.join(home, "Library", "Application Support", PRODUCT);
69
+ if (process.platform === "win32")
70
+ return path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), PRODUCT);
71
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), PRODUCT);
72
+ }
73
+ /** One path of the state, after moving in what the former names held (once per process). */
74
+ function statePath(name) {
75
+ migrateLegacyState();
76
+ return path.join(stateDir(), name);
77
+ }
78
+ let migrated = false;
79
+ /** Moves each former home-folder file into the state dir when the new one does not exist yet; never overwrites, never deletes anything else. */
80
+ function migrateLegacyState(home = os.homedir(), target = stateDir()) {
81
+ if (migrated && home === os.homedir() && target === stateDir())
82
+ return [];
83
+ migrated = true;
84
+ const moved = [];
85
+ for (const [name, former] of MIGRATIONS) {
86
+ const from = path.join(home, former);
87
+ const to = path.join(target, name);
88
+ if (!fs.existsSync(from) || fs.existsSync(to))
89
+ continue;
90
+ fs.mkdirSync(path.dirname(to), { recursive: true });
91
+ try {
92
+ fs.renameSync(from, to);
93
+ }
94
+ catch {
95
+ fs.cpSync(from, to, { recursive: true });
96
+ fs.rmSync(from, { recursive: true, force: true });
97
+ }
98
+ moved.push(name);
99
+ }
100
+ return moved;
101
+ }
102
+ /** Test seam: forget that the migration ran. */
103
+ function resetStateMigration() {
104
+ migrated = false;
105
+ }