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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ Sovkora CLI
2
+ Copyright 2026 Krizaka
3
+
4
+ This product includes software developed at Krizaka (https://krizaka.com)
5
+ as part of the Sovkora platform (https://github.com/krizaka/orazaka).
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
8
+ this file except in compliance with the License. You may obtain a copy of the
9
+ License at http://www.apache.org/licenses/LICENSE-2.0
package/README.md CHANGED
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # Sovkora CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > `apps/cli` of [Sovkora](../../README.md), one repository (pnpm, app layer). Depends on nothing else of Sovkora. Licence: [Apache-2.0](LICENSE).
4
+
5
+ The developer CLI: install, start, dev, test, docs and pack tooling for the local Sovkora stack, with an offline SQLite queue.
6
+
7
+ ## Quick start
8
+
9
+ Requirements: git, JDK 21, Node.js 22+, Docker (Python 3.11+ for the media worker).
10
+
11
+ ```bash
12
+ npx sovkora install # no workspace here? clones the platform into ./orazaka, then configures it
13
+ cd sovkora && ./mvnw install && pnpm install
14
+ npx sovkora start # Docker infrastructure (PostgreSQL + pgvector, Redis, RabbitMQ)
15
+ npx sovkora dev # the whole stack: services, web (with the operator console), mobile
16
+ ```
17
+
18
+ The npm package is `sovkora`, and so is the command; installed globally it runs without `npx`:
19
+
20
+ ```bash
21
+ npm install -g sovkora # then: sovkora <command>
22
+ ```
23
+
24
+ `install` verifies the tools (and offers Homebrew installs on macOS), clones
25
+ [krizaka/orazaka](https://github.com/krizaka/orazaka) and every component repository when it is not run inside a
26
+ workspace (`--dir <path>`, `--depth <n>`; `--yes` accepts every default without a prompt), sets up the media worker's
27
+ Python environment and writes `.env` and `infra/docker-compose.override.yml`. `install --check-only` only reports.
28
+ `start`, `dev`, `test` and `docs` run inside a workspace and say how to get one when there is none.
29
+
30
+ ## What it provides
31
+
32
+ The single orchestrator of the platform (no shell scripts): `sovkora install`, `start` (Docker infra),
33
+ `models pull`, `dev`, `onboard`, `test [unit|it|e2e]`, `docs [build|sync]`, `pack list|validate|install|publish`,
34
+ `demo seed`, `doctor`.
35
+
36
+ ### Local image models
37
+
38
+ Images are generated on the Mac by [stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) (`sd-server`,
39
+ Metal). `sovkora models image` installs the models it can serve — every one under a licence that allows commercial use:
40
+
41
+ | Model | Licence | Disk | RAM | Measured on an M1 Max (64 GB) |
42
+ | :---------------------------------------------- | :-------------------- | ------: | -----: | :-------------------------------------- |
43
+ | `flux-2-klein-4b` — FLUX.2 [klein] 4B (default) | Apache-2.0 | 8.7 GB | ~11 GB | 1024Ɨ1024 in ~82 s, 1024Ɨ1280 in ~105 s |
44
+ | `z-image-turbo` — Z-Image Turbo | Apache-2.0 | 11.2 GB | ~12 GB | 1024Ɨ1024 in ~233 s |
45
+ | `v1-5-pruned-emaonly` — Stable Diffusion 1.5 | CreativeML OpenRAIL-M | 4.3 GB | ~5 GB | 512Ɨ512 in ~68 s |
46
+
47
+ ```bash
48
+ sovkora models image list # licence, size, installed, which one is served
49
+ sovkora models image pull flux-2-klein-4b # download into ~/models/stable-diffusion, sha256-verified
50
+ sovkora models image use flux-2-klein-4b # make it the catalogue's default, then restart the stack
51
+ ```
52
+
53
+ `sd-server` serves one model at a time: `sovkora start` launches the catalogue's default image model with its own
54
+ recipe (steps, guidance, flags from `src/services/image-model-recipes.json`) and refuses to serve another one under its name.
55
+ Prose inputs with commas go through a file: `sovkora studio run <installation> --inputs-file inputs.json`.
56
+
57
+ ### Runs as background tasks (ADR-088)
58
+
59
+ `sovkora runs ls [--watch] [--json]` lists the runs (name, status, current step, elapsed time, cost against the budget; `--watch` refreshes every 3 s); `sovkora runs show <name|id> [--steps] [--json]` shows one run and its folded timeline. Name and cost columns show `-` until the Studio serves them. `sovkora runs stop <ref>` cancels a run, `sovkora runs approve <ref>` approves the step it waits on, `sovkora runs resume <ref> --from <step>` starts a new run from a step (all take `--json`). `sovkora runs send <ref> "<message>"` answers a run that waits for input and `sovkora runs deny <ref> [--reason <text>]` refuses the approval it waits on (the run stops without the step). `sovkora runs wait <ref> [--notify]` follows a run until it ends or needs you. `sovkora studio run <target>` now follows the run to its end; `--background` prints the run id and returns at once, `--notify` sends a desktop notification (Notification Center on macOS, `notify-send` on Linux, the terminal bell elsewhere) when it ends or needs approval.
60
+
61
+ ## Build and test
62
+
63
+ ```bash
64
+ pnpm install # from the repository root: every app, each with its own lockfile
65
+ pnpm --dir apps/cli run validate # lint, types and tests, as CI runs them
66
+ ```
67
+
68
+ CI runs it on every pull request that touches `apps/cli/` (ADR-029: one repository, one CI).
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ /**
3
+ * @file agent.command.ts
4
+ * @description The CLI agent listener: holds the agent stream open, records the automation payloads it receives in the
5
+ * local SQLite queue and reports their status back.
6
+ *
7
+ * It **never executes** what the server sends. Running a shell command received over the network is remote code
8
+ * execution by design; ADR-079 (krizaka/orazaka, docs/adr/ADR-079-automations-and-local-agents.md) retires it: work on
9
+ * the user's machine is done by the Sovkora runner (the Mac app today, a headless runner later), with tools behind
10
+ * approvals and no shell in v1. A payload that reaches this listener is recorded and reported as refused.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ var __importDefault = (this && this.__importDefault) || function (mod) {
46
+ return (mod && mod.__esModule) ? mod : { "default": mod };
47
+ };
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ exports.agentCommand = exports.REFUSAL = void 0;
50
+ const commander_1 = require("commander");
51
+ const chalk_1 = __importDefault(require("chalk"));
52
+ const http = __importStar(require("node:http"));
53
+ const https = __importStar(require("node:https"));
54
+ const threads_1 = require("../threads");
55
+ const settings_api_1 = require("../services/settings.api");
56
+ const config_1 = require("../utils/config");
57
+ const prompts_1 = require("../ui/prompts");
58
+ const local_store_1 = require("../services/local-store");
59
+ let isReconnecting = false;
60
+ let reconnectTimer = null;
61
+ let heartbeatTimer = null;
62
+ /**
63
+ * Sends a job report back to the Gateway.
64
+ */
65
+ async function postJobReport(jobId, status, logs, exitCode, userId, token) {
66
+ try {
67
+ const url = `${config_1.ROUTER_URL}/api/v1/agent/report`;
68
+ const response = await fetch(url, {
69
+ method: "POST",
70
+ headers: {
71
+ "Content-Type": "application/json",
72
+ Authorization: `Bearer ${token}`,
73
+ "X-User-Id": userId,
74
+ },
75
+ body: JSON.stringify({
76
+ jobId,
77
+ status,
78
+ logs,
79
+ exitCode,
80
+ }),
81
+ });
82
+ if (response.ok) {
83
+ (0, local_store_1.markJobSynced)(jobId);
84
+ console.log(chalk_1.default.green(`āœ“ Job ${jobId} execution report successfully synced with Router.`));
85
+ return true;
86
+ }
87
+ else {
88
+ console.warn(chalk_1.default.yellow(`āš ļø Failed to sync report for job ${jobId}. Status: ${response.status}. Retrying later.`));
89
+ return false;
90
+ }
91
+ }
92
+ catch {
93
+ console.warn(chalk_1.default.yellow(`āš ļø Network disconnected. Exit code and logs saved locally for job ${jobId}. Will sync on reconnection.`));
94
+ return false;
95
+ }
96
+ }
97
+ exports.REFUSAL = "Refused: this listener never runs commands sent by the server (ADR-079). Use the Sovkora runner — the Mac app's Automations — whose tools ask before any side effect.";
98
+ /**
99
+ * Records and reports the refusal of a payload: nothing is executed, whatever it carries.
100
+ */
101
+ async function refuseRemoteExecution(jobId, userId, token) {
102
+ console.warn(chalk_1.default.yellow(`ā›” Job ${jobId}: ${exports.REFUSAL}`));
103
+ (0, local_store_1.updateJobStatus)(jobId, "FAILED", exports.REFUSAL);
104
+ await postJobReport(jobId, "FAILED", exports.REFUSAL, -1, userId, token);
105
+ }
106
+ /**
107
+ * Parses and processes a text/event-stream event.
108
+ */
109
+ async function handleSseEvent(eventStr, userId, token) {
110
+ const lines = eventStr.split("\n");
111
+ let eventName = "";
112
+ let dataStr = "";
113
+ for (const line of lines) {
114
+ if (line.startsWith("event:")) {
115
+ eventName = line.slice(6).trim();
116
+ }
117
+ else if (line.startsWith("data:")) {
118
+ dataStr = line.slice(5).trim();
119
+ }
120
+ }
121
+ if (eventName === "connected") {
122
+ console.log(chalk_1.default.gray(`Router connection heartbeat: ${dataStr}`));
123
+ }
124
+ else if (eventName === "automation_payload") {
125
+ try {
126
+ const data = JSON.parse(dataStr);
127
+ console.log(chalk_1.default.cyan(`\nšŸ“„ Received automation job payload: [Job ID: ${data.jobId}] [Action: ${data.action}]`));
128
+ // Recorded in the local SQLite queue (so the refusal is reported even after a disconnection), never executed.
129
+ (0, local_store_1.insertJob)(data.jobId, data.payload, "REFUSED");
130
+ await refuseRemoteExecution(data.jobId, userId, token);
131
+ }
132
+ catch (err) {
133
+ const msg = err instanceof Error ? err.message : String(err);
134
+ console.error(chalk_1.default.red(`Failed to parse automation payload: ${msg}`));
135
+ }
136
+ }
137
+ }
138
+ /**
139
+ * Schedules reconnection timer after disconnect.
140
+ */
141
+ function scheduleReconnect(userId, token) {
142
+ if (isReconnecting)
143
+ return;
144
+ isReconnecting = true;
145
+ console.log(chalk_1.default.yellow("\nšŸ”Œ SSE tunnel disconnected. Attempting reconnection in 5 seconds..."));
146
+ if (reconnectTimer)
147
+ clearTimeout(reconnectTimer);
148
+ reconnectTimer = setTimeout(() => {
149
+ isReconnecting = false;
150
+ listenToAgentStream(userId, token);
151
+ }, 5000);
152
+ }
153
+ /**
154
+ * Connects to the SSE endpoint and registers listeners.
155
+ */
156
+ function listenToAgentStream(userId, token) {
157
+ const urlObj = new URL(`${config_1.ROUTER_URL}/api/v1/agent/stream`);
158
+ const options = {
159
+ method: "GET",
160
+ headers: {
161
+ "X-User-Id": userId,
162
+ Authorization: `Bearer ${token}`,
163
+ Accept: "text/event-stream",
164
+ },
165
+ };
166
+ const client = urlObj.protocol === "https:" ? https : http;
167
+ const req = client.request(urlObj, options, (res) => {
168
+ if (res.statusCode !== 200) {
169
+ console.error(chalk_1.default.red(`\nāŒ SSE connection failed with status: ${res.statusCode}`));
170
+ scheduleReconnect(userId, token);
171
+ return;
172
+ }
173
+ console.log(chalk_1.default.green(`\nāœ“ SSE stream established with Router. Local Agent is online.`));
174
+ // Force run-once sync on successful connection
175
+ const unsynced = (0, local_store_1.getUnsyncedJobs)();
176
+ if (unsynced.length > 0) {
177
+ console.log(chalk_1.default.cyan(`\nFound ${unsynced.length} unsynced local job(s) from disconnected state.`));
178
+ for (const job of unsynced) {
179
+ if (job.status === "COMPLETED" || job.status === "FAILED") {
180
+ const exitCode = job.status === "COMPLETED" ? 0 : 1;
181
+ postJobReport(job.jobId, job.status, job.executionLogs, exitCode, userId, token).catch((err) => console.error(chalk_1.default.red(String(err))));
182
+ }
183
+ }
184
+ }
185
+ let buffer = "";
186
+ res.setEncoding("utf8");
187
+ res.on("data", (chunk) => {
188
+ buffer += chunk;
189
+ const parts = buffer.split("\n\n");
190
+ buffer = parts.pop() || "";
191
+ for (const part of parts) {
192
+ handleSseEvent(part, userId, token).catch((err) => console.error(chalk_1.default.red(String(err))));
193
+ }
194
+ });
195
+ res.on("end", () => {
196
+ console.warn(chalk_1.default.yellow("\nāš ļø SSE stream ended."));
197
+ scheduleReconnect(userId, token);
198
+ });
199
+ res.on("error", (err) => {
200
+ console.error(chalk_1.default.red(`\nāŒ SSE stream error: ${err.message}`));
201
+ scheduleReconnect(userId, token);
202
+ });
203
+ });
204
+ req.on("error", (err) => {
205
+ console.error(chalk_1.default.red(`\nāŒ SSE request failed: ${err.message}`));
206
+ scheduleReconnect(userId, token);
207
+ });
208
+ req.end();
209
+ }
210
+ /**
211
+ * Registers a heartbeat timer to periodically sync unsynced jobs.
212
+ */
213
+ function startHeartbeatSync(userId, token) {
214
+ if (heartbeatTimer)
215
+ clearInterval(heartbeatTimer);
216
+ heartbeatTimer = setInterval(async () => {
217
+ const unsynced = (0, local_store_1.getUnsyncedJobs)();
218
+ if (unsynced.length > 0) {
219
+ for (const job of unsynced) {
220
+ if (job.status === "COMPLETED" || job.status === "FAILED") {
221
+ const exitCode = job.status === "COMPLETED" ? 0 : 1;
222
+ postJobReport(job.jobId, job.status, job.executionLogs, exitCode, userId, token).catch((err) => console.error(chalk_1.default.red(String(err))));
223
+ }
224
+ }
225
+ }
226
+ }, 15000);
227
+ }
228
+ exports.agentCommand = new commander_1.Command("agent").description("Manage Sovkora local executing agent").addCommand(new commander_1.Command("listen").description("Start CLI agent listener and reverse tunnel").action(async () => {
229
+ const config = (0, threads_1.requireAuth)();
230
+ let userId = config.userId;
231
+ if (!userId) {
232
+ const s = await (0, prompts_1.createSpinner)();
233
+ s.start("Fetching user profile ID to configure CLI Agent...");
234
+ try {
235
+ const me = await settings_api_1.SettingsApi.getMe();
236
+ userId = me.id;
237
+ (0, threads_1.saveConfig)({
238
+ ...config,
239
+ userId,
240
+ });
241
+ s.stop("User ID retrieved and configured.");
242
+ }
243
+ catch (err) {
244
+ s.stop("Failed to retrieve user ID", 1);
245
+ const msg = err instanceof Error ? err.message : String(err);
246
+ console.error(chalk_1.default.red(`Error: ${msg}`));
247
+ process.exit(1);
248
+ }
249
+ }
250
+ // Initialize local SQLite table
251
+ (0, local_store_1.getDb)();
252
+ console.log(chalk_1.default.cyan("🄷 Starting Sovkora Local Agent Listener..."));
253
+ console.log(chalk_1.default.gray(`Gateway: ${config_1.ROUTER_URL}`));
254
+ console.log(chalk_1.default.gray(`User ID: ${userId}`));
255
+ // Connect and start polling heartbeat sync
256
+ listenToAgentStream(userId, config.token);
257
+ startHeartbeatSync(userId, config.token);
258
+ // Keep process alive
259
+ process.on("SIGINT", () => {
260
+ console.log(chalk_1.default.yellow("\nStopping Agent Listener..."));
261
+ if (reconnectTimer)
262
+ clearTimeout(reconnectTimer);
263
+ if (heartbeatTimer)
264
+ clearInterval(heartbeatTimer);
265
+ process.exit(0);
266
+ });
267
+ }));