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
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * @file index.ts
5
+ * @description Main entry point and bootstrap registry for the Sovkora CLI.
6
+ * Registers all commands, displays the startup banner, and provides graceful error handling.
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
42
+ return (mod && mod.__esModule) ? mod : { "default": mod };
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ const commander_1 = require("commander");
46
+ const fs = __importStar(require("node:fs"));
47
+ const path = __importStar(require("node:path"));
48
+ const chalk_1 = __importDefault(require("chalk"));
49
+ const development_status_1 = require("./utils/development-status");
50
+ const version_manager_1 = require("./services/version-manager");
51
+ const login_command_1 = require("./commands/login.command");
52
+ const register_command_1 = require("./commands/register.command");
53
+ const verify_command_1 = require("./commands/verify.command");
54
+ const forgot_command_1 = require("./commands/forgot.command");
55
+ const reset_command_1 = require("./commands/reset.command");
56
+ const chat_command_1 = require("./commands/chat.command");
57
+ const settings_command_1 = require("./commands/settings.command");
58
+ const profile_command_1 = require("./commands/profile.command");
59
+ const video_command_1 = require("./commands/video.command");
60
+ const graph_command_1 = require("./commands/graph.command");
61
+ const studio_command_1 = require("./commands/studio.command");
62
+ const runs_command_1 = require("./commands/runs.command");
63
+ const cinema_command_1 = require("./commands/cinema.command");
64
+ const pack_command_1 = require("./commands/pack.command");
65
+ const mcp_command_1 = require("./commands/mcp.command");
66
+ const init_command_1 = require("./commands/init.command");
67
+ const doctor_command_1 = require("./commands/doctor.command");
68
+ const start_command_1 = require("./commands/start.command");
69
+ const recover_command_1 = require("./commands/recover.command");
70
+ const stop_command_1 = require("./commands/stop.command");
71
+ const config_command_1 = require("./commands/config.command");
72
+ const agent_command_1 = require("./commands/agent.command");
73
+ const install_command_1 = require("./commands/install.command");
74
+ const generate_command_1 = require("./commands/generate.command");
75
+ const logs_command_1 = require("./commands/logs.command");
76
+ const status_command_1 = require("./commands/status.command");
77
+ const dev_command_1 = require("./commands/dev.command");
78
+ const onboard_command_1 = require("./commands/onboard.command");
79
+ const test_command_1 = require("./commands/test.command");
80
+ const docs_command_1 = require("./commands/docs.command");
81
+ const db_command_1 = require("./commands/db.command");
82
+ const models_command_1 = require("./commands/models.command");
83
+ const demo_command_1 = require("./commands/demo.command");
84
+ const release_command_1 = require("./commands/release.command");
85
+ function getVersion() {
86
+ const pkgPath = path.resolve(__dirname, "..", "package.json");
87
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
88
+ return pkg?.version ?? "UNKNOWN";
89
+ }
90
+ const VERSION = getVersion();
91
+ function getBanner() {
92
+ const v = `v${VERSION}`;
93
+ return `
94
+ ${chalk_1.default.cyan(" ┌──────────────────────────────────────────────┐")}
95
+ ${chalk_1.default.cyan(" │")} ${chalk_1.default.cyan("│")}
96
+ ${chalk_1.default.cyan(" │")} ${chalk_1.default.white.bold("🥷 O R A Z A K A")} ${chalk_1.default.gray(v.padEnd(8))} ${chalk_1.default.cyan("│")}
97
+ ${chalk_1.default.cyan(" │")} ${chalk_1.default.gray("Sovereign AI Orchestration Engine")} ${chalk_1.default.cyan("│")}
98
+ ${chalk_1.default.cyan(" │")} ${chalk_1.default.cyan("│")}
99
+ ${chalk_1.default.cyan(" └──────────────────────────────────────────────┘")}
100
+ `;
101
+ }
102
+ function getHelpFooter() {
103
+ return `
104
+ ${chalk_1.default.gray((0, development_status_1.developmentStatus)())}
105
+ ${chalk_1.default.cyan.bold("Quick Start:")}
106
+ ${chalk_1.default.white("$")} npx sovkora init ${chalk_1.default.gray("Initialize workspace")}
107
+ ${chalk_1.default.white("$")} npx sovkora install ${chalk_1.default.gray("Verify tools & setup topology")}
108
+ ${chalk_1.default.white("$")} npx sovkora start ${chalk_1.default.gray("Launch infrastructure (dev mode)")}
109
+ ${chalk_1.default.white("$")} npx sovkora dev ${chalk_1.default.gray("Launch full dev stack in parallel")}
110
+ ${chalk_1.default.white("$")} npx sovkora status ${chalk_1.default.gray("Check service health")}
111
+
112
+ ${chalk_1.default.cyan.bold("Development:")}
113
+ ${chalk_1.default.white("$")} npx sovkora generate ${chalk_1.default.gray("Scaffold features & interceptors")}
114
+ ${chalk_1.default.white("$")} npx sovkora logs ${chalk_1.default.gray("Stream real-time logs")}
115
+ ${chalk_1.default.white("$")} npx sovkora recover ${chalk_1.default.gray("Diagnose & fix issues")}
116
+ ${chalk_1.default.white("$")} npx sovkora doctor ${chalk_1.default.gray("Full system diagnostics")}
117
+
118
+ ${chalk_1.default.cyan.bold("Documentation:")}
119
+ ${chalk_1.default.gray("https://github.com/krizaka/orazaka/blob/main/docs/_generated/CLI.md")}
120
+ `;
121
+ }
122
+ const program = new commander_1.Command("sovkora");
123
+ program
124
+ .version(VERSION)
125
+ .description("Sovkora AI CLI — Sovereign multi-modal AI orchestration from your terminal")
126
+ .addHelpText("before", getBanner())
127
+ .addHelpText("after", getHelpFooter())
128
+ // ─── Lifecycle Commands ────────────────────────────────
129
+ .addCommand(init_command_1.initCommand)
130
+ .addCommand(install_command_1.installCommand)
131
+ .addCommand(doctor_command_1.doctorCommand)
132
+ .addCommand(config_command_1.configCommand)
133
+ .addCommand(start_command_1.startCommand)
134
+ .addCommand(stop_command_1.stopCommand)
135
+ .addCommand(onboard_command_1.onboardCommand)
136
+ .addCommand(demo_command_1.demoCommand)
137
+ .addCommand(release_command_1.releaseCommand)
138
+ // ─── Recovery & Troubleshooting ─────────────────────────
139
+ .addCommand(recover_command_1.recoverCommand)
140
+ // ─── Observability ──────────────────────────────────────
141
+ .addCommand(logs_command_1.logsCommand)
142
+ .addCommand(status_command_1.statusCommand)
143
+ .addCommand(models_command_1.modelsCommand)
144
+ .addCommand(db_command_1.dbCommand)
145
+ // ─── Development & Code Generation ──────────────────────
146
+ .addCommand(generate_command_1.generateCommand)
147
+ .addCommand(dev_command_1.devCommand)
148
+ .addCommand(test_command_1.testCommand)
149
+ .addCommand(docs_command_1.docsCommand)
150
+ // ─── Auth Commands ─────────────────────────────────────
151
+ .addCommand(login_command_1.loginCommand)
152
+ .addCommand(register_command_1.registerCommand)
153
+ .addCommand(verify_command_1.verifyCommand)
154
+ .addCommand(forgot_command_1.forgotCommand)
155
+ .addCommand(reset_command_1.resetCommand)
156
+ // ─── Core Commands ─────────────────────────────────────
157
+ .addCommand(chat_command_1.chatCommand)
158
+ .addCommand(settings_command_1.settingsCommand)
159
+ .addCommand(profile_command_1.profileCommand)
160
+ .addCommand(video_command_1.videoCommand)
161
+ .addCommand(graph_command_1.graphCommand)
162
+ .addCommand(studio_command_1.studioCommand)
163
+ .addCommand(runs_command_1.runsCommand)
164
+ .addCommand(cinema_command_1.cinemaCommand)
165
+ .addCommand(pack_command_1.packCommand)
166
+ .addCommand(mcp_command_1.mcpCommand)
167
+ .addCommand(agent_command_1.agentCommand);
168
+ // Check for CLI updates (non-blocking, background check)
169
+ async function checkVersionAsync() {
170
+ try {
171
+ // Skip if suppressed (CI/CD environments)
172
+ if (process.env.ORAZAKA_SKIP_VERSION_CHECK === "true") {
173
+ return;
174
+ }
175
+ const versionManager = new version_manager_1.VersionManager(VERSION);
176
+ // Don't block startup - check in background with timeout
177
+ const checkPromise = versionManager.checkForUpdates();
178
+ const timeoutPromise = new Promise((resolve) => {
179
+ setTimeout(() => resolve(), 2000); // 2 second timeout
180
+ });
181
+ const result = await Promise.race([
182
+ checkPromise.then((info) => ({ success: true, info })),
183
+ timeoutPromise.then(() => ({ success: false, info: undefined })),
184
+ ]);
185
+ if (result.success && result.info) {
186
+ const lines = versionManager.formatUpdateNotification(result.info);
187
+ for (const line of lines) {
188
+ console.log(line);
189
+ }
190
+ }
191
+ }
192
+ catch {
193
+ // Silently fail - don't break CLI if version check fails
194
+ }
195
+ }
196
+ // Graceful execution entry point
197
+ async function main() {
198
+ // Check for updates (non-blocking)
199
+ checkVersionAsync().catch(() => {
200
+ // Ignore errors from version check
201
+ });
202
+ await program.parseAsync(process.argv);
203
+ }
204
+ main().catch((err) => {
205
+ console.error(chalk_1.default.red(`\n❌ Fatal Error: ${err instanceof Error ? err.message : String(err)}`));
206
+ process.exit(1);
207
+ });
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ /**
3
+ * @file renderers.ts
4
+ * @description Output rendering pipeline for multi-modal CLI responses.
5
+ * Handles text, image (Data URL → file), audio (Data URL → file), and video (Base64 → file).
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.renderText = renderText;
42
+ exports.renderImage = renderImage;
43
+ exports.renderAudio = renderAudio;
44
+ exports.renderVideo = renderVideo;
45
+ exports.renderTimeline = renderTimeline;
46
+ const fs = __importStar(require("node:fs"));
47
+ const path = __importStar(require("node:path"));
48
+ const date_fns_1 = require("date-fns");
49
+ const config_1 = require("./utils/config");
50
+ const threads_1 = require("./threads");
51
+ const DATA_URL_REGEX = /^data:([^;]+);base64,(.+)$/;
52
+ /**
53
+ * Extracts MIME type and raw binary bytes from an RFC 2397 Data URL.
54
+ *
55
+ * @param dataUrl - The full data URL string.
56
+ * @returns Decoded buffer and MIME type, or null if the format is invalid.
57
+ */
58
+ function decodeDataUrl(dataUrl) {
59
+ const match = DATA_URL_REGEX.exec(dataUrl);
60
+ if (!match)
61
+ return null;
62
+ return { mime: match[1], buffer: Buffer.from(match[2], "base64") };
63
+ }
64
+ /**
65
+ * Determines a file extension from a MIME type string.
66
+ *
67
+ * @param mime - The MIME type (e.g., `image/png`, `audio/mp3`).
68
+ * @returns A file extension including the dot.
69
+ */
70
+ function extensionFromMime(mime) {
71
+ const map = {
72
+ "image/png": ".png",
73
+ "image/jpeg": ".jpg",
74
+ "image/webp": ".webp",
75
+ "audio/mp3": ".mp3",
76
+ "audio/mpeg": ".mp3",
77
+ "audio/wav": ".wav",
78
+ "video/mp4": ".mp4",
79
+ };
80
+ return map[mime] || ".bin";
81
+ }
82
+ /**
83
+ * Writes raw binary data to disk and prints a confirmation.
84
+ *
85
+ * @param buffer - The binary payload.
86
+ * @param savePath - Absolute or relative path to the target file.
87
+ */
88
+ function writeToDisk(buffer, savePath) {
89
+ const resolved = path.resolve(savePath);
90
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
91
+ fs.writeFileSync(resolved, buffer);
92
+ const sizeKb = (buffer.length / 1024).toFixed(1);
93
+ console.log(`\x1b[32m✓ Saved to ${resolved} (${sizeKb} KB)\x1b[0m`);
94
+ }
95
+ /**
96
+ * Generates a timestamped filename for auto-saved media.
97
+ *
98
+ * @param prefix - A descriptive prefix (e.g., `orazaka-image`).
99
+ * @param ext - The file extension including the dot.
100
+ * @returns A filename string.
101
+ */
102
+ function autoFileName(prefix, ext) {
103
+ const ts = (0, date_fns_1.format)(new Date(), "yyyy-MM-dd'T'HH-mm-ss");
104
+ return `${prefix}-${ts}${ext}`;
105
+ }
106
+ // ── Public Renderers ─────────────────────────────────────────────────────────
107
+ /**
108
+ * Renders plain text content to stdout.
109
+ *
110
+ * @param content - The text content.
111
+ */
112
+ function renderText(content) {
113
+ console.log(content);
114
+ }
115
+ /**
116
+ * Renders an image response. If the content is a Data URL, it is decoded and saved to disk.
117
+ *
118
+ * @param content - The image content (Data URL or plain text description).
119
+ * @param savePath - Optional explicit save path; auto-generates if omitted.
120
+ */
121
+ async function downloadUrl(urlStr) {
122
+ const absolute = urlStr.startsWith("http");
123
+ const fullUrl = absolute ? urlStr : `${config_1.ROUTER_URL}${urlStr}`;
124
+ // An asset of the platform (`/api/v1/assets/…`) is its owner's: the session's token asks for it. A URL elsewhere gets none.
125
+ const token = urlStr.startsWith("/api/") ? (0, threads_1.loadConfig)()?.token : undefined;
126
+ const response = token
127
+ ? await fetch(fullUrl, { headers: { Authorization: `Bearer ${token}` } })
128
+ : await fetch(fullUrl);
129
+ if (!response.ok) {
130
+ throw new Error(`Failed to download media: status ${response.status}`);
131
+ }
132
+ return Buffer.from(await response.arrayBuffer());
133
+ }
134
+ /**
135
+ * Shared media content renderer. Handles the decode/download/save pipeline
136
+ * and delegates formatting to the per-kind config.
137
+ */
138
+ async function renderMediaContent(content, config, savePath) {
139
+ const decoded = decodeDataUrl(content);
140
+ if (decoded) {
141
+ const ext = extensionFromMime(decoded.mime);
142
+ const target = savePath || autoFileName(config.prefix, ext);
143
+ writeToDisk(decoded.buffer, target);
144
+ for (const line of config.formatSuccess(target, decoded.buffer, decoded.mime)) {
145
+ console.log(line);
146
+ }
147
+ }
148
+ else if (content.startsWith("http") || content.startsWith("/uploads") || content.startsWith("/api/")) {
149
+ try {
150
+ const buffer = await downloadUrl(content);
151
+ const target = savePath || autoFileName(config.prefix, config.defaultExt);
152
+ writeToDisk(buffer, target);
153
+ for (const line of config.formatSuccess(target, buffer)) {
154
+ console.log(line);
155
+ }
156
+ }
157
+ catch (err) {
158
+ const msg = err instanceof Error ? err.message : String(err);
159
+ console.log(`${config.color}[${config.label}]\x1b[0m Failed to download ${config.label.toLowerCase()} URL: ${msg}`);
160
+ }
161
+ }
162
+ else {
163
+ console.log(`${config.color}[${config.label}]\x1b[0m ${content}`);
164
+ }
165
+ }
166
+ // ── Media Render Configs ─────────────────────────────────────────────────────
167
+ const IMAGE_CONFIG = {
168
+ prefix: "orazaka-image",
169
+ defaultExt: ".png",
170
+ color: "\x1b[35m",
171
+ label: "IMAGE",
172
+ formatSuccess: (target, buffer, mime) => [
173
+ `\x1b[35m┌─ IMAGE OUTPUT ─────────────────────────────────┐\x1b[0m`,
174
+ `\x1b[35m│\x1b[0m Format: ${(mime || "image/png").padEnd(40)} \x1b[35m│\x1b[0m`,
175
+ `\x1b[35m│\x1b[0m Size: ${(buffer.length / 1024).toFixed(1).padEnd(37)} KB \x1b[35m│\x1b[0m`,
176
+ `\x1b[35m│\x1b[0m File: ${path.basename(target).padEnd(40)} \x1b[35m│\x1b[0m`,
177
+ `\x1b[35m└────────────────────────────────────────────────┘\x1b[0m`,
178
+ ],
179
+ };
180
+ const AUDIO_CONFIG = {
181
+ prefix: "orazaka-speech",
182
+ defaultExt: ".mp3",
183
+ color: "\x1b[33m",
184
+ label: "AUDIO",
185
+ formatSuccess: (target) => [
186
+ `\x1b[33m🔊 Audio saved → ${path.resolve(target)}\x1b[0m`,
187
+ `\x1b[90m Hint: afplay "${path.resolve(target)}" (macOS)\x1b[0m`,
188
+ ],
189
+ };
190
+ const VIDEO_CONFIG = {
191
+ prefix: "orazaka-video",
192
+ defaultExt: ".mp4",
193
+ color: "\x1b[36m",
194
+ label: "VIDEO",
195
+ formatSuccess: (target, buffer) => {
196
+ const sizeMb = (buffer.length / (1024 * 1024)).toFixed(2);
197
+ return [
198
+ `\x1b[36m🎬 Video saved → ${path.resolve(target)} (${sizeMb} MB)\x1b[0m`,
199
+ `\x1b[90m Hint: open "${path.resolve(target)}" (macOS QuickTime)\x1b[0m`,
200
+ ];
201
+ },
202
+ };
203
+ // ── Public Renderers ─────────────────────────────────────────────────────────
204
+ /**
205
+ * Renders an image response. If the content is a Data URL, it is decoded and saved to disk.
206
+ * If it's a URL, the image is downloaded and saved.
207
+ */
208
+ async function renderImage(content, savePath) {
209
+ return renderMediaContent(content, IMAGE_CONFIG, savePath);
210
+ }
211
+ /**
212
+ * Renders an audio response. If the content is a Data URL, it is decoded and saved to disk.
213
+ * If it's a URL, the audio is downloaded and saved.
214
+ */
215
+ async function renderAudio(content, savePath) {
216
+ return renderMediaContent(content, AUDIO_CONFIG, savePath);
217
+ }
218
+ /**
219
+ * Renders a video response by decoding the Base64 payload and saving to disk.
220
+ * If it's a URL, the video is downloaded and saved.
221
+ */
222
+ async function renderVideo(content, savePath) {
223
+ return renderMediaContent(content, VIDEO_CONFIG, savePath);
224
+ }
225
+ /**
226
+ * Dispatches a timeline message to the appropriate media renderer.
227
+ *
228
+ * @param message - The timeline message with its discriminated kind.
229
+ * @param savePath - Optional explicit save path for media output.
230
+ */
231
+ async function renderTimeline(message, savePath) {
232
+ switch (message.kind) {
233
+ case "text":
234
+ renderText(message.content);
235
+ break;
236
+ case "image":
237
+ await renderImage(message.content, savePath);
238
+ break;
239
+ case "audio":
240
+ await renderAudio(message.content, savePath);
241
+ break;
242
+ case "video":
243
+ await renderVideo(message.content, savePath);
244
+ break;
245
+ default: {
246
+ const _exhaustive = message;
247
+ return _exhaustive;
248
+ }
249
+ }
250
+ }
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ /**
3
+ * @file api-client.ts
4
+ * @description Base client for all REST and GraphQL outgoing requests to the Gateway.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.ApiClient = void 0;
41
+ const fs = __importStar(require("node:fs"));
42
+ const path = __importStar(require("node:path"));
43
+ const threads_1 = require("../threads");
44
+ const config_1 = require("../utils/config");
45
+ class ApiClient {
46
+ /**
47
+ * Uploads a file to the Gateway.
48
+ */
49
+ static async uploadFile(filePath) {
50
+ const url = `${this.getBaseUrl()}/api/v1/media/upload`;
51
+ const config = (0, threads_1.loadConfig)();
52
+ const headers = {
53
+ ...(config?.token ? { Authorization: `Bearer ${config.token}` } : {}),
54
+ ...(config?.userId ? { "X-User-Id": config.userId } : {}),
55
+ };
56
+ const formData = new FormData();
57
+ const fileBuffer = fs.readFileSync(filePath);
58
+ const blob = new Blob([fileBuffer]);
59
+ formData.append("file", blob, path.basename(filePath));
60
+ const response = await fetch(url, {
61
+ method: "POST",
62
+ headers,
63
+ body: formData,
64
+ });
65
+ if (!response.ok) {
66
+ const errText = await response.text().catch(() => "");
67
+ throw new Error(`Upload failed: status ${response.status} - ${errText}`);
68
+ }
69
+ return response.json();
70
+ }
71
+ /**
72
+ * Downloads what the Gateway serves at `pathOrUrl` (a run's output, `/api/v1/assets/<job>/<file>`) into `file`.
73
+ */
74
+ static async downloadTo(pathOrUrl, file) {
75
+ const separator = pathOrUrl.startsWith("/") ? "" : "/";
76
+ const url = /^https?:\/\//.test(pathOrUrl) ? pathOrUrl : `${this.getBaseUrl()}${separator}${pathOrUrl}`;
77
+ const config = (0, threads_1.loadConfig)();
78
+ const response = await fetch(url, {
79
+ headers: config?.token && url.startsWith(this.getBaseUrl()) ? { Authorization: `Bearer ${config.token}` } : {},
80
+ });
81
+ if (!response.ok) {
82
+ throw new Error(`Download failed: status ${response.status}`);
83
+ }
84
+ const bytes = Buffer.from(await response.arrayBuffer());
85
+ fs.mkdirSync(path.dirname(file), { recursive: true });
86
+ fs.writeFileSync(file, bytes);
87
+ return bytes.length;
88
+ }
89
+ static getBaseUrl() {
90
+ return config_1.ROUTER_URL;
91
+ }
92
+ /**
93
+ * Executes a REST API request to the Gateway.
94
+ */
95
+ static async requestRest(options) {
96
+ const url = `${this.getBaseUrl()}${options.path}`;
97
+ const config = (0, threads_1.loadConfig)();
98
+ const headers = {
99
+ "Content-Type": "application/json",
100
+ ...(config?.token ? { Authorization: `Bearer ${config.token}` } : {}),
101
+ ...(config?.userId ? { "X-User-Id": config.userId } : {}),
102
+ };
103
+ const response = await fetch(url, {
104
+ method: options.method,
105
+ headers,
106
+ body: options.body ? JSON.stringify(options.body) : undefined,
107
+ });
108
+ if (!response.ok) {
109
+ const errBody = (await response.json().catch(() => ({})));
110
+ // `error` is the shape most handlers use; `message` + `cause` is what the Studio context's
111
+ // RestErrorResolver returns. Reading only the first turned a 422 that named the failing
112
+ // slice into "HTTP request failed: status 422", which is a diagnosis an operator has to go
113
+ // and find in three services' logs.
114
+ const detail = [errBody.error, errBody.message, errBody.cause]
115
+ .filter((part) => typeof part === "string" && part.length > 0)
116
+ .join(" — ");
117
+ throw new Error(detail || `HTTP request failed: status ${response.status}`);
118
+ }
119
+ return response.json();
120
+ }
121
+ /**
122
+ * Executes a GraphQL API request to the Gateway.
123
+ */
124
+ static async requestGql(query, variables) {
125
+ const url = `${this.getBaseUrl()}/graphql`;
126
+ const config = (0, threads_1.loadConfig)();
127
+ const headers = {
128
+ "Content-Type": "application/json",
129
+ ...(config?.token ? { Authorization: `Bearer ${config.token}` } : {}),
130
+ ...(config?.userId ? { "X-User-Id": config.userId } : {}),
131
+ };
132
+ const response = await fetch(url, {
133
+ method: "POST",
134
+ headers,
135
+ body: JSON.stringify({ query, variables }),
136
+ });
137
+ if (!response.ok) {
138
+ throw new Error(`GraphQL request failed: status ${response.status}`);
139
+ }
140
+ const json = (await response.json());
141
+ if (json.errors && json.errors.length > 0) {
142
+ throw new Error(json.errors[0].message);
143
+ }
144
+ if (!json.data) {
145
+ throw new Error("No data returned from the GraphQL endpoint.");
146
+ }
147
+ return json.data;
148
+ }
149
+ }
150
+ exports.ApiClient = ApiClient;