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,145 @@
1
+ "use strict";
2
+ /**
3
+ * @file local-store.ts
4
+ * @description Local persistent transaction engine for agent offline resilience.
5
+ * Coordinates SQLite-based storage of task payloads, execution states, and logs.
6
+ * Uses better-sqlite3 for cross-environment compatibility (Jest, ts-jest, Node 18+).
7
+ */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getDb = getDb;
13
+ exports.closeDb = closeDb;
14
+ exports.insertJob = insertJob;
15
+ exports.updateJobStatus = updateJobStatus;
16
+ exports.getUnsyncedJobs = getUnsyncedJobs;
17
+ exports.markJobSynced = markJobSynced;
18
+ const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
19
+ const state_dir_1 = require("../utils/state-dir");
20
+ let dbInstance = null;
21
+ /**
22
+ * Returns the active Database instance. Initializes it if not yet open.
23
+ */
24
+ function getDb() {
25
+ if (!dbInstance) {
26
+ dbInstance = new better_sqlite3_1.default((0, state_dir_1.statePath)("tasks.db"));
27
+ dbInstance.pragma("journal_mode = WAL");
28
+ dbInstance.exec(`
29
+ CREATE TABLE IF NOT EXISTS orazaka_local_jobs (
30
+ job_id TEXT PRIMARY KEY,
31
+ command_payload TEXT NOT NULL,
32
+ status TEXT NOT NULL,
33
+ retry_count INTEGER NOT NULL DEFAULT 0,
34
+ user_approval_state TEXT NOT NULL,
35
+ execution_logs TEXT NOT NULL DEFAULT '',
36
+ synced INTEGER NOT NULL DEFAULT 0
37
+ )
38
+ `);
39
+ }
40
+ return dbInstance;
41
+ }
42
+ /**
43
+ * Closes the local database connection. Useful for clean tests.
44
+ */
45
+ function closeDb() {
46
+ if (dbInstance) {
47
+ dbInstance.close();
48
+ dbInstance = null;
49
+ }
50
+ }
51
+ /**
52
+ * Inserts a new job instruction into the local SQLite store as PENDING.
53
+ * Atomic ingestion protocol: write before execute.
54
+ */
55
+ function insertJob(jobId, payload, approvalState = "APPROVED") {
56
+ const db = getDb();
57
+ const stmt = db.prepare(`
58
+ INSERT INTO orazaka_local_jobs (job_id, command_payload, status, retry_count, user_approval_state, execution_logs, synced)
59
+ VALUES (?, ?, 'PENDING', 0, ?, '', 0)
60
+ ON CONFLICT(job_id) DO UPDATE SET
61
+ command_payload = excluded.command_payload,
62
+ status = 'PENDING',
63
+ user_approval_state = excluded.user_approval_state,
64
+ synced = 0
65
+ `);
66
+ stmt.run(jobId, JSON.stringify(payload), approvalState);
67
+ }
68
+ /**
69
+ * Updates the execution status, logs, and optionally retry count/sync state.
70
+ */
71
+ function updateJobStatus(jobId, status, logs, retryCount, synced) {
72
+ const db = getDb();
73
+ if (retryCount !== undefined && synced !== undefined) {
74
+ const stmt = db.prepare(`
75
+ UPDATE orazaka_local_jobs
76
+ SET status = ?, execution_logs = ?, retry_count = ?, synced = ?
77
+ WHERE job_id = ?
78
+ `);
79
+ stmt.run(status, logs, retryCount, synced, jobId);
80
+ }
81
+ else if (retryCount !== undefined) {
82
+ const stmt = db.prepare(`
83
+ UPDATE orazaka_local_jobs
84
+ SET status = ?, execution_logs = ?, retry_count = ?
85
+ WHERE job_id = ?
86
+ `);
87
+ stmt.run(status, logs, retryCount, jobId);
88
+ }
89
+ else if (synced !== undefined) {
90
+ const stmt = db.prepare(`
91
+ UPDATE orazaka_local_jobs
92
+ SET status = ?, execution_logs = ?, synced = ?
93
+ WHERE job_id = ?
94
+ `);
95
+ stmt.run(status, logs, synced, jobId);
96
+ }
97
+ else {
98
+ const stmt = db.prepare(`
99
+ UPDATE orazaka_local_jobs
100
+ SET status = ?, execution_logs = ?
101
+ WHERE job_id = ?
102
+ `);
103
+ stmt.run(status, logs, jobId);
104
+ }
105
+ }
106
+ /**
107
+ * Retrieves all jobs currently in COMPLETED or FAILED state that have not been synced yet.
108
+ */
109
+ function getUnsyncedJobs() {
110
+ const db = getDb();
111
+ const stmt = db.prepare(`
112
+ SELECT
113
+ job_id AS jobId,
114
+ command_payload AS commandPayload,
115
+ status,
116
+ retry_count AS retryCount,
117
+ user_approval_state AS userApprovalState,
118
+ execution_logs AS executionLogs,
119
+ synced
120
+ FROM orazaka_local_jobs
121
+ WHERE synced = 0 AND (status = 'COMPLETED' OR status = 'FAILED')
122
+ `);
123
+ const rows = stmt.all();
124
+ return rows.map((raw) => ({
125
+ jobId: raw.jobId,
126
+ commandPayload: raw.commandPayload,
127
+ status: raw.status,
128
+ retryCount: Number(raw.retryCount),
129
+ userApprovalState: raw.userApprovalState,
130
+ executionLogs: raw.executionLogs,
131
+ synced: Number(raw.synced),
132
+ }));
133
+ }
134
+ /**
135
+ * Marks a job as synced with the Gateway.
136
+ */
137
+ function markJobSynced(jobId) {
138
+ const db = getDb();
139
+ const stmt = db.prepare(`
140
+ UPDATE orazaka_local_jobs
141
+ SET synced = 1
142
+ WHERE job_id = ?
143
+ `);
144
+ stmt.run(jobId);
145
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ /**
3
+ * @file mcp.api.ts
4
+ * @description Outbound adapter service for managing user-scoped dynamic MCP server configurations.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.McpApi = void 0;
8
+ const api_client_1 = require("./api-client");
9
+ exports.McpApi = {
10
+ /**
11
+ * Lists all active user-scoped MCP servers.
12
+ */
13
+ listUserServers: async () => {
14
+ return api_client_1.ApiClient.requestRest({
15
+ method: "GET",
16
+ path: "/api/v1/mcp/servers/user",
17
+ });
18
+ },
19
+ /**
20
+ * Registers a new user-scoped MCP server.
21
+ */
22
+ registerUserServer: async (server) => {
23
+ return api_client_1.ApiClient.requestRest({
24
+ method: "POST",
25
+ path: "/api/v1/mcp/servers/user",
26
+ body: server,
27
+ });
28
+ },
29
+ /**
30
+ * Deletes a user-scoped MCP server.
31
+ */
32
+ deleteUserServer: async (id) => {
33
+ await api_client_1.ApiClient.requestRest({
34
+ method: "DELETE",
35
+ path: `/api/v1/mcp/servers/user/${id}`,
36
+ });
37
+ },
38
+ };
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /**
3
+ * @file model-catalog.ts
4
+ * @description Reads and updates the model catalogue (`orazaka_models`) of the local database.
5
+ *
6
+ * The catalogue is data in the DB (AGENTS.md §4): which image model is the default is a row, not a
7
+ * flag of this CLI. These helpers go through `psql` inside the database container, like every
8
+ * local-only command of this CLI, and take only values they have already validated.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.queryCatalog = queryCatalog;
12
+ exports.defaultImageModel = defaultImageModel;
13
+ exports.setDefaultImageModel = setDefaultImageModel;
14
+ const node_child_process_1 = require("node:child_process");
15
+ const tool_path_1 = require("./tool-path");
16
+ const CONTAINER = "orazaka-db-vector";
17
+ /** Runs one statement against the jobs database and returns its rows, split on `|`. */
18
+ function queryCatalog(sql, env = process.env) {
19
+ const out = (0, node_child_process_1.execFileSync)((0, tool_path_1.toolPath)("docker"), [
20
+ "exec",
21
+ "-i",
22
+ CONTAINER,
23
+ "psql",
24
+ "-U",
25
+ env.DB_USERNAME ?? "orazaka_app",
26
+ "-d",
27
+ env.DB_NAME ?? "orazaka_db",
28
+ "-v",
29
+ "ON_ERROR_STOP=1",
30
+ "-t",
31
+ "-A",
32
+ "-F|",
33
+ "-c",
34
+ sql,
35
+ ], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
36
+ return out
37
+ .split("\n")
38
+ .map((line) => line.trim())
39
+ .filter(Boolean)
40
+ .map((line) => line.split("|"));
41
+ }
42
+ /** A model name the catalogue may hold: letters, digits, dots, dashes, slashes, colons. */
43
+ const MODEL_NAME = /^[A-Za-z0-9._:/-]{1,255}$/;
44
+ function requireModelName(name) {
45
+ if (!MODEL_NAME.test(name)) {
46
+ throw new Error(`Not a catalogue model name: ${name}`);
47
+ }
48
+ return name;
49
+ }
50
+ /** @returns the catalogue's default image model, or `undefined` when it names none. */
51
+ function defaultImageModel(env = process.env) {
52
+ const rows = queryCatalog("SELECT model_name FROM orazaka_models WHERE category = 'image' AND is_default ORDER BY model_name LIMIT 1", env);
53
+ return rows[0]?.[0];
54
+ }
55
+ /**
56
+ * Makes `name` the one default image model.
57
+ *
58
+ * @throws when the catalogue has no image row of that name — the row comes from the job service's
59
+ * seed (or its migration), never from this command
60
+ */
61
+ function setDefaultImageModel(name, env = process.env) {
62
+ const model = requireModelName(name);
63
+ const rows = queryCatalog(`UPDATE orazaka_models SET is_default = (model_name = '${model}') WHERE category = 'image' ` +
64
+ `AND EXISTS (SELECT 1 FROM orazaka_models WHERE category = 'image' AND model_name = '${model}') ` +
65
+ "RETURNING model_name", env);
66
+ if (rows.length === 0) {
67
+ throw new Error(`The catalogue has no image model '${model}'. Apply infra/migrations/2026-10-11-image-models.sql ` +
68
+ "from the workspace (or reset the database), then retry.");
69
+ }
70
+ }
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ /**
3
+ * @file notify.ts
4
+ * @description A desktop notification through the OS, with no dependency (orazaka-cli#90 `--notify`):
5
+ * Notification Center on macOS, `notify-send` on Linux; elsewhere the terminal bell.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.notifyCommand = notifyCommand;
9
+ exports.notify = notify;
10
+ exports.outcomeMessage = outcomeMessage;
11
+ const node_child_process_1 = require("node:child_process");
12
+ /** The command that shows `title`/`message` on this platform, or null when the OS has none. */
13
+ function notifyCommand(platform, title, message) {
14
+ if (platform === "darwin") {
15
+ // The text goes through argv, never into the script source, so a run name cannot inject AppleScript.
16
+ return {
17
+ file: "osascript",
18
+ args: [
19
+ "-e",
20
+ "on run argv",
21
+ "-e",
22
+ "display notification (item 2 of argv) with title (item 1 of argv)",
23
+ "-e",
24
+ "end run",
25
+ title,
26
+ message,
27
+ ],
28
+ };
29
+ }
30
+ if (platform === "linux")
31
+ return { file: "notify-send", args: [title, message] };
32
+ return null;
33
+ }
34
+ /** Shows the notification; never throws: a missing notifier must not fail a run's command. */
35
+ function notify(title, message, platform = process.platform) {
36
+ const command = notifyCommand(platform, title, message);
37
+ if (!command) {
38
+ process.stderr.write("\u0007");
39
+ return;
40
+ }
41
+ (0, node_child_process_1.execFile)(command.file, command.args, () => { });
42
+ }
43
+ /** The words of the notification for how a followed run ended. */
44
+ function outcomeMessage(outcome, name) {
45
+ switch (outcome) {
46
+ case "finished":
47
+ return `${name} finished`;
48
+ case "failed":
49
+ return `${name} failed`;
50
+ case "cancelled":
51
+ return `${name} was stopped`;
52
+ default:
53
+ return `${name} needs your approval`;
54
+ }
55
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * @file pack.api.ts
4
+ * @description Outbound adapter for the pack install surface (ADR-037, seam S4).
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.PackApi = void 0;
8
+ const api_client_1 = require("./api-client");
9
+ const BUNDLES = "/api/v1/studios/packs/bundles";
10
+ exports.PackApi = {
11
+ /** The semantic half of validation: do this platform's capabilities resolve for this bundle? */
12
+ validate: async (bundle) => api_client_1.ApiClient.requestRest({
13
+ method: "POST",
14
+ path: `${BUNDLES}/validation`,
15
+ body: bundle,
16
+ }),
17
+ /** Applies a bundle: capabilities, billing, catalogue — or none of them. */
18
+ install: async (bundle) => api_client_1.ApiClient.requestRest({
19
+ method: "POST",
20
+ path: BUNDLES,
21
+ body: bundle,
22
+ }),
23
+ };
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+ /**
3
+ * @file pack.bundle.ts
4
+ * @description Reads a pack bundle directory into the single value the installer applies (ADR-037 §3.2).
5
+ *
6
+ * A bundle on disk is a manifest plus the files it names; a bundle on the wire is one object.
7
+ * Resolving the two apart matters: an install that had to reach back to the filesystem could
8
+ * fail after writing half a catalogue, so every file is read and every reference resolved
9
+ * BEFORE anything is sent.
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.BundleError = void 0;
49
+ exports.validateManifest = validateManifest;
50
+ exports.loadBundle = loadBundle;
51
+ const fs = __importStar(require("node:fs"));
52
+ const path = __importStar(require("node:path"));
53
+ const yaml_1 = require("yaml");
54
+ const _2020_1 = __importDefault(require("ajv/dist/2020"));
55
+ const ajv_formats_1 = __importDefault(require("ajv-formats"));
56
+ const platform_1 = require("../utils/platform");
57
+ /** A structural problem with the manifest, phrased for a terminal rather than a stack trace. */
58
+ class BundleError extends Error {
59
+ }
60
+ exports.BundleError = BundleError;
61
+ const MANIFEST = "pack.yaml";
62
+ const I18N_DIR = "i18n";
63
+ /** Where the platform keeps the manifest contract it enforces. */
64
+ const PACKS_DIR = "packs";
65
+ const SCHEMA_FILE = "pack.schema.json";
66
+ /**
67
+ * The PLATFORM's manifest schema — never the bundle's.
68
+ *
69
+ * <p>This used to walk up from the bundle directory, and its own error message said what was
70
+ * wrong with that: "a bundle is validated against the schema of the platform installing it".
71
+ * Walking up from the bundle finds the schema of whatever tree the bundle happens to sit in — for
72
+ * a pack outside this repository, that is either nothing at all (phase G's acceptance criterion
73
+ * failed here first) or a schema the pack author shipped themselves, which would let a bundle
74
+ * validate against its own claim about what a manifest is.
75
+ *
76
+ * <p>Resolved from this CLI's own location instead: the tool doing the installing carries the
77
+ * contract it enforces. A CLI cloned in the workspace finds `orazaka-packs/pack.schema.json` by that
78
+ * walk. The CLI installed from npm sits outside any workspace, so it takes the schema of the workspace
79
+ * it operates on — the one holding `modules.json` around the current directory, i.e. the
80
+ * platform the pack is being installed into — never a file next to the bundle.
81
+ */
82
+ function locateSchema() {
83
+ let dir = __dirname;
84
+ for (let depth = 0; depth < 10; depth += 1) {
85
+ const candidate = path.join(dir, PACKS_DIR, SCHEMA_FILE);
86
+ if (fs.existsSync(candidate)) {
87
+ return candidate;
88
+ }
89
+ const parent = path.dirname(dir);
90
+ if (parent === dir) {
91
+ break;
92
+ }
93
+ dir = parent;
94
+ }
95
+ const workspace = (0, platform_1.locateWorkspace)();
96
+ const fromWorkspace = workspace ? path.join(workspace, PACKS_DIR, SCHEMA_FILE) : null;
97
+ if (fromWorkspace && fs.existsSync(fromWorkspace)) {
98
+ return fromWorkspace;
99
+ }
100
+ throw new BundleError(`This CLI cannot find its own ${PACKS_DIR}/${SCHEMA_FILE}. A bundle is validated against the ` +
101
+ "schema of the platform installing it, so a platform that cannot produce its schema must " +
102
+ "refuse rather than trust the bundle's.");
103
+ }
104
+ /** Turns ajv's error objects into lines an operator can act on. */
105
+ function describe(errors) {
106
+ return (errors ?? []).map((error) => {
107
+ const where = error.instancePath === "" ? "(root)" : error.instancePath;
108
+ return `${where} ${error.message ?? "is invalid"}`;
109
+ });
110
+ }
111
+ /** Validates the manifest's SHAPE against pack.schema.json. Semantics are the service's half. */
112
+ function validateManifest(bundleDir, manifest) {
113
+ const schema = JSON.parse(fs.readFileSync(locateSchema(), "utf-8"));
114
+ const ajv = new _2020_1.default({ allErrors: true, strict: false });
115
+ (0, ajv_formats_1.default)(ajv);
116
+ const validate = ajv.compile(schema);
117
+ return validate(manifest) ? [] : describe(validate.errors);
118
+ }
119
+ /** Reads one blueprint file, keeping its three schemas as the raw JSON the table stores. */
120
+ function readBlueprint(bundleDir, relativePath) {
121
+ const file = path.join(bundleDir, relativePath);
122
+ if (!fs.existsSync(file)) {
123
+ throw new BundleError(`Blueprint not found: ${relativePath}`);
124
+ }
125
+ const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
126
+ for (const required of ["version", "definition", "inputSchema"]) {
127
+ if (raw[required] === undefined) {
128
+ throw new BundleError(`${relativePath} declares no ${required}`);
129
+ }
130
+ }
131
+ return {
132
+ version: String(raw.version),
133
+ status: textOr(raw.status, "DRAFT"),
134
+ // Re-serialised, not passed through: the table's columns are jsonb and the service sends
135
+ // them as text. Stringifying here keeps the CLI from inventing a second JSON dialect.
136
+ definition: JSON.stringify(raw.definition),
137
+ inputSchema: JSON.stringify(raw.inputSchema),
138
+ configSchema: JSON.stringify(raw.configSchema ?? {}),
139
+ estimatedCredits: Number(raw.estimatedCredits ?? 0),
140
+ changelog: raw.changelog ?? null,
141
+ createdBy: textOr(raw.createdBy, "system"),
142
+ };
143
+ }
144
+ /** A scalar field as text, or its declared default when the manifest omits it. */
145
+ function textOr(value, fallback) {
146
+ return value == null ? fallback : String(value);
147
+ }
148
+ /** Reads every i18n/<locale>.yaml into the translation map the bundle carries. */
149
+ function readTranslations(bundleDir) {
150
+ const dir = path.join(bundleDir, I18N_DIR);
151
+ if (!fs.existsSync(dir)) {
152
+ return {};
153
+ }
154
+ const translations = {};
155
+ for (const file of fs.readdirSync(dir).sort()) {
156
+ if (!file.endsWith(".yaml") && !file.endsWith(".yml")) {
157
+ continue;
158
+ }
159
+ const locale = file.replace(/\.ya?ml$/, "");
160
+ translations[locale] = (0, yaml_1.parse)(fs.readFileSync(path.join(dir, file), "utf-8")) ?? {};
161
+ }
162
+ return translations;
163
+ }
164
+ /**
165
+ * The capabilities a pack contributes, with their contract re-serialised.
166
+ *
167
+ * `inputSchema` and `outputSchema` are objects in the manifest and `jsonb` in the table, and the
168
+ * record between them carries them as text — the same resolution the three blueprint schemas
169
+ * already get above, and for the same reason: stringifying here keeps the CLI from inventing a
170
+ * second JSON dialect (ADR-069).
171
+ */
172
+ function readCapabilities(declared) {
173
+ if (!Array.isArray(declared)) {
174
+ return [];
175
+ }
176
+ return declared.map((entry) => {
177
+ const capability = entry;
178
+ return {
179
+ ...capability,
180
+ inputSchema: JSON.stringify(capability.inputSchema ?? {}),
181
+ outputSchema: JSON.stringify(capability.outputSchema ?? {}),
182
+ };
183
+ });
184
+ }
185
+ /**
186
+ * Reads a bundle directory into the value the installer applies.
187
+ *
188
+ * @param bundleDir the directory holding pack.yaml
189
+ * @returns the resolved bundle, and the shape problems found in its manifest
190
+ */
191
+ function loadBundle(bundleDir) {
192
+ const resolved = path.resolve(bundleDir);
193
+ const manifestPath = path.join(resolved, MANIFEST);
194
+ if (!fs.existsSync(manifestPath)) {
195
+ throw new BundleError(`No ${MANIFEST} in ${resolved} — that file is what makes a directory a pack.`);
196
+ }
197
+ const manifest = (0, yaml_1.parse)(fs.readFileSync(manifestPath, "utf-8"));
198
+ const problems = validateManifest(resolved, manifest);
199
+ if (problems.length > 0) {
200
+ // Returned rather than thrown: `validate` must be able to print every problem at once, and a
201
+ // bundle with four faults should cost one run to diagnose rather than four.
202
+ return { bundle: manifest, problems };
203
+ }
204
+ const requires = (manifest.requires ?? {});
205
+ const studios = manifest.studios.map((studio) => ({
206
+ key: String(studio.key),
207
+ profession: String(studio.profession),
208
+ iconKey: String(studio.iconKey),
209
+ pricing: String(studio.pricing),
210
+ entitlementKey: String(studio.entitlementKey),
211
+ status: textOr(studio.status, "DRAFT"),
212
+ publisherId: textOr(studio.publisherId, "orazaka"),
213
+ sortWeight: Number(studio.sortWeight ?? 0),
214
+ blueprint: readBlueprint(resolved, String(studio.blueprint)),
215
+ }));
216
+ return {
217
+ bundle: {
218
+ apiVersion: String(manifest.apiVersion),
219
+ key: String(manifest.key),
220
+ version: String(manifest.version),
221
+ tier: textOr(manifest.tier, "DATA"),
222
+ distribution: textOr(manifest.distribution, "OSS"),
223
+ regulatoryClass: textOr(manifest.regulatoryClass, "STANDARD"),
224
+ // The schema's declared default, like tier and regulatoryClass above. VERTICAL is also the
225
+ // kind that grants nothing by itself, so an omitted kind can never hand out a capability.
226
+ kind: textOr(manifest.kind, "VERTICAL"),
227
+ capabilities: readCapabilities(requires.capabilities),
228
+ catalog: manifest.catalog ?? null,
229
+ pricing: manifest.pricing ?? null,
230
+ studios,
231
+ translations: readTranslations(resolved),
232
+ // Passed through, never defaulted: the platform refuses a SENSITIVE bundle that declares
233
+ // no scope guard, and a CLI inventing an empty one would turn that refusal into a pack
234
+ // that installs with a control nobody wrote (ADR-051).
235
+ scopeGuard: manifest.scopeGuard ?? null,
236
+ consent: manifest.consent ?? null,
237
+ safety: manifest.safety ?? null,
238
+ },
239
+ problems: [],
240
+ };
241
+ }
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ /**
3
+ * @file pack.sources.ts
4
+ * @description Where this deployment's packs come from — `orazaka.packs.sources` (ADR-049).
5
+ *
6
+ * The one line that separates an OSS deployment from a cloud one. An OSS install lists local
7
+ * directories; a cloud install lists a registry as well. Nothing else in the tree changes, which
8
+ * is the whole claim of the open-core split: a cloud pack is never a core patch.
9
+ *
10
+ * Read from ORAZAKA_PACKS_SOURCES, comma-separated, in priority order. A source is either a
11
+ * directory path or `registry:<url>`.
12
+ */
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || (function () {
30
+ var ownKeys = function(o) {
31
+ ownKeys = Object.getOwnPropertyNames || function (o) {
32
+ var ar = [];
33
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
34
+ return ar;
35
+ };
36
+ return ownKeys(o);
37
+ };
38
+ return function (mod) {
39
+ if (mod && mod.__esModule) return mod;
40
+ var result = {};
41
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
42
+ __setModuleDefault(result, mod);
43
+ return result;
44
+ };
45
+ })();
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.DEFAULT_SOURCE = void 0;
48
+ exports.packSources = packSources;
49
+ exports.discoverBundles = discoverBundles;
50
+ const fs = __importStar(require("node:fs"));
51
+ const path = __importStar(require("node:path"));
52
+ const config_1 = require("../utils/config");
53
+ /** The default an untouched clone runs with: this repository's own reference packs. */
54
+ exports.DEFAULT_SOURCE = "packs";
55
+ const REGISTRY_PREFIX = "registry:";
56
+ /**
57
+ * This deployment's pack sources, in the order they are searched.
58
+ *
59
+ * @returns every configured source, including ones this deployment cannot serve
60
+ */
61
+ function packSources() {
62
+ return (0, config_1.strEnv)("ORAZAKA_PACKS_SOURCES", exports.DEFAULT_SOURCE)
63
+ .split(",")
64
+ .map((entry) => entry.trim())
65
+ .filter((entry) => entry.length > 0)
66
+ .map((entry) => entry.startsWith(REGISTRY_PREFIX)
67
+ ? {
68
+ kind: "registry",
69
+ location: entry.slice(REGISTRY_PREFIX.length),
70
+ // Named, not silently skipped: a deployment that thinks it has a registry and
71
+ // quietly resolves nothing is worse than one that says the control plane is absent.
72
+ unavailable: "registry sources need the cloud control plane; this deployment is local (AGENTS.md §0)",
73
+ }
74
+ : { kind: "directory", location: entry });
75
+ }
76
+ /**
77
+ * Every bundle the configured sources offer.
78
+ *
79
+ * <p>A directory that does not exist is skipped rather than fatal: sources are a deployment's
80
+ * declaration of where it looks, and looking somewhere empty is not an error.
81
+ *
82
+ * @returns the bundles, in source order
83
+ */
84
+ function discoverBundles() {
85
+ const found = [];
86
+ for (const source of packSources()) {
87
+ if (source.kind !== "directory" || !fs.existsSync(source.location)) {
88
+ continue;
89
+ }
90
+ for (const entry of fs.readdirSync(source.location, { withFileTypes: true })) {
91
+ if (!entry.isDirectory()) {
92
+ continue;
93
+ }
94
+ const directory = path.join(source.location, entry.name);
95
+ if (fs.existsSync(path.join(directory, "pack.yaml"))) {
96
+ found.push({ directory, source: source.location });
97
+ }
98
+ }
99
+ }
100
+ return found;
101
+ }