@spekn/cli 1.0.2 → 1.0.5

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 (39) hide show
  1. package/dist/main.js +118 -52
  2. package/dist/resources/prompts/repo-sync-analysis.prompt.md +1 -1
  3. package/dist/tui/index.mjs +4745 -537
  4. package/dist/tui/prompts/spec-creation-system.prompt.md +2 -2
  5. package/dist/tui/prompts/spec-refinement-system.prompt.md +9 -0
  6. package/package.json +3 -3
  7. package/dist/tui/chunk-4WEASLXY.mjs +0 -3444
  8. package/dist/tui/chunk-755CADEG.mjs +0 -3401
  9. package/dist/tui/chunk-BUJQVTY5.mjs +0 -3409
  10. package/dist/tui/chunk-BZKKMGFB.mjs +0 -1959
  11. package/dist/tui/chunk-DJYOBCNM.mjs +0 -3159
  12. package/dist/tui/chunk-GTFTFDY4.mjs +0 -3417
  13. package/dist/tui/chunk-IMEBD2KA.mjs +0 -3444
  14. package/dist/tui/chunk-IX6DR5SW.mjs +0 -3433
  15. package/dist/tui/chunk-JKFOY4IF.mjs +0 -2003
  16. package/dist/tui/chunk-OXXZ3O5L.mjs +0 -3378
  17. package/dist/tui/chunk-SHJNIAAJ.mjs +0 -1697
  18. package/dist/tui/chunk-V4SNDRUS.mjs +0 -1666
  19. package/dist/tui/chunk-VXVHNZST.mjs +0 -1666
  20. package/dist/tui/chunk-WCTSFKTA.mjs +0 -3459
  21. package/dist/tui/chunk-X2XP5ACW.mjs +0 -3443
  22. package/dist/tui/chunk-YUYJ7VBG.mjs +0 -2029
  23. package/dist/tui/chunk-ZM3EI5IA.mjs +0 -3384
  24. package/dist/tui/chunk-ZYOX64HP.mjs +0 -1653
  25. package/dist/tui/use-session-store-63YUGUFA.mjs +0 -8
  26. package/dist/tui/use-session-store-ACO2SMJC.mjs +0 -8
  27. package/dist/tui/use-session-store-BVFDAWOB.mjs +0 -8
  28. package/dist/tui/use-session-store-DJIZ3FQZ.mjs +0 -9
  29. package/dist/tui/use-session-store-EAIQA4UG.mjs +0 -9
  30. package/dist/tui/use-session-store-EFBAXC3G.mjs +0 -8
  31. package/dist/tui/use-session-store-FJOR4KTG.mjs +0 -8
  32. package/dist/tui/use-session-store-IJE5KVOC.mjs +0 -8
  33. package/dist/tui/use-session-store-KGAFXCKI.mjs +0 -8
  34. package/dist/tui/use-session-store-KS4DPNDY.mjs +0 -8
  35. package/dist/tui/use-session-store-MMHJENNL.mjs +0 -8
  36. package/dist/tui/use-session-store-OZ6HC4I2.mjs +0 -9
  37. package/dist/tui/use-session-store-PTMWISNJ.mjs +0 -8
  38. package/dist/tui/use-session-store-VCDECQMW.mjs +0 -8
  39. package/dist/tui/use-session-store-VOK5ML5J.mjs +0 -9
@@ -1,3443 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/store/use-session-store.ts
5
- import { create as create6 } from "zustand";
6
- import { subscribeWithSelector as subscribeWithSelector6 } from "zustand/middleware";
7
-
8
- // src/utils/project-context.ts
9
- import fs from "fs";
10
- import os from "os";
11
- import path from "path";
12
- var LOCAL_CONTEXT_FILE = ".spekn";
13
- var GLOBAL_CONTEXT_PATH = path.join(os.homedir(), ".spekn", "context.json");
14
- var GLOBAL_CONFIG_PATH = path.join(os.homedir(), ".spekn", "config.json");
15
- var GLOBAL_ERROR_LOG_PATH = "~/.spekn/error.log";
16
- var DEFAULT_GLOBAL_CONFIG = {
17
- logging: {
18
- enabled: false,
19
- path: GLOBAL_ERROR_LOG_PATH,
20
- level: "info"
21
- }
22
- };
23
- var LOG_LEVEL_RANK = {
24
- debug: 10,
25
- info: 20,
26
- warn: 30,
27
- error: 40
28
- };
29
- function loadContextFile(filePath) {
30
- try {
31
- const raw = fs.readFileSync(filePath, "utf-8");
32
- const parsed = JSON.parse(raw);
33
- if (!parsed || typeof parsed !== "object") return null;
34
- return parsed;
35
- } catch {
36
- return null;
37
- }
38
- }
39
- __name(loadContextFile, "loadContextFile");
40
- function loadGlobalContextData() {
41
- try {
42
- const raw = fs.readFileSync(GLOBAL_CONTEXT_PATH, "utf-8");
43
- const parsed = JSON.parse(raw);
44
- if (!parsed || typeof parsed !== "object") return null;
45
- return parsed;
46
- } catch {
47
- return null;
48
- }
49
- }
50
- __name(loadGlobalContextData, "loadGlobalContextData");
51
- function getGlobalProjects(global) {
52
- if (!global) return [];
53
- return Array.isArray(global.projects) ? global.projects : [];
54
- }
55
- __name(getGlobalProjects, "getGlobalProjects");
56
- function isRoot(dirPath) {
57
- return path.dirname(dirPath) === dirPath;
58
- }
59
- __name(isRoot, "isRoot");
60
- function findNearestLocalContextFile(startDir = process.cwd()) {
61
- let current = path.resolve(startDir);
62
- while (true) {
63
- const candidate = path.join(current, LOCAL_CONTEXT_FILE);
64
- if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
65
- return candidate;
66
- }
67
- if (isRoot(current)) return null;
68
- current = path.dirname(current);
69
- }
70
- }
71
- __name(findNearestLocalContextFile, "findNearestLocalContextFile");
72
- function resolveContextWorkspaceRoot(input) {
73
- const fallback = path.resolve(input?.fallbackDir ?? process.cwd());
74
- try {
75
- const raw = fs.readFileSync(GLOBAL_CONTEXT_PATH, "utf-8");
76
- const global = JSON.parse(raw);
77
- const projects = getGlobalProjects(global);
78
- const selectedProjectId = input?.projectId ?? global.lastUsedProjectId;
79
- const selected = projects.find((entry) => entry?.id === selectedProjectId) ?? projects.find((entry) => Array.isArray(entry?.repoPaths) && entry.repoPaths.length > 0);
80
- const repoPaths = Array.isArray(selected?.repoPaths) ? selected.repoPaths : [];
81
- const existingPath = repoPaths.find((repoPath) => {
82
- try {
83
- return fs.existsSync(repoPath);
84
- } catch {
85
- return false;
86
- }
87
- });
88
- const resolvedPath = existingPath ?? repoPaths[0];
89
- if (typeof resolvedPath === "string" && resolvedPath.trim().length > 0) {
90
- return path.resolve(resolvedPath);
91
- }
92
- } catch {
93
- }
94
- return fallback;
95
- }
96
- __name(resolveContextWorkspaceRoot, "resolveContextWorkspaceRoot");
97
- function resolveDeclaredContext(input) {
98
- const localPath = input.repoPath ? path.join(path.resolve(input.repoPath), LOCAL_CONTEXT_FILE) : findNearestLocalContextFile();
99
- const local = localPath ? loadContextFile(localPath) : null;
100
- const global = loadGlobalContextData();
101
- const globalProjectId = global?.lastUsedProjectId;
102
- const globalProjectOrganizationId = (globalProjectId ? getGlobalProjects(global).find((project) => project.id === globalProjectId)?.organizationId : void 0) ?? global?.defaultOrganizationId;
103
- const projectId = input.explicitProjectId ?? local?.projectId ?? globalProjectId;
104
- const organizationId = input.explicitOrganizationId ?? local?.organizationId ?? (projectId ? getGlobalProjects(global).find((project) => project.id === projectId)?.organizationId : void 0) ?? globalProjectOrganizationId ?? input.credentialsOrganizationId;
105
- return {
106
- projectId,
107
- organizationId
108
- };
109
- }
110
- __name(resolveDeclaredContext, "resolveDeclaredContext");
111
- function saveLocalContext(repoPath, context) {
112
- const filePath = path.join(path.resolve(repoPath), LOCAL_CONTEXT_FILE);
113
- const content = {
114
- projectId: context.projectId,
115
- organizationId: context.organizationId,
116
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
117
- };
118
- fs.writeFileSync(filePath, JSON.stringify(content, null, 2) + "\n", "utf-8");
119
- }
120
- __name(saveLocalContext, "saveLocalContext");
121
- function saveGlobalContext(repoPathInput, context) {
122
- const dirPath = path.dirname(GLOBAL_CONTEXT_PATH);
123
- fs.mkdirSync(dirPath, {
124
- recursive: true,
125
- mode: 448
126
- });
127
- const existing = loadGlobalContextData();
128
- const now = (/* @__PURE__ */ new Date()).toISOString();
129
- const repoPath = path.resolve(repoPathInput);
130
- const organizationId = context.organizationId ?? existing?.defaultOrganizationId ?? "";
131
- const previousProjects = getGlobalProjects(existing);
132
- const updatedProjects = previousProjects.map((project) => project.id === context.projectId ? {
133
- ...project,
134
- organizationId: organizationId || project.organizationId,
135
- lastUsed: now,
136
- repoPaths: Array.from(/* @__PURE__ */ new Set([
137
- ...project.repoPaths ?? [],
138
- repoPath
139
- ]))
140
- } : project);
141
- if (!updatedProjects.some((project) => project.id === context.projectId) && organizationId) {
142
- updatedProjects.unshift({
143
- id: context.projectId,
144
- organizationId,
145
- lastUsed: now,
146
- repoPaths: [
147
- repoPath
148
- ]
149
- });
150
- }
151
- const content = {
152
- defaultOrganizationId: organizationId || existing?.defaultOrganizationId,
153
- projects: updatedProjects.slice(0, 10),
154
- lastUsedProjectId: context.projectId,
155
- preferences: existing?.preferences,
156
- repoSync: existing?.repoSync,
157
- updatedAt: now
158
- };
159
- fs.writeFileSync(GLOBAL_CONTEXT_PATH, JSON.stringify(content, null, 2) + "\n", {
160
- encoding: "utf-8",
161
- mode: 384
162
- });
163
- }
164
- __name(saveGlobalContext, "saveGlobalContext");
165
- function saveGlobalContextSelectionOnly(context) {
166
- const dirPath = path.dirname(GLOBAL_CONTEXT_PATH);
167
- fs.mkdirSync(dirPath, {
168
- recursive: true,
169
- mode: 448
170
- });
171
- const existing = loadGlobalContextData();
172
- const now = (/* @__PURE__ */ new Date()).toISOString();
173
- const organizationId = context.organizationId ?? existing?.defaultOrganizationId ?? "";
174
- const previousProjects = getGlobalProjects(existing);
175
- const updatedProjects = previousProjects.map((project) => project.id === context.projectId ? {
176
- ...project,
177
- organizationId: organizationId || project.organizationId,
178
- lastUsed: now
179
- } : project);
180
- if (!updatedProjects.some((project) => project.id === context.projectId) && organizationId) {
181
- updatedProjects.unshift({
182
- id: context.projectId,
183
- organizationId,
184
- lastUsed: now,
185
- repoPaths: []
186
- });
187
- }
188
- const content = {
189
- defaultOrganizationId: organizationId || existing?.defaultOrganizationId,
190
- projects: updatedProjects.slice(0, 10),
191
- lastUsedProjectId: context.projectId,
192
- preferences: existing?.preferences,
193
- repoSync: existing?.repoSync,
194
- updatedAt: now
195
- };
196
- fs.writeFileSync(GLOBAL_CONTEXT_PATH, JSON.stringify(content, null, 2) + "\n", {
197
- encoding: "utf-8",
198
- mode: 384
199
- });
200
- }
201
- __name(saveGlobalContextSelectionOnly, "saveGlobalContextSelectionOnly");
202
- function ensureGitignoreHasSpekn(repoPath) {
203
- const gitignorePath = path.join(path.resolve(repoPath), ".gitignore");
204
- const entry = ".spekn";
205
- if (!fs.existsSync(gitignorePath)) {
206
- fs.writeFileSync(gitignorePath, `${entry}
207
- `, "utf-8");
208
- return;
209
- }
210
- const content = fs.readFileSync(gitignorePath, "utf-8");
211
- const lines = content.split(/\r?\n/);
212
- if (lines.some((line) => line.trim() === entry)) return;
213
- const needsNewline = content.length > 0 && !content.endsWith("\n");
214
- const toAppend = `${needsNewline ? "\n" : ""}${entry}
215
- `;
216
- fs.appendFileSync(gitignorePath, toAppend, "utf-8");
217
- }
218
- __name(ensureGitignoreHasSpekn, "ensureGitignoreHasSpekn");
219
- function hasLocalContext(repoPath) {
220
- const startDir = repoPath ? path.resolve(repoPath) : process.cwd();
221
- return findNearestLocalContextFile(startDir) !== null;
222
- }
223
- __name(hasLocalContext, "hasLocalContext");
224
- function persistProjectContext(repoPath, context) {
225
- saveLocalContext(repoPath, context);
226
- saveGlobalContext(repoPath, context);
227
- ensureGitignoreHasSpekn(repoPath);
228
- }
229
- __name(persistProjectContext, "persistProjectContext");
230
- function persistSelectedProjectContext(context) {
231
- saveGlobalContextSelectionOnly(context);
232
- }
233
- __name(persistSelectedProjectContext, "persistSelectedProjectContext");
234
- function persistProjectContextWithoutRepoPath(repoPath, context) {
235
- saveLocalContext(repoPath, context);
236
- saveGlobalContextSelectionOnly(context);
237
- ensureGitignoreHasSpekn(repoPath);
238
- }
239
- __name(persistProjectContextWithoutRepoPath, "persistProjectContextWithoutRepoPath");
240
- function loadGlobalContextConfig() {
241
- try {
242
- const raw = fs.readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
243
- const parsed = JSON.parse(raw);
244
- const levelCandidate = parsed?.logging?.level;
245
- const level = levelCandidate === "debug" || levelCandidate === "info" || levelCandidate === "warn" || levelCandidate === "error" ? levelCandidate : DEFAULT_GLOBAL_CONFIG.logging.level;
246
- return {
247
- logging: {
248
- enabled: typeof parsed?.logging?.enabled === "boolean" ? parsed.logging.enabled : DEFAULT_GLOBAL_CONFIG.logging.enabled,
249
- path: typeof parsed?.logging?.path === "string" && parsed.logging.path.trim().length > 0 ? parsed.logging.path : DEFAULT_GLOBAL_CONFIG.logging.path,
250
- level
251
- }
252
- };
253
- } catch {
254
- return DEFAULT_GLOBAL_CONFIG;
255
- }
256
- }
257
- __name(loadGlobalContextConfig, "loadGlobalContextConfig");
258
- function saveGlobalContextConfig(config) {
259
- const dirPath = path.dirname(GLOBAL_CONFIG_PATH);
260
- fs.mkdirSync(dirPath, {
261
- recursive: true,
262
- mode: 448
263
- });
264
- fs.writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", {
265
- encoding: "utf-8",
266
- mode: 384
267
- });
268
- }
269
- __name(saveGlobalContextConfig, "saveGlobalContextConfig");
270
- function ensureGlobalContextConfig() {
271
- const config = loadGlobalContextConfig();
272
- if (!fs.existsSync(GLOBAL_CONFIG_PATH)) {
273
- saveGlobalContextConfig(config);
274
- }
275
- return config;
276
- }
277
- __name(ensureGlobalContextConfig, "ensureGlobalContextConfig");
278
- function expandHomePath(filePath) {
279
- if (filePath === "~") return os.homedir();
280
- if (filePath.startsWith("~/")) {
281
- return path.join(os.homedir(), filePath.slice(2));
282
- }
283
- return filePath;
284
- }
285
- __name(expandHomePath, "expandHomePath");
286
- function appendGlobalStructuredLog(input) {
287
- try {
288
- const config = ensureGlobalContextConfig();
289
- if (!config.logging.enabled) return;
290
- if (LOG_LEVEL_RANK[input.level] < LOG_LEVEL_RANK[config.logging.level]) return;
291
- const logPath = path.resolve(expandHomePath(config.logging.path));
292
- const dirPath = path.dirname(logPath);
293
- fs.mkdirSync(dirPath, {
294
- recursive: true,
295
- mode: 448
296
- });
297
- const payload = {
298
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
299
- source: input.source,
300
- level: input.level,
301
- message: input.message,
302
- details: input.details ?? {}
303
- };
304
- fs.appendFileSync(logPath, `${JSON.stringify(payload)}
305
- `, {
306
- encoding: "utf-8",
307
- mode: 384
308
- });
309
- } catch {
310
- }
311
- }
312
- __name(appendGlobalStructuredLog, "appendGlobalStructuredLog");
313
- function appendGlobalErrorLog(input) {
314
- appendGlobalStructuredLog({
315
- source: input.source,
316
- level: "error",
317
- message: input.message,
318
- details: input.details
319
- });
320
- }
321
- __name(appendGlobalErrorLog, "appendGlobalErrorLog");
322
-
323
- // src/auth/credentials-store.ts
324
- import * as fs2 from "fs";
325
- import * as os2 from "os";
326
- import * as path2 from "path";
327
- import { z } from "zod";
328
- var CliCredentialsSchema = z.object({
329
- accessToken: z.string(),
330
- refreshToken: z.string(),
331
- expiresAt: z.number(),
332
- keycloakUrl: z.string(),
333
- realm: z.string(),
334
- organizationId: z.string().optional(),
335
- user: z.object({
336
- sub: z.string(),
337
- email: z.string(),
338
- name: z.string().optional()
339
- }).optional()
340
- });
341
- var TokenResponseSchema = z.object({
342
- access_token: z.string(),
343
- refresh_token: z.string(),
344
- expires_in: z.number()
345
- });
346
- var CredentialsStore = class {
347
- static {
348
- __name(this, "CredentialsStore");
349
- }
350
- configDir;
351
- credentialsPath;
352
- constructor(configDir) {
353
- this.configDir = configDir ?? path2.join(os2.homedir(), ".spekn");
354
- this.credentialsPath = path2.join(this.configDir, "credentials.json");
355
- }
356
- load() {
357
- try {
358
- const raw = fs2.readFileSync(this.credentialsPath, "utf-8");
359
- return CliCredentialsSchema.parse(JSON.parse(raw));
360
- } catch {
361
- return null;
362
- }
363
- }
364
- save(creds) {
365
- fs2.mkdirSync(this.configDir, {
366
- recursive: true,
367
- mode: 448
368
- });
369
- const json = JSON.stringify(creds, null, 2);
370
- fs2.writeFileSync(this.credentialsPath, json, {
371
- encoding: "utf-8",
372
- mode: 384
373
- });
374
- }
375
- clear() {
376
- try {
377
- fs2.rmSync(this.credentialsPath);
378
- } catch (err) {
379
- if (err.code !== "ENOENT") {
380
- throw err;
381
- }
382
- }
383
- }
384
- async getValidToken() {
385
- const creds = this.load();
386
- if (creds === null) {
387
- return null;
388
- }
389
- const bufferMs = 3e4;
390
- if (Date.now() + bufferMs < creds.expiresAt) {
391
- return creds.accessToken;
392
- }
393
- try {
394
- const tokenUrl = `${creds.keycloakUrl}/realms/${creds.realm}/protocol/openid-connect/token`;
395
- const body = new URLSearchParams({
396
- grant_type: "refresh_token",
397
- client_id: "spekn-cli",
398
- refresh_token: creds.refreshToken
399
- });
400
- const res = await fetch(tokenUrl, {
401
- method: "POST",
402
- body,
403
- headers: {
404
- "Content-Type": "application/x-www-form-urlencoded"
405
- }
406
- });
407
- if (!res.ok) {
408
- return null;
409
- }
410
- const data = TokenResponseSchema.parse(await res.json());
411
- const updated = {
412
- ...creds,
413
- accessToken: data.access_token,
414
- refreshToken: data.refresh_token,
415
- expiresAt: Date.now() + data.expires_in * 1e3
416
- };
417
- this.save(updated);
418
- return updated.accessToken;
419
- } catch {
420
- return null;
421
- }
422
- }
423
- };
424
-
425
- // src/auth/jwt.ts
426
- function decodeJwtPayload(token) {
427
- try {
428
- const parts = token.split(".");
429
- if (parts.length !== 3) {
430
- return null;
431
- }
432
- const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
433
- const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
434
- const json = Buffer.from(padded, "base64").toString("utf-8");
435
- return JSON.parse(json);
436
- } catch {
437
- return null;
438
- }
439
- }
440
- __name(decodeJwtPayload, "decodeJwtPayload");
441
-
442
- // src/services/cli-runner.ts
443
- import { spawn } from "child_process";
444
- var CliRunner = class {
445
- static {
446
- __name(this, "CliRunner");
447
- }
448
- apiUrl;
449
- credentialsStore = new CredentialsStore();
450
- constructor(apiUrl) {
451
- this.apiUrl = apiUrl;
452
- }
453
- resolveCliEntry() {
454
- const cliEntry = process.argv[1];
455
- return typeof cliEntry === "string" && cliEntry.length > 0 ? cliEntry : null;
456
- }
457
- buildCliEnv(options) {
458
- const env = {
459
- ...process.env
460
- };
461
- delete env.SPEKN_ORGANIZATION_ID;
462
- if (options?.organizationId) {
463
- env.SPEKN_ORGANIZATION_ID = options.organizationId;
464
- }
465
- if (options?.interactionEnabled) {
466
- env.SPEKN_INTERACTION_MODE = "json-stdio";
467
- } else {
468
- delete env.SPEKN_INTERACTION_MODE;
469
- }
470
- return env;
471
- }
472
- async respondToInteraction(child, request, onProgress, requestInteraction) {
473
- const requestPromise = requestInteraction?.(request);
474
- const value = await Promise.race([
475
- requestPromise,
476
- new Promise((resolve) => setTimeout(() => resolve(void 0), 12e4))
477
- ]);
478
- if (!child.stdin || child.stdin.destroyed) return;
479
- if (value === "skip") {
480
- child.stdin.write(`${JSON.stringify({
481
- id: request.id,
482
- skip: true
483
- })}
484
- `);
485
- return;
486
- }
487
- const allowed = new Set(request.options.map((option) => option?.value).filter((optionValue) => typeof optionValue === "string"));
488
- if (typeof value === "string" && allowed.has(value)) {
489
- child.stdin.write(`${JSON.stringify({
490
- id: request.id,
491
- value
492
- })}
493
- `);
494
- return;
495
- }
496
- const fallbackValue = request.options[0]?.value;
497
- if (typeof fallbackValue === "string") {
498
- onProgress?.(`[interaction] Auto-selecting default: ${fallbackValue}`);
499
- child.stdin.write(`${JSON.stringify({
500
- id: request.id,
501
- value: fallbackValue
502
- })}
503
- `);
504
- return;
505
- }
506
- child.stdin.write(`${JSON.stringify({
507
- id: request.id
508
- })}
509
- `);
510
- }
511
- async runCliCommand(args, options) {
512
- const cliEntry = this.resolveCliEntry();
513
- if (!cliEntry) {
514
- return {
515
- success: false,
516
- exitCode: 1,
517
- stdoutLines: [],
518
- stderrLines: [],
519
- outputLines: [],
520
- output: "Could not resolve CLI entrypoint.",
521
- error: "Could not resolve CLI entrypoint."
522
- };
523
- }
524
- const includeAuthToken = options?.includeAuthToken !== false;
525
- const token = includeAuthToken ? await this.credentialsStore.getValidToken().catch(() => null) : null;
526
- const env = this.buildCliEnv({
527
- organizationId: options?.organizationId,
528
- interactionEnabled: Boolean(options?.requestInteraction)
529
- });
530
- if (includeAuthToken && token) {
531
- env.SPEKN_AUTH_TOKEN = token;
532
- } else if (!includeAuthToken) {
533
- delete env.SPEKN_AUTH_TOKEN;
534
- }
535
- const finalArgs = [
536
- cliEntry,
537
- ...args
538
- ];
539
- const stdoutLines = [];
540
- const stderrLines = [];
541
- const outputLines = [];
542
- const maxLines = options?.maxOutputLines ?? 250;
543
- let stdoutBuffer = "";
544
- let stderrBuffer = "";
545
- const pushLine = /* @__PURE__ */ __name((line, stream) => {
546
- const target = stream === "stdout" ? stdoutLines : stderrLines;
547
- target.push(line);
548
- outputLines.push(line);
549
- if (target.length > maxLines) target.shift();
550
- if (outputLines.length > maxLines) outputLines.shift();
551
- options?.onProgress?.(line);
552
- }, "pushLine");
553
- const processLine = /* @__PURE__ */ __name((line, stream, child) => {
554
- const trimmed = line.trim();
555
- if (!trimmed) return;
556
- const activityMarker = "[spekn-activity] ";
557
- const activityIdx = trimmed.indexOf(activityMarker);
558
- if (activityIdx >= 0) {
559
- try {
560
- const parsed = JSON.parse(trimmed.slice(activityIdx + activityMarker.length));
561
- if (parsed.type === "spekn.activity") {
562
- options?.onActivity?.(parsed);
563
- return;
564
- }
565
- } catch {
566
- }
567
- }
568
- const marker = "[spekn-interaction] ";
569
- const markerIndex = trimmed.indexOf(marker);
570
- if (options?.requestInteraction && markerIndex >= 0) {
571
- const payloadRaw = trimmed.slice(markerIndex + marker.length);
572
- let payload = null;
573
- try {
574
- payload = JSON.parse(payloadRaw);
575
- } catch {
576
- payload = null;
577
- }
578
- if (payload?.type === "spekn.interaction.request" && typeof payload.id === "string" && Array.isArray(payload.options)) {
579
- options.onProgress?.(`[interaction] ${payload.title ?? "Selection required"}`);
580
- const request = {
581
- id: payload.id,
582
- title: payload.title ?? "Selection required",
583
- message: payload.message ?? "Choose an option",
584
- options: payload.options,
585
- allowSkip: payload.allowSkip === true
586
- };
587
- void this.respondToInteraction(child, request, options.onProgress, options.requestInteraction).catch(() => {
588
- if (!child.stdin || child.stdin.destroyed) return;
589
- child.stdin.write(`${JSON.stringify({
590
- id: request.id
591
- })}
592
- `);
593
- });
594
- return;
595
- }
596
- }
597
- pushLine(trimmed, stream);
598
- }, "processLine");
599
- try {
600
- const child = spawn(process.execPath, finalArgs, {
601
- cwd: options?.cwd ?? process.cwd(),
602
- env,
603
- stdio: [
604
- "pipe",
605
- "pipe",
606
- "pipe"
607
- ]
608
- });
609
- const onData = /* @__PURE__ */ __name((stream, data) => {
610
- const chunk = String(data);
611
- if (stream === "stdout") {
612
- stdoutBuffer += chunk;
613
- } else {
614
- stderrBuffer += chunk;
615
- }
616
- const buffer = stream === "stdout" ? stdoutBuffer : stderrBuffer;
617
- const lines = buffer.split(/\r?\n|\r/);
618
- const remainder = lines.pop() ?? "";
619
- if (stream === "stdout") {
620
- stdoutBuffer = remainder;
621
- } else {
622
- stderrBuffer = remainder;
623
- }
624
- for (const line of lines) {
625
- processLine(line, stream, child);
626
- }
627
- }, "onData");
628
- child.stdout?.on("data", (data) => onData("stdout", data));
629
- child.stderr?.on("data", (data) => onData("stderr", data));
630
- const exitCode = await new Promise((resolve, reject) => {
631
- child.on("error", reject);
632
- child.on("close", (code) => resolve(code ?? 1));
633
- });
634
- if (stdoutBuffer.trim().length > 0) {
635
- processLine(stdoutBuffer, "stdout", child);
636
- }
637
- if (stderrBuffer.trim().length > 0) {
638
- processLine(stderrBuffer, "stderr", child);
639
- }
640
- return {
641
- success: exitCode === 0,
642
- exitCode,
643
- stdoutLines,
644
- stderrLines,
645
- outputLines,
646
- output: outputLines.join("\n")
647
- };
648
- } catch (error) {
649
- const message = error instanceof Error ? error.message : String(error);
650
- return {
651
- success: false,
652
- exitCode: 1,
653
- stdoutLines,
654
- stderrLines,
655
- outputLines,
656
- output: message,
657
- error: message
658
- };
659
- }
660
- }
661
- async runCliJson(args, cwd, organizationId) {
662
- const result = await this.runCliCommand(args, {
663
- cwd,
664
- organizationId,
665
- includeAuthToken: true
666
- });
667
- if (!result.success && result.output.trim().length === 0) {
668
- return {
669
- ok: false,
670
- error: result.error ?? "CLI command failed."
671
- };
672
- }
673
- const output = result.stdoutLines.join("\n").trim() || result.output.trim();
674
- const jsonStart = output.indexOf("{");
675
- if (jsonStart === -1) {
676
- return {
677
- ok: false,
678
- error: output || "Command produced no JSON output."
679
- };
680
- }
681
- try {
682
- const parsed = JSON.parse(output.slice(jsonStart));
683
- return {
684
- ok: true,
685
- value: parsed
686
- };
687
- } catch (error) {
688
- const message = error instanceof Error ? error.message : String(error);
689
- return {
690
- ok: false,
691
- error: message
692
- };
693
- }
694
- }
695
- };
696
-
697
- // src/services/auth-service.ts
698
- var AuthService = class {
699
- static {
700
- __name(this, "AuthService");
701
- }
702
- credentialsStore = new CredentialsStore();
703
- cliRunner;
704
- constructor(apiUrl) {
705
- this.cliRunner = new CliRunner(apiUrl);
706
- }
707
- async checkAuthentication() {
708
- try {
709
- const token = await this.credentialsStore.getValidToken();
710
- return token || null;
711
- } catch {
712
- return null;
713
- }
714
- }
715
- async authenticateViaCli(onProgress) {
716
- const result = await this.cliRunner.runCliCommand([
717
- "auth",
718
- "login"
719
- ], {
720
- cwd: process.cwd(),
721
- includeAuthToken: false,
722
- onProgress
723
- });
724
- return result.success;
725
- }
726
- extractUserEmail(token) {
727
- try {
728
- const claims = decodeJwtPayload(token);
729
- return typeof claims?.["email"] === "string" ? claims["email"] : void 0;
730
- } catch {
731
- return void 0;
732
- }
733
- }
734
- extractTokenExpiry(token) {
735
- try {
736
- const claims = decodeJwtPayload(token);
737
- if (typeof claims?.["exp"] === "number") {
738
- return claims["exp"] * 1e3;
739
- }
740
- return void 0;
741
- } catch {
742
- return void 0;
743
- }
744
- }
745
- extractPermissions(token) {
746
- const claims = decodeJwtPayload(token);
747
- return Array.isArray(claims?.permissions) ? claims.permissions.filter((item) => typeof item === "string") : [];
748
- }
749
- };
750
-
751
- // src/shared-enums.ts
752
- var OrganizationPlan = {
753
- FREE: "free",
754
- PRO: "pro",
755
- TEAM: "team",
756
- ENTERPRISE: "enterprise"
757
- };
758
- var WorkflowPhase = {
759
- SPECIFY: "specify",
760
- CLARIFY: "clarify",
761
- PLAN: "plan",
762
- IMPLEMENT: "implement",
763
- VERIFY: "verify",
764
- COMPLETE: "complete"
765
- };
766
-
767
- // src/services/client.ts
768
- import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
769
-
770
- // src/utils/trpc-url.ts
771
- function normalizeTrpcUrl(apiUrl) {
772
- if (apiUrl.endsWith("/trpc")) {
773
- return apiUrl;
774
- }
775
- if (apiUrl.endsWith("/")) {
776
- return `${apiUrl}trpc`;
777
- }
778
- return `${apiUrl}/trpc`;
779
- }
780
- __name(normalizeTrpcUrl, "normalizeTrpcUrl");
781
-
782
- // src/services/client.ts
783
- function createApiClient(apiUrl, token, organizationId) {
784
- return createTRPCProxyClient({
785
- links: [
786
- httpBatchLink({
787
- url: normalizeTrpcUrl(apiUrl),
788
- headers: {
789
- authorization: token ? `Bearer ${token}` : "",
790
- "x-organization-id": organizationId
791
- }
792
- })
793
- ]
794
- });
795
- }
796
- __name(createApiClient, "createApiClient");
797
-
798
- // src/services/bootstrap-service.ts
799
- function normalizePlan(raw) {
800
- if (raw === OrganizationPlan.PRO) return OrganizationPlan.PRO;
801
- if (raw === OrganizationPlan.TEAM) return OrganizationPlan.TEAM;
802
- if (raw === OrganizationPlan.ENTERPRISE) return OrganizationPlan.ENTERPRISE;
803
- return OrganizationPlan.FREE;
804
- }
805
- __name(normalizePlan, "normalizePlan");
806
- function normalizeRole(raw) {
807
- if (raw === "owner" || raw === "admin" || raw === "member" || raw === "viewer") {
808
- return raw;
809
- }
810
- return "member";
811
- }
812
- __name(normalizeRole, "normalizeRole");
813
- var BootstrapService = class {
814
- static {
815
- __name(this, "BootstrapService");
816
- }
817
- apiUrl;
818
- credentialsStore = new CredentialsStore();
819
- authService;
820
- constructor(apiUrl) {
821
- this.apiUrl = apiUrl;
822
- this.authService = new AuthService(apiUrl);
823
- }
824
- async bootstrap(projectIdArg) {
825
- const token = await this.credentialsStore.getValidToken();
826
- if (!token) {
827
- throw new Error("No valid credentials. Run `spekn auth login` first.");
828
- }
829
- const permissions = this.authService.extractPermissions(token);
830
- const stored = this.credentialsStore.load();
831
- const declared = resolveDeclaredContext({
832
- explicitProjectId: projectIdArg,
833
- repoPath: process.cwd(),
834
- credentialsOrganizationId: stored?.organizationId,
835
- envOrganizationId: process.env.SPEKN_ORGANIZATION_ID
836
- });
837
- if (!declared.projectId) {
838
- throw new Error("PROJECT_CONTEXT_REQUIRED");
839
- }
840
- const fallbackOrg = declared.organizationId ?? "";
841
- const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
842
- const orgs = await bootstrapClient.organization.list.query();
843
- if (orgs.length === 0) {
844
- throw new Error("No organization membership found for this account.");
845
- }
846
- const org = orgs.find((candidate) => candidate.id === fallbackOrg) ?? orgs[0];
847
- const organizationId = org.id;
848
- const client2 = createApiClient(this.apiUrl, token, organizationId);
849
- const projects = await client2.project.list.query({
850
- limit: 20,
851
- offset: 0
852
- });
853
- if (projects.length === 0) {
854
- throw new Error("ONBOARDING_REQUIRED");
855
- }
856
- const project = projects.find((candidate) => candidate.id === declared.projectId);
857
- if (!project) {
858
- throw new Error("ONBOARDING_REQUIRED");
859
- }
860
- const repoPath = resolveContextWorkspaceRoot({
861
- projectId: project.id,
862
- fallbackDir: process.cwd()
863
- });
864
- return {
865
- boot: {
866
- apiUrl: this.apiUrl,
867
- organizationId,
868
- organizationName: org.name,
869
- role: normalizeRole(org.role),
870
- plan: normalizePlan(org.plan),
871
- projectId: project.id,
872
- projectName: project.name,
873
- repoPath,
874
- permissions
875
- },
876
- client: client2
877
- };
878
- }
879
- hasDeclaredProjectContext(projectIdArg) {
880
- const stored = this.credentialsStore.load();
881
- const declared = resolveDeclaredContext({
882
- explicitProjectId: projectIdArg,
883
- repoPath: process.cwd(),
884
- credentialsOrganizationId: stored?.organizationId,
885
- envOrganizationId: process.env.SPEKN_ORGANIZATION_ID
886
- });
887
- return Boolean(declared.projectId);
888
- }
889
- async loadWorkflowSummary(client2, projectId) {
890
- const states = await client2.workflowState.listByProject.query({
891
- projectId
892
- });
893
- const first = Array.isArray(states) && states.length > 0 ? states[0] : null;
894
- const currentPhase = first?.currentPhase ?? null;
895
- const blockedCount = Array.isArray(states) ? states.filter((state) => state.specificationLockStatus === "locked").length : 0;
896
- return {
897
- currentPhase,
898
- blockedCount,
899
- hasVerificationEvidence: Boolean(first?.hasVerificationEvidence),
900
- hasPlanningArtifacts: Boolean(first?.hasPlanningArtifacts)
901
- };
902
- }
903
- hasLocalProjectContext(repoPath) {
904
- return hasLocalContext(repoPath);
905
- }
906
- persistContext(organizationId, projectId) {
907
- persistSelectedProjectContext({
908
- organizationId,
909
- projectId
910
- });
911
- }
912
- };
913
-
914
- // src/services/bridge-service.ts
915
- import fs3 from "fs";
916
- import os3 from "os";
917
- import path3 from "path";
918
- import { spawn as spawn2 } from "child_process";
919
- var DEFAULT_BRIDGE_CONFIG = {
920
- port: 19550,
921
- pairing: null
922
- };
923
- function loadLocalBridgeConfig() {
924
- const configPath = path3.join(os3.homedir(), ".spekn", "bridge", "config.json");
925
- try {
926
- const raw = fs3.readFileSync(configPath, "utf-8");
927
- const parsed = JSON.parse(raw);
928
- return {
929
- port: typeof parsed.port === "number" ? parsed.port : DEFAULT_BRIDGE_CONFIG.port,
930
- pairing: parsed.pairing ?? DEFAULT_BRIDGE_CONFIG.pairing
931
- };
932
- } catch {
933
- return DEFAULT_BRIDGE_CONFIG;
934
- }
935
- }
936
- __name(loadLocalBridgeConfig, "loadLocalBridgeConfig");
937
- async function loadWebMcpChannels(port) {
938
- try {
939
- const res = await fetch(`http://127.0.0.1:${port}/webmcp/channels`);
940
- if (!res.ok) return [];
941
- const data = await res.json();
942
- return data.channels ?? [];
943
- } catch {
944
- return [];
945
- }
946
- }
947
- __name(loadWebMcpChannels, "loadWebMcpChannels");
948
- var BridgeService = class {
949
- static {
950
- __name(this, "BridgeService");
951
- }
952
- cliRunner;
953
- constructor(apiUrl) {
954
- this.cliRunner = new CliRunner(apiUrl);
955
- }
956
- async loadBridgeSummary(client2) {
957
- const [flag, devices, metrics] = await Promise.all([
958
- client2.bridge.getFeatureFlag.query().catch(() => ({
959
- enabled: false
960
- })),
961
- client2.bridge.listDevices.query().catch(() => []),
962
- client2.bridge.getMetrics.query().catch(() => ({
963
- connectedDevices: 0,
964
- authFailures: 0
965
- }))
966
- ]);
967
- return {
968
- featureEnabled: Boolean(flag.enabled),
969
- devices: Array.isArray(devices) ? devices.map((device) => ({
970
- id: device.id,
971
- name: device.name,
972
- status: device.status,
973
- isDefault: Boolean(device.isDefault),
974
- lastSeenAt: device.lastSeenAt
975
- })) : [],
976
- connectedDevices: Number(metrics.connectedDevices ?? 0),
977
- authFailures: Number(metrics.authFailures ?? 0)
978
- };
979
- }
980
- async loadLocalBridgeSummary() {
981
- const config = loadLocalBridgeConfig();
982
- let running = false;
983
- let uptimeSec;
984
- try {
985
- const response = await fetch(`http://127.0.0.1:${config.port}/health`);
986
- if (response.ok) {
987
- const payload = await response.json();
988
- running = true;
989
- uptimeSec = Number(payload.uptime ?? 0);
990
- }
991
- } catch {
992
- running = false;
993
- }
994
- return {
995
- paired: config.pairing !== null,
996
- deviceId: config.pairing?.deviceId,
997
- deviceName: config.pairing?.deviceName,
998
- port: config.port,
999
- running,
1000
- uptimeSec
1001
- };
1002
- }
1003
- startLocalBridgeDetached() {
1004
- const cliEntry = this.cliRunner.resolveCliEntry();
1005
- if (!cliEntry) return;
1006
- const args = [
1007
- cliEntry,
1008
- "bridge",
1009
- "start"
1010
- ];
1011
- const child = spawn2(process.execPath, args, {
1012
- detached: true,
1013
- stdio: "ignore"
1014
- });
1015
- child.unref();
1016
- }
1017
- async stopLocalBridge(configPort) {
1018
- const port = configPort ?? loadLocalBridgeConfig().port;
1019
- try {
1020
- await fetch(`http://127.0.0.1:${port}/shutdown`, {
1021
- method: "POST"
1022
- });
1023
- } catch {
1024
- }
1025
- }
1026
- async loadBridgeLogs(port, since) {
1027
- const p = port ?? loadLocalBridgeConfig().port;
1028
- try {
1029
- const url = since ? `http://127.0.0.1:${p}/logs?since=${since}` : `http://127.0.0.1:${p}/logs`;
1030
- const res = await fetch(url);
1031
- if (!res.ok) return [];
1032
- const data = await res.json();
1033
- return data.logs;
1034
- } catch {
1035
- return [];
1036
- }
1037
- }
1038
- };
1039
-
1040
- // src/services/decision-service.ts
1041
- var DecisionService = class {
1042
- static {
1043
- __name(this, "DecisionService");
1044
- }
1045
- async loadDecisions(client2, projectId) {
1046
- const result = await client2.decision.getAll.query({
1047
- projectId,
1048
- limit: 50,
1049
- offset: 0
1050
- });
1051
- const decisions = Array.isArray(result?.decisions) ? result.decisions : [];
1052
- return decisions.map((decision) => ({
1053
- id: decision.id,
1054
- title: decision.title,
1055
- status: decision.status,
1056
- decisionType: decision.decisionType,
1057
- specAnchor: decision.specAnchor,
1058
- createdAt: decision.createdAt
1059
- }));
1060
- }
1061
- async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1062
- await client2.decision.update.mutate({
1063
- projectId,
1064
- id: decisionId,
1065
- data: {
1066
- status,
1067
- rationale: reason || existingRationale
1068
- }
1069
- });
1070
- }
1071
- async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1072
- const deleteMutation = client2?.decision?.delete?.mutate;
1073
- if (typeof deleteMutation !== "function") {
1074
- throw new Error("Decision delete route is unavailable.");
1075
- }
1076
- await deleteMutation({
1077
- projectId,
1078
- id: decisionId,
1079
- mode
1080
- });
1081
- }
1082
- };
1083
-
1084
- // src/services/export-service.ts
1085
- var ExportService = class {
1086
- static {
1087
- __name(this, "ExportService");
1088
- }
1089
- apiUrl;
1090
- cliRunner;
1091
- constructor(apiUrl) {
1092
- this.apiUrl = apiUrl;
1093
- this.cliRunner = new CliRunner(apiUrl);
1094
- }
1095
- async previewExport(client2, projectId, format) {
1096
- const result = await client2.export.preview.query({
1097
- projectId,
1098
- formatId: format
1099
- });
1100
- return {
1101
- content: String(result.content ?? ""),
1102
- anchorCount: Number(result.anchorCount ?? 0),
1103
- specVersion: typeof result.specVersion === "string" ? result.specVersion : void 0,
1104
- warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
1105
- };
1106
- }
1107
- async generateExport(client2, projectId, format) {
1108
- const result = await client2.export.generate.mutate({
1109
- projectId,
1110
- formatId: format
1111
- });
1112
- return {
1113
- content: String(result.content ?? ""),
1114
- anchorCount: Number(result.anchorCount ?? 0),
1115
- specVersion: typeof result.specVersion === "string" ? result.specVersion : void 0,
1116
- warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
1117
- };
1118
- }
1119
- async discoverExportCapabilities(projectId, organizationId) {
1120
- const fallback = {
1121
- plan: "free",
1122
- modes: [
1123
- "global"
1124
- ],
1125
- formats: [
1126
- {
1127
- id: "agents-md"
1128
- },
1129
- {
1130
- id: "claude-md"
1131
- },
1132
- {
1133
- id: "cursorrules"
1134
- },
1135
- {
1136
- id: "gemini-md"
1137
- }
1138
- ]
1139
- };
1140
- const cliResult = await this.cliRunner.runCliJson([
1141
- "export",
1142
- "discover",
1143
- "--project",
1144
- projectId,
1145
- "--api-url",
1146
- this.apiUrl,
1147
- "--json"
1148
- ], void 0, organizationId);
1149
- if (!cliResult.ok) {
1150
- return fallback;
1151
- }
1152
- const result = cliResult.value;
1153
- const modes = Array.isArray(result?.modes) ? result.modes.filter((mode) => mode === "global" || mode === "scoped") : fallback.modes;
1154
- const formats = Array.isArray(result?.formats) ? result.formats.map((format) => {
1155
- if (format?.id !== "agents-md" && format?.id !== "claude-md" && format?.id !== "cursorrules" && format?.id !== "gemini-md") {
1156
- return null;
1157
- }
1158
- const formatModes = Array.isArray(format?.modes) ? format.modes.filter((mode) => mode === "global" || mode === "scoped") : void 0;
1159
- return {
1160
- id: format.id,
1161
- name: typeof format?.name === "string" ? format.name : void 0,
1162
- filename: typeof format?.filename === "string" ? format.filename : void 0,
1163
- modes: formatModes
1164
- };
1165
- }).filter((format) => format !== null) : fallback.formats;
1166
- return {
1167
- plan: result?.plan === "pro" || result?.plan === "team" || result?.plan === "enterprise" ? result.plan : "free",
1168
- modes: modes.length > 0 ? modes : fallback.modes,
1169
- formats: formats.length > 0 ? formats : fallback.formats
1170
- };
1171
- }
1172
- async exportStatus(projectId, format, options) {
1173
- const args = [
1174
- "export",
1175
- "status",
1176
- "--project",
1177
- projectId,
1178
- "--format",
1179
- format,
1180
- "--api-url",
1181
- this.apiUrl,
1182
- "--json"
1183
- ];
1184
- if (options?.mode) args.push("--mode", options.mode);
1185
- if (options?.scopePath) args.push("--scope", options.scopePath);
1186
- const cliResult = await this.cliRunner.runCliJson(args, void 0, options?.organizationId);
1187
- if (!cliResult.ok) {
1188
- return {
1189
- overall: "missing",
1190
- targets: []
1191
- };
1192
- }
1193
- const result = cliResult.value;
1194
- const overall = result?.overall === "diverged" || result?.overall === "outdated" || result?.overall === "up-to-date" ? result.overall : "missing";
1195
- const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1196
- const status = target?.status === "diverged" || target?.status === "outdated" || target?.status === "up-to-date" ? target.status : "missing";
1197
- const kind = target?.kind === "canonical" ? "canonical" : "entrypoint";
1198
- if (typeof target?.path !== "string") return null;
1199
- return {
1200
- path: target.path,
1201
- kind,
1202
- status
1203
- };
1204
- }).filter((target) => target !== null) : [];
1205
- return {
1206
- overall,
1207
- targets
1208
- };
1209
- }
1210
- async deliverExport(projectId, format, delivery, options) {
1211
- const args = [
1212
- "export",
1213
- "--project",
1214
- projectId,
1215
- "--format",
1216
- format,
1217
- "--delivery",
1218
- delivery,
1219
- "--api-url",
1220
- this.apiUrl,
1221
- "--json"
1222
- ];
1223
- if (options?.mode) args.push("--mode", options.mode);
1224
- if (options?.scopePath) args.push("--scope", options.scopePath);
1225
- const exportCwd = delivery === "download" ? resolveContextWorkspaceRoot({
1226
- projectId,
1227
- fallbackDir: process.cwd()
1228
- }) : process.cwd();
1229
- const cliResult = await this.cliRunner.runCliJson(args, exportCwd, options?.organizationId);
1230
- if (!cliResult.ok) {
1231
- throw new Error(cliResult.error);
1232
- }
1233
- const result = cliResult.value;
1234
- if (delivery === "commit") {
1235
- return {
1236
- message: typeof result?.commitSha === "string" ? `Committed to ${result.branch ?? "branch"}: ${result.commitSha}` : "Export commit completed."
1237
- };
1238
- }
1239
- if (delivery === "pr") {
1240
- return {
1241
- message: typeof result?.prUrl === "string" ? `PR #${result.prNumber ?? "?"}: ${result.prUrl}` : "Export PR created."
1242
- };
1243
- }
1244
- if (delivery === "download") {
1245
- const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1246
- if (typeof target?.path !== "string") return null;
1247
- return {
1248
- path: target.path,
1249
- kind: target?.kind === "canonical" ? "canonical" : "entrypoint",
1250
- status: "up-to-date"
1251
- };
1252
- }).filter((target) => target !== null) : [];
1253
- const count = targets.length;
1254
- return {
1255
- message: `Wrote ${count} export file(s) to ${exportCwd}.`,
1256
- localStatus: {
1257
- overall: "up-to-date",
1258
- targets
1259
- }
1260
- };
1261
- }
1262
- return {
1263
- message: "Export copy payload generated."
1264
- };
1265
- }
1266
- };
1267
-
1268
- // src/services/organization-service.ts
1269
- var OrganizationService = class {
1270
- static {
1271
- __name(this, "OrganizationService");
1272
- }
1273
- apiUrl;
1274
- credentialsStore = new CredentialsStore();
1275
- constructor(apiUrl) {
1276
- this.apiUrl = apiUrl;
1277
- }
1278
- async listOrganizations() {
1279
- const token = await this.credentialsStore.getValidToken();
1280
- if (!token) {
1281
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1282
- }
1283
- const stored = this.credentialsStore.load();
1284
- const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
1285
- const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
1286
- const orgs = await bootstrapClient.organization.list.query();
1287
- return orgs.map((org) => ({
1288
- id: org.id,
1289
- name: org.name,
1290
- plan: org.plan,
1291
- role: org.role
1292
- }));
1293
- }
1294
- async createOrganization(input) {
1295
- const token = await this.credentialsStore.getValidToken();
1296
- if (!token) {
1297
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1298
- }
1299
- const stored = this.credentialsStore.load();
1300
- const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
1301
- const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
1302
- const createdOrg = await bootstrapClient.organization.create.mutate(input);
1303
- return {
1304
- id: createdOrg.id,
1305
- name: createdOrg.name,
1306
- plan: createdOrg.plan,
1307
- role: "owner"
1308
- };
1309
- }
1310
- async listProjects(organizationId) {
1311
- const token = await this.credentialsStore.getValidToken();
1312
- if (!token) {
1313
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1314
- }
1315
- const client2 = createApiClient(this.apiUrl, token, organizationId);
1316
- const projects = await client2.project.list.query({
1317
- limit: 100,
1318
- offset: 0
1319
- });
1320
- return projects.map((project) => ({
1321
- id: project.id,
1322
- name: project.name
1323
- }));
1324
- }
1325
- async createProject(organizationId, name) {
1326
- try {
1327
- const token = await this.credentialsStore.getValidToken();
1328
- if (!token) {
1329
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1330
- }
1331
- const client2 = createApiClient(this.apiUrl, token, organizationId);
1332
- const created = await client2.project.create.mutate({
1333
- name: name.trim()
1334
- });
1335
- return {
1336
- id: created.id,
1337
- name: String(created.name ?? name.trim())
1338
- };
1339
- } catch (error) {
1340
- const message = error instanceof Error ? error.message : String(error);
1341
- appendGlobalErrorLog({
1342
- source: "wizard.createProject",
1343
- message,
1344
- details: {
1345
- apiUrl: this.apiUrl,
1346
- organizationId,
1347
- projectName: name.trim(),
1348
- cwd: process.cwd()
1349
- }
1350
- });
1351
- throw error;
1352
- }
1353
- }
1354
- canCreateProject(org) {
1355
- const role = String(org?.role ?? "").toLowerCase();
1356
- return role === "owner" || role === "admin";
1357
- }
1358
- };
1359
-
1360
- // src/services/repo-service.ts
1361
- import { execFileSync } from "child_process";
1362
- import path4 from "path";
1363
- var RepoService = class {
1364
- static {
1365
- __name(this, "RepoService");
1366
- }
1367
- apiUrl;
1368
- credentialsStore = new CredentialsStore();
1369
- cliRunner;
1370
- constructor(apiUrl) {
1371
- this.apiUrl = apiUrl;
1372
- this.cliRunner = new CliRunner(apiUrl);
1373
- }
1374
- attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
1375
- const repoPath = process.cwd();
1376
- let args = [];
1377
- let lastOutputLines = [];
1378
- try {
1379
- const remoteUrl = this.execGit(repoPath, [
1380
- "remote",
1381
- "get-url",
1382
- "origin"
1383
- ]);
1384
- const token = await this.credentialsStore.getValidToken();
1385
- if (!token) {
1386
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1387
- }
1388
- const client2 = createApiClient(this.apiUrl, token, organizationId);
1389
- const repos = await client2.gitRepository.list.query({
1390
- projectId,
1391
- limit: 100,
1392
- offset: 0
1393
- });
1394
- const isAlreadyAttached = repos.some((repo) => repo.repositoryUrl === remoteUrl);
1395
- const cliEntry = this.cliRunner.resolveCliEntry();
1396
- if (!cliEntry) {
1397
- throw new Error("Could not resolve CLI entrypoint for repo register.");
1398
- }
1399
- const runAnalyze = !isAlreadyAttached;
1400
- args = isAlreadyAttached ? [
1401
- cliEntry,
1402
- "repo",
1403
- "sync",
1404
- "--project-id",
1405
- projectId,
1406
- "--path",
1407
- repoPath,
1408
- "--api-url",
1409
- this.apiUrl,
1410
- "--no-analyze"
1411
- ] : [
1412
- cliEntry,
1413
- "repo",
1414
- "register",
1415
- "--project-id",
1416
- projectId,
1417
- "--path",
1418
- repoPath,
1419
- "--api-url",
1420
- this.apiUrl,
1421
- "--analyze"
1422
- ];
1423
- if (isAlreadyAttached) {
1424
- onProgress?.("Repository already attached to this project. Syncing metadata only (no analysis)...");
1425
- } else {
1426
- onProgress?.("Repository not attached yet. Registering and running analysis...");
1427
- }
1428
- const runResult = await this.cliRunner.runCliCommand(args.slice(1), {
1429
- cwd: repoPath,
1430
- organizationId,
1431
- onProgress,
1432
- requestInteraction,
1433
- onActivity
1434
- });
1435
- lastOutputLines = runResult.outputLines;
1436
- const exitCode = runResult.exitCode;
1437
- if (exitCode !== 0) {
1438
- appendGlobalErrorLog({
1439
- source: "wizard.registerCurrentRepository",
1440
- message: `Repository registration/analysis failed (exit ${exitCode}).`,
1441
- details: {
1442
- apiUrl: this.apiUrl,
1443
- organizationId,
1444
- projectId,
1445
- repoPath,
1446
- command: process.execPath,
1447
- args,
1448
- lastOutputLines: lastOutputLines.slice(-80)
1449
- }
1450
- });
1451
- throw new Error(`Repository registration/analysis failed (exit ${exitCode}).`);
1452
- }
1453
- if (runAnalyze) {
1454
- persistProjectContext(repoPath, {
1455
- projectId,
1456
- organizationId
1457
- });
1458
- } else {
1459
- persistProjectContextWithoutRepoPath(repoPath, {
1460
- projectId,
1461
- organizationId
1462
- });
1463
- }
1464
- return {
1465
- success: true,
1466
- analyzed: runAnalyze
1467
- };
1468
- } catch (error) {
1469
- const message = error instanceof Error ? error.message : String(error);
1470
- appendGlobalErrorLog({
1471
- source: "wizard.registerCurrentRepository",
1472
- message,
1473
- details: {
1474
- apiUrl: this.apiUrl,
1475
- organizationId,
1476
- projectId,
1477
- repoPath,
1478
- command: process.execPath,
1479
- args,
1480
- lastOutputLines: lastOutputLines.slice(-80)
1481
- }
1482
- });
1483
- throw error;
1484
- }
1485
- }, "attachOrSyncCurrentRepository");
1486
- async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1487
- const repoPath = path4.resolve(repoPathInput || process.cwd());
1488
- if (!this.cliRunner.resolveCliEntry()) {
1489
- return {
1490
- success: false,
1491
- output: "Could not resolve CLI entrypoint.",
1492
- exitCode: 1
1493
- };
1494
- }
1495
- const token = await this.credentialsStore.getValidToken();
1496
- if (!token) {
1497
- return {
1498
- success: false,
1499
- output: "No valid credentials. Run `spekn auth login` first.",
1500
- exitCode: 1
1501
- };
1502
- }
1503
- const args = [
1504
- "repo",
1505
- "sync",
1506
- "--project-id",
1507
- projectId,
1508
- "--path",
1509
- repoPath,
1510
- "--api-url",
1511
- this.apiUrl
1512
- ];
1513
- if (options?.analyze === false) {
1514
- args.push("--no-analyze");
1515
- }
1516
- if (options?.importToProject) {
1517
- args.push("--import-to-project");
1518
- }
1519
- if (typeof options?.maxFiles === "number" && Number.isFinite(options.maxFiles)) {
1520
- args.push("--max-files", String(Math.max(1, Math.floor(options.maxFiles))));
1521
- }
1522
- if (options?.analysisEngine) {
1523
- args.push("--analysis-engine", options.analysisEngine);
1524
- }
1525
- if (options?.agent && options.agent.trim().length > 0) {
1526
- args.push("--agent", options.agent.trim());
1527
- }
1528
- try {
1529
- const runResult = await this.cliRunner.runCliCommand(args, {
1530
- cwd: repoPath,
1531
- organizationId,
1532
- onProgress: options?.onProgress,
1533
- requestInteraction: options?.requestInteraction,
1534
- onActivity: options?.onActivity
1535
- });
1536
- return {
1537
- success: runResult.success,
1538
- output: runResult.output,
1539
- exitCode: runResult.exitCode
1540
- };
1541
- } catch (error) {
1542
- const message = error instanceof Error ? error.message : String(error);
1543
- return {
1544
- success: false,
1545
- output: message,
1546
- exitCode: 1
1547
- };
1548
- }
1549
- }
1550
- async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1551
- const result = await this.cliRunner.runCliCommand([
1552
- "repo",
1553
- "detach",
1554
- "--path",
1555
- repoPath
1556
- ], {
1557
- cwd: repoPath,
1558
- includeAuthToken: false
1559
- });
1560
- return {
1561
- success: result.success,
1562
- output: result.output || result.error || "Unknown detach error"
1563
- };
1564
- }
1565
- execGit(repoPath, args) {
1566
- try {
1567
- return execFileSync("git", [
1568
- "-C",
1569
- repoPath,
1570
- ...args
1571
- ], {
1572
- encoding: "utf-8",
1573
- stdio: [
1574
- "pipe",
1575
- "pipe",
1576
- "pipe"
1577
- ]
1578
- }).trim();
1579
- } catch {
1580
- throw new Error("Could not read git metadata. Run TUI from a git repository with an 'origin' remote.");
1581
- }
1582
- }
1583
- };
1584
-
1585
- // src/services/spec-service.ts
1586
- var SpecService = class {
1587
- static {
1588
- __name(this, "SpecService");
1589
- }
1590
- async loadSpecs(client2, projectId) {
1591
- const specs = await client2.specification.list.query({
1592
- projectId,
1593
- limit: 50,
1594
- offset: 0
1595
- });
1596
- return (Array.isArray(specs) ? specs : []).map((spec) => {
1597
- const frontmatter = spec.frontmatter ?? {};
1598
- const hints = frontmatter.hints ?? {};
1599
- const aiContext = frontmatter.aiContext ?? {};
1600
- const acp = frontmatter.acp ?? {};
1601
- const tags = Array.isArray(frontmatter.tags) ? frontmatter.tags.filter((tag) => typeof tag === "string") : [];
1602
- const aiFocusAreas = Array.isArray(aiContext.focusAreas) ? aiContext.focusAreas.filter((area) => typeof area === "string") : [];
1603
- const acpAllowedAgents = Array.isArray(acp.allowedAgents) ? acp.allowedAgents.filter((agent) => typeof agent === "string") : [];
1604
- const countArray = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.length : 0, "countArray");
1605
- return {
1606
- id: spec.id,
1607
- specRef: typeof frontmatter.specRef === "string" ? frontmatter.specRef : typeof spec.specRef === "string" ? spec.specRef : void 0,
1608
- frontmatter,
1609
- title: spec.title,
1610
- status: spec.status,
1611
- version: spec.version,
1612
- updatedAt: spec.updatedAt,
1613
- type: typeof frontmatter.type === "string" ? frontmatter.type : void 0,
1614
- content: typeof spec.content === "string" ? spec.content : void 0,
1615
- tags: tags.length > 0 ? tags : void 0,
1616
- author: typeof frontmatter.author === "string" ? frontmatter.author : void 0,
1617
- hintCounts: {
1618
- constraints: countArray(hints.constraints),
1619
- requirements: countArray(hints.requirements),
1620
- technical: countArray(hints.technical),
1621
- guidance: countArray(hints.guidance)
1622
- },
1623
- relationCounts: {
1624
- dependsOn: countArray(frontmatter.dependsOn),
1625
- conflictsWith: countArray(frontmatter.conflictsWith),
1626
- compatibleWith: countArray(frontmatter.compatibleWith)
1627
- },
1628
- acpPolicyMode: typeof acp.policyMode === "string" ? acp.policyMode : void 0,
1629
- acpAllowedAgents: acpAllowedAgents.length > 0 ? acpAllowedAgents : void 0,
1630
- aiTokenBudget: typeof aiContext.tokenBudget === "number" ? aiContext.tokenBudget : void 0,
1631
- aiFocusAreas: aiFocusAreas.length > 0 ? aiFocusAreas : void 0
1632
- };
1633
- });
1634
- }
1635
- async updateSpecificationContent(client2, projectId, specificationId, content) {
1636
- await client2.specification.update.mutate({
1637
- projectId,
1638
- id: specificationId,
1639
- data: {
1640
- content,
1641
- changeType: "patch",
1642
- changeDescription: "Edited from TUI editor"
1643
- }
1644
- });
1645
- }
1646
- async updateSpecificationStatus(client2, projectId, specificationId, status) {
1647
- await client2.specification.update.mutate({
1648
- projectId,
1649
- id: specificationId,
1650
- data: {
1651
- status,
1652
- changeType: "metadata",
1653
- changeDescription: `Status changed to ${status} from TUI`
1654
- }
1655
- });
1656
- }
1657
- async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1658
- const deleteMutation = client2?.specification?.delete?.mutate;
1659
- if (typeof deleteMutation !== "function") {
1660
- throw new Error("Specification delete route is unavailable.");
1661
- }
1662
- await deleteMutation({
1663
- projectId,
1664
- id: specificationId,
1665
- mode
1666
- });
1667
- }
1668
- async refineSpecificationWithAi(client2, input) {
1669
- const refineMutation = client2?.specification?.refine?.mutate;
1670
- if (typeof refineMutation !== "function") {
1671
- throw new Error("Specification refine route is unavailable.");
1672
- }
1673
- const result = await refineMutation({
1674
- projectId: input.projectId,
1675
- specificationContent: input.specContent,
1676
- userMessage: input.userMessage,
1677
- agentType: input.agentType
1678
- });
1679
- if (typeof result?.content !== "string") {
1680
- throw new Error("AI refinement response was missing content.");
1681
- }
1682
- return result.content;
1683
- }
1684
- };
1685
-
1686
- // src/services/context-service.ts
1687
- var TuiContextService = class {
1688
- static {
1689
- __name(this, "TuiContextService");
1690
- }
1691
- apiUrl;
1692
- authService;
1693
- bootstrapService;
1694
- bridgeService;
1695
- decisionService;
1696
- exportService;
1697
- organizationService;
1698
- repoService;
1699
- specService;
1700
- constructor(apiUrl) {
1701
- this.apiUrl = apiUrl;
1702
- this.authService = new AuthService(apiUrl);
1703
- this.bootstrapService = new BootstrapService(apiUrl);
1704
- this.bridgeService = new BridgeService(apiUrl);
1705
- this.decisionService = new DecisionService();
1706
- this.exportService = new ExportService(apiUrl);
1707
- this.organizationService = new OrganizationService(apiUrl);
1708
- this.repoService = new RepoService(apiUrl);
1709
- this.specService = new SpecService();
1710
- }
1711
- // ── Bootstrap ──────────────────────────────────────────────────────
1712
- async bootstrap(projectIdArg) {
1713
- return this.bootstrapService.bootstrap(projectIdArg);
1714
- }
1715
- hasDeclaredProjectContext(projectIdArg) {
1716
- return this.bootstrapService.hasDeclaredProjectContext(projectIdArg);
1717
- }
1718
- hasLocalProjectContext(repoPath) {
1719
- return this.bootstrapService.hasLocalProjectContext(repoPath);
1720
- }
1721
- async loadWorkflowSummary(client2, projectId) {
1722
- return this.bootstrapService.loadWorkflowSummary(client2, projectId);
1723
- }
1724
- persistContext(organizationId, projectId) {
1725
- this.bootstrapService.persistContext(organizationId, projectId);
1726
- }
1727
- // ── Auth ───────────────────────────────────────────────────────────
1728
- async checkAuthentication() {
1729
- return this.authService.checkAuthentication();
1730
- }
1731
- async authenticateViaCli(onProgress) {
1732
- return this.authService.authenticateViaCli(onProgress);
1733
- }
1734
- extractUserEmail(token) {
1735
- return this.authService.extractUserEmail(token);
1736
- }
1737
- extractTokenExpiry(token) {
1738
- return this.authService.extractTokenExpiry(token);
1739
- }
1740
- // ── Organization & Project ─────────────────────────────────────────
1741
- async listOrganizations() {
1742
- return this.organizationService.listOrganizations();
1743
- }
1744
- async createOrganization(input) {
1745
- return this.organizationService.createOrganization(input);
1746
- }
1747
- async listProjects(organizationId) {
1748
- return this.organizationService.listProjects(organizationId);
1749
- }
1750
- async createProject(organizationId, name) {
1751
- return this.organizationService.createProject(organizationId, name);
1752
- }
1753
- canCreateProject(org) {
1754
- return this.organizationService.canCreateProject(org);
1755
- }
1756
- // ── Specs ──────────────────────────────────────────────────────────
1757
- async loadSpecs(client2, projectId) {
1758
- return this.specService.loadSpecs(client2, projectId);
1759
- }
1760
- async updateSpecificationContent(client2, projectId, specificationId, content) {
1761
- return this.specService.updateSpecificationContent(client2, projectId, specificationId, content);
1762
- }
1763
- async updateSpecificationStatus(client2, projectId, specificationId, status) {
1764
- return this.specService.updateSpecificationStatus(client2, projectId, specificationId, status);
1765
- }
1766
- async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1767
- return this.specService.deleteSpecification(client2, projectId, specificationId, mode);
1768
- }
1769
- async refineSpecificationWithAi(client2, input) {
1770
- return this.specService.refineSpecificationWithAi(client2, input);
1771
- }
1772
- // ── Decisions ──────────────────────────────────────────────────────
1773
- async loadDecisions(client2, projectId) {
1774
- return this.decisionService.loadDecisions(client2, projectId);
1775
- }
1776
- async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1777
- return this.decisionService.resolveDecision(client2, projectId, decisionId, status, reason, existingRationale);
1778
- }
1779
- async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1780
- return this.decisionService.deleteDecision(client2, projectId, decisionId, mode);
1781
- }
1782
- // ── Export ─────────────────────────────────────────────────────────
1783
- async previewExport(client2, projectId, format) {
1784
- return this.exportService.previewExport(client2, projectId, format);
1785
- }
1786
- async generateExport(client2, projectId, format) {
1787
- return this.exportService.generateExport(client2, projectId, format);
1788
- }
1789
- async discoverExportCapabilities(projectId, organizationId) {
1790
- return this.exportService.discoverExportCapabilities(projectId, organizationId);
1791
- }
1792
- async exportStatus(projectId, format, options) {
1793
- return this.exportService.exportStatus(projectId, format, options);
1794
- }
1795
- async deliverExport(projectId, format, delivery, options) {
1796
- return this.exportService.deliverExport(projectId, format, delivery, options);
1797
- }
1798
- // ── Bridge ─────────────────────────────────────────────────────────
1799
- async loadBridgeSummary(client2) {
1800
- return this.bridgeService.loadBridgeSummary(client2);
1801
- }
1802
- async loadLocalBridgeSummary() {
1803
- return this.bridgeService.loadLocalBridgeSummary();
1804
- }
1805
- startLocalBridgeDetached() {
1806
- this.bridgeService.startLocalBridgeDetached();
1807
- }
1808
- async stopLocalBridge(configPort) {
1809
- return this.bridgeService.stopLocalBridge(configPort);
1810
- }
1811
- async loadBridgeLogs(port, since) {
1812
- return this.bridgeService.loadBridgeLogs(port, since);
1813
- }
1814
- // ── Repository ─────────────────────────────────────────────────────
1815
- attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
1816
- return this.repoService.attachOrSyncCurrentRepository(organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity);
1817
- }, "attachOrSyncCurrentRepository");
1818
- async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1819
- return this.repoService.syncRepositoryViaCli(organizationId, projectId, repoPathInput, options);
1820
- }
1821
- async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1822
- return this.repoService.detachContextViaCli(_projectId, repoPath);
1823
- }
1824
- };
1825
-
1826
- // src/store/service-bridge.ts
1827
- var service = null;
1828
- var client = null;
1829
- function initServiceBridge(apiUrl) {
1830
- if (!service) {
1831
- service = new TuiContextService(apiUrl);
1832
- }
1833
- return service;
1834
- }
1835
- __name(initServiceBridge, "initServiceBridge");
1836
- function getService() {
1837
- if (!service) {
1838
- throw new Error("Service bridge not initialized. Call initServiceBridge() first.");
1839
- }
1840
- return service;
1841
- }
1842
- __name(getService, "getService");
1843
- function getClient() {
1844
- return client;
1845
- }
1846
- __name(getClient, "getClient");
1847
- function setClient(c) {
1848
- client = c;
1849
- }
1850
- __name(setClient, "setClient");
1851
-
1852
- // src/store/use-tui-ui-store.ts
1853
- import { create } from "zustand";
1854
- import { subscribeWithSelector } from "zustand/middleware";
1855
- var _initialScreen = "home";
1856
- function setInitialScreen(screen) {
1857
- _initialScreen = screen;
1858
- }
1859
- __name(setInitialScreen, "setInitialScreen");
1860
- var initialState = {
1861
- screen: _initialScreen,
1862
- showHelp: false,
1863
- commandMode: false,
1864
- searchQuery: "",
1865
- navMode: "content",
1866
- cursorSpec: null,
1867
- cursorDecision: null,
1868
- openedSpecId: void 0,
1869
- editorMenuOpen: false,
1870
- statusMenuOpen: false,
1871
- aiRefineMenuOpen: false,
1872
- editorLaunching: false,
1873
- selectedEditor: "",
1874
- selectedOrganizationIndex: void 0,
1875
- selectedProjectIndex: void 0,
1876
- newProjectName: void 0,
1877
- selectedAnalysisAgent: "auto"
1878
- };
1879
- var useTuiUiStore = create()(subscribeWithSelector((set) => ({
1880
- ...initialState,
1881
- screen: _initialScreen,
1882
- setScreen: /* @__PURE__ */ __name((screen) => set({
1883
- screen
1884
- }), "setScreen"),
1885
- toggleHelp: /* @__PURE__ */ __name(() => set((prev) => ({
1886
- showHelp: !prev.showHelp
1887
- })), "toggleHelp"),
1888
- setShowHelp: /* @__PURE__ */ __name((show) => set({
1889
- showHelp: show
1890
- }), "setShowHelp"),
1891
- setCommandMode: /* @__PURE__ */ __name((enabled) => set({
1892
- commandMode: enabled
1893
- }), "setCommandMode"),
1894
- setSearchQuery: /* @__PURE__ */ __name((query) => set({
1895
- searchQuery: query
1896
- }), "setSearchQuery"),
1897
- setNavMode: /* @__PURE__ */ __name((mode) => set({
1898
- navMode: mode
1899
- }), "setNavMode"),
1900
- setCursorSpec: /* @__PURE__ */ __name((spec) => set({
1901
- cursorSpec: spec
1902
- }), "setCursorSpec"),
1903
- setCursorDecision: /* @__PURE__ */ __name((decision) => set({
1904
- cursorDecision: decision
1905
- }), "setCursorDecision"),
1906
- setOpenedSpecId: /* @__PURE__ */ __name((specId) => set({
1907
- openedSpecId: specId
1908
- }), "setOpenedSpecId"),
1909
- setSelectedEditor: /* @__PURE__ */ __name((editor) => set({
1910
- selectedEditor: editor
1911
- }), "setSelectedEditor"),
1912
- setEditorMenuOpen: /* @__PURE__ */ __name((open) => set({
1913
- editorMenuOpen: open
1914
- }), "setEditorMenuOpen"),
1915
- setStatusMenuOpen: /* @__PURE__ */ __name((open) => set({
1916
- statusMenuOpen: open
1917
- }), "setStatusMenuOpen"),
1918
- setAiRefineMenuOpen: /* @__PURE__ */ __name((open) => set({
1919
- aiRefineMenuOpen: open
1920
- }), "setAiRefineMenuOpen"),
1921
- setEditorLaunching: /* @__PURE__ */ __name((launching) => set({
1922
- editorLaunching: launching
1923
- }), "setEditorLaunching"),
1924
- openEditorMenuForSpec: /* @__PURE__ */ __name((specId, editor) => set({
1925
- openedSpecId: specId,
1926
- selectedEditor: editor,
1927
- editorMenuOpen: true
1928
- }), "openEditorMenuForSpec"),
1929
- resetSpecsUi: /* @__PURE__ */ __name(() => set({
1930
- openedSpecId: void 0,
1931
- cursorSpec: null,
1932
- editorMenuOpen: false,
1933
- statusMenuOpen: false,
1934
- aiRefineMenuOpen: false,
1935
- editorLaunching: false
1936
- }), "resetSpecsUi"),
1937
- setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
1938
- selectedOrganizationIndex: index
1939
- }), "setSelectedOrganizationIndex"),
1940
- setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
1941
- selectedProjectIndex: index
1942
- }), "setSelectedProjectIndex"),
1943
- setNewProjectName: /* @__PURE__ */ __name((name) => set({
1944
- newProjectName: name
1945
- }), "setNewProjectName"),
1946
- setSelectedAnalysisAgent: /* @__PURE__ */ __name((agent) => set({
1947
- selectedAnalysisAgent: agent
1948
- }), "setSelectedAnalysisAgent"),
1949
- resetOnboardingUi: /* @__PURE__ */ __name(() => set({
1950
- selectedOrganizationIndex: void 0,
1951
- selectedProjectIndex: void 0,
1952
- newProjectName: void 0,
1953
- selectedAnalysisAgent: "auto"
1954
- }), "resetOnboardingUi"),
1955
- showTooltip: /* @__PURE__ */ __name((message, duration = 3e3) => set((state) => {
1956
- if (state.tooltipTimeout) {
1957
- clearTimeout(state.tooltipTimeout);
1958
- }
1959
- const timeout = setTimeout(() => {
1960
- useTuiUiStore.getState().clearTooltip();
1961
- }, duration);
1962
- return {
1963
- tooltip: message,
1964
- tooltipTimeout: timeout
1965
- };
1966
- }), "showTooltip"),
1967
- clearTooltip: /* @__PURE__ */ __name(() => set((state) => {
1968
- if (state.tooltipTimeout) {
1969
- clearTimeout(state.tooltipTimeout);
1970
- }
1971
- return {
1972
- tooltip: void 0,
1973
- tooltipTimeout: void 0
1974
- };
1975
- }), "clearTooltip")
1976
- })));
1977
-
1978
- // src/capabilities/policy.ts
1979
- var TIER_ORDER = {
1980
- [OrganizationPlan.FREE]: 0,
1981
- [OrganizationPlan.PRO]: 1,
1982
- [OrganizationPlan.TEAM]: 2,
1983
- [OrganizationPlan.ENTERPRISE]: 3
1984
- };
1985
- var NAV_DEFINITIONS = [
1986
- {
1987
- id: "home",
1988
- label: "Home",
1989
- description: "Next actions and workflow pulse",
1990
- requiredPlan: OrganizationPlan.FREE
1991
- },
1992
- {
1993
- id: "specs",
1994
- label: "Specs",
1995
- description: "Manage governed specifications",
1996
- requiredPlan: OrganizationPlan.FREE
1997
- },
1998
- {
1999
- id: "decisions",
2000
- label: "Decision Log",
2001
- description: "Review decisions and rationale",
2002
- requiredPlan: OrganizationPlan.FREE
2003
- },
2004
- {
2005
- id: "export",
2006
- label: "Export",
2007
- description: "Generate AGENTS.md / CLAUDE.md / .cursorrules",
2008
- requiredPlan: OrganizationPlan.FREE
2009
- },
2010
- {
2011
- id: "bridge",
2012
- label: "Local Bridge",
2013
- description: "Bridge status and controls",
2014
- requiredPlan: OrganizationPlan.FREE
2015
- },
2016
- {
2017
- id: "active-runs",
2018
- label: "Active Runs",
2019
- description: "Realtime orchestration dashboard",
2020
- requiredPlan: OrganizationPlan.TEAM
2021
- },
2022
- {
2023
- id: "phase-gates",
2024
- label: "Phase Gates",
2025
- description: "Approve and unblock workflow phases",
2026
- requiredPlan: OrganizationPlan.TEAM
2027
- },
2028
- {
2029
- id: "skills-marketplace",
2030
- label: "Skills Marketplace",
2031
- description: "Manage shared managed skills",
2032
- requiredPlan: OrganizationPlan.TEAM
2033
- },
2034
- {
2035
- id: "org-governance",
2036
- label: "Org Governance",
2037
- description: "Compliance, policy, deployment gates",
2038
- requiredPlan: OrganizationPlan.ENTERPRISE
2039
- }
2040
- ];
2041
- var GATE_DISABLED_PHASES = [
2042
- WorkflowPhase.SPECIFY,
2043
- WorkflowPhase.CLARIFY
2044
- ];
2045
- function meetsMinimumTier(current, required) {
2046
- return TIER_ORDER[current] >= TIER_ORDER[required];
2047
- }
2048
- __name(meetsMinimumTier, "meetsMinimumTier");
2049
- function resolveNavPolicy(ctx) {
2050
- return NAV_DEFINITIONS.map((item) => {
2051
- if (!meetsMinimumTier(ctx.plan, item.requiredPlan)) {
2052
- return {
2053
- ...item,
2054
- state: "locked",
2055
- reason: `Requires ${item.requiredPlan.toUpperCase()} tier`
2056
- };
2057
- }
2058
- if (item.id === "phase-gates" && ctx.role === "viewer") {
2059
- return {
2060
- ...item,
2061
- state: "disabled",
2062
- reason: "Viewer role cannot approve gates"
2063
- };
2064
- }
2065
- if (item.id === "phase-gates" && ctx.workflowPhase && GATE_DISABLED_PHASES.includes(ctx.workflowPhase)) {
2066
- return {
2067
- ...item,
2068
- state: "disabled",
2069
- reason: `Gate approvals are unavailable in ${ctx.workflowPhase} phase`
2070
- };
2071
- }
2072
- return {
2073
- ...item,
2074
- state: "enabled"
2075
- };
2076
- });
2077
- }
2078
- __name(resolveNavPolicy, "resolveNavPolicy");
2079
-
2080
- // src/state/onboarding-utils.ts
2081
- function logOnboardingAttachResult(appendLog, result) {
2082
- if (result.warning) {
2083
- appendLog(`[warn] ${result.warning}`);
2084
- }
2085
- if (result.analyzed) {
2086
- appendLog("[setup] Repository attached and analysis complete.");
2087
- } else if (result.warning) {
2088
- appendLog("[setup] Repository attached; analysis did not fully complete.");
2089
- } else {
2090
- appendLog("[setup] Repository already attached. Metadata sync complete (analysis skipped).");
2091
- }
2092
- }
2093
- __name(logOnboardingAttachResult, "logOnboardingAttachResult");
2094
-
2095
- // src/store/windows/use-onboarding-window.ts
2096
- import { create as create2 } from "zustand";
2097
- import { subscribeWithSelector as subscribeWithSelector2 } from "zustand/middleware";
2098
- var useOnboardingWindow = create2()(subscribeWithSelector2((set) => ({
2099
- mode: "initial-setup",
2100
- step: "organization",
2101
- attachCurrentFolder: true,
2102
- runLines: [],
2103
- runStatus: "running",
2104
- startedAt: null,
2105
- availableAgents: [],
2106
- canCreateProject: false,
2107
- toolCalls: {},
2108
- setMode: /* @__PURE__ */ __name((mode) => set({
2109
- mode
2110
- }), "setMode"),
2111
- setStep: /* @__PURE__ */ __name((step) => set({
2112
- step
2113
- }), "setStep"),
2114
- setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
2115
- selectedOrganizationIndex: index
2116
- }), "setSelectedOrganizationIndex"),
2117
- setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
2118
- selectedProjectIndex: index
2119
- }), "setSelectedProjectIndex"),
2120
- setNewProjectName: /* @__PURE__ */ __name((name) => set({
2121
- newProjectName: name
2122
- }), "setNewProjectName"),
2123
- setAttachCurrentFolder: /* @__PURE__ */ __name((attach) => set({
2124
- attachCurrentFolder: attach
2125
- }), "setAttachCurrentFolder"),
2126
- setRunLines: /* @__PURE__ */ __name((lines) => set({
2127
- runLines: lines
2128
- }), "setRunLines"),
2129
- addRunLine: /* @__PURE__ */ __name((line) => set((state) => ({
2130
- runLines: [
2131
- ...state.runLines,
2132
- line
2133
- ].slice(-400)
2134
- })), "addRunLine"),
2135
- setRunStatus: /* @__PURE__ */ __name((status) => set({
2136
- runStatus: status
2137
- }), "setRunStatus"),
2138
- setStartedAt: /* @__PURE__ */ __name((ts) => set({
2139
- startedAt: ts
2140
- }), "setStartedAt"),
2141
- setInteraction: /* @__PURE__ */ __name((interaction) => set({
2142
- interaction
2143
- }), "setInteraction"),
2144
- setError: /* @__PURE__ */ __name((error) => set({
2145
- error
2146
- }), "setError"),
2147
- setSelectedOrganizationId: /* @__PURE__ */ __name((id) => set({
2148
- selectedOrganizationId: id
2149
- }), "setSelectedOrganizationId"),
2150
- setSelectedProjectId: /* @__PURE__ */ __name((id) => set({
2151
- selectedProjectId: id
2152
- }), "setSelectedProjectId"),
2153
- setAvailableAgents: /* @__PURE__ */ __name((agents) => set({
2154
- availableAgents: agents
2155
- }), "setAvailableAgents"),
2156
- setCanCreateProject: /* @__PURE__ */ __name((canCreate) => set({
2157
- canCreateProject: canCreate
2158
- }), "setCanCreateProject"),
2159
- upsertToolCall: /* @__PURE__ */ __name((event) => set((state) => {
2160
- const id = event.toolCallId ?? `tc-${Date.now()}`;
2161
- const existing = state.toolCalls[id];
2162
- const updated = existing ? {
2163
- ...existing,
2164
- status: event.status ?? existing.status,
2165
- title: event.title ?? existing.title,
2166
- locations: event.locations ?? existing.locations,
2167
- completedAt: event.status === "completed" || event.status === "failed" ? Date.now() : existing.completedAt
2168
- } : {
2169
- toolCallId: id,
2170
- title: event.title ?? event.toolName ?? "Tool call",
2171
- toolName: event.toolName,
2172
- kind: event.kind ?? "other",
2173
- status: event.status ?? "in_progress",
2174
- locations: event.locations ?? [],
2175
- startedAt: Date.now()
2176
- };
2177
- return {
2178
- toolCalls: {
2179
- ...state.toolCalls,
2180
- [id]: updated
2181
- }
2182
- };
2183
- }), "upsertToolCall"),
2184
- setActiveThought: /* @__PURE__ */ __name((text) => set({
2185
- activeThought: text
2186
- }), "setActiveThought"),
2187
- reset: /* @__PURE__ */ __name(() => set({
2188
- mode: "initial-setup",
2189
- step: "organization",
2190
- selectedOrganizationIndex: void 0,
2191
- selectedProjectIndex: void 0,
2192
- newProjectName: void 0,
2193
- attachCurrentFolder: true,
2194
- runLines: [],
2195
- runStatus: "running",
2196
- startedAt: null,
2197
- interaction: void 0,
2198
- error: void 0,
2199
- selectedOrganizationId: void 0,
2200
- selectedProjectId: void 0,
2201
- availableAgents: [],
2202
- canCreateProject: false,
2203
- toolCalls: {},
2204
- activeThought: void 0
2205
- }), "reset")
2206
- })));
2207
-
2208
- // src/store/auth-utils.ts
2209
- function isAuthenticationError(message) {
2210
- const normalized = message.toLowerCase();
2211
- return normalized.includes("authentication required") || normalized.includes("no valid credentials") || normalized.includes("unauthorized") || normalized.includes("forbidden") || normalized.includes("invalid token") || normalized.includes("token expired") || normalized.includes("auth");
2212
- }
2213
- __name(isAuthenticationError, "isAuthenticationError");
2214
-
2215
- // src/store/use-project-data-store.ts
2216
- import { create as create3 } from "zustand";
2217
- import { subscribeWithSelector as subscribeWithSelector3 } from "zustand/middleware";
2218
- var EMPTY_WORKFLOW = {
2219
- currentPhase: null,
2220
- blockedCount: 0,
2221
- hasPlanningArtifacts: false,
2222
- hasVerificationEvidence: false
2223
- };
2224
- var useProjectDataStore = create3()(subscribeWithSelector3((set, get) => ({
2225
- specs: [],
2226
- decisions: [],
2227
- workflow: EMPTY_WORKFLOW,
2228
- navPolicy: [],
2229
- setProjectData: /* @__PURE__ */ __name((specs, decisions, workflow, navPolicy) => set({
2230
- specs,
2231
- decisions,
2232
- workflow,
2233
- navPolicy
2234
- }), "setProjectData"),
2235
- setPollingData: /* @__PURE__ */ __name((workflow, navPolicy) => set({
2236
- workflow,
2237
- navPolicy
2238
- }), "setPollingData"),
2239
- clearProjectData: /* @__PURE__ */ __name(() => set({
2240
- specs: [],
2241
- decisions: [],
2242
- workflow: EMPTY_WORKFLOW,
2243
- navPolicy: []
2244
- }), "clearProjectData"),
2245
- updateSpecificationContent: /* @__PURE__ */ __name(async (specificationId, content) => {
2246
- const client2 = getClient();
2247
- const boot = getBootContext();
2248
- if (!client2 || !boot) return;
2249
- await withSessionFeedback({
2250
- statusLine: "Saving specification...",
2251
- action: /* @__PURE__ */ __name(() => getService().updateSpecificationContent(client2, boot.projectId, specificationId, content), "action"),
2252
- successLog: "[specs] saved specification changes",
2253
- failureLog: "[error] save failed",
2254
- failureStatusLine: "Save failed"
2255
- });
2256
- }, "updateSpecificationContent"),
2257
- updateSpecificationStatus: /* @__PURE__ */ __name(async (specificationId, status, options) => {
2258
- const client2 = getClient();
2259
- const boot = getBootContext();
2260
- if (!client2 || !boot) return;
2261
- setSessionStatusLine(`Updating status to ${status}...`);
2262
- try {
2263
- await getService().updateSpecificationStatus(client2, boot.projectId, specificationId, status);
2264
- appendSessionLog(`[specs] status updated to ${status}`);
2265
- if (options?.refresh !== false) {
2266
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-BVFDAWOB.mjs");
2267
- await useSessionStore2.getState().refresh();
2268
- }
2269
- } catch (error) {
2270
- const message = error instanceof Error ? error.message : String(error);
2271
- appendSessionLog(`[error] status update failed: ${message}`);
2272
- setSessionStatusLine("Status update failed");
2273
- refreshOnAuthenticationError(message);
2274
- }
2275
- }, "updateSpecificationStatus"),
2276
- deleteSpecification: /* @__PURE__ */ __name(async (specificationId, mode = "archive", options) => {
2277
- const client2 = getClient();
2278
- const boot = getBootContext();
2279
- if (!client2 || !boot) return;
2280
- setSessionStatusLine(mode === "delete" ? "Deleting specification permanently..." : "Archiving specification...");
2281
- try {
2282
- await getService().deleteSpecification(client2, boot.projectId, specificationId, mode);
2283
- appendSessionLog(mode === "delete" ? "[specs] specification deleted permanently" : "[specs] specification archived");
2284
- if (options?.refresh !== false) {
2285
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-BVFDAWOB.mjs");
2286
- await useSessionStore2.getState().refresh();
2287
- }
2288
- } catch (error) {
2289
- const message = error instanceof Error ? error.message : String(error);
2290
- appendSessionLog(`[error] specification ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2291
- setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2292
- refreshOnAuthenticationError(message);
2293
- }
2294
- }, "deleteSpecification"),
2295
- refineSpecificationWithAi: /* @__PURE__ */ __name(async (specificationId, userMessage) => {
2296
- const client2 = getClient();
2297
- const boot = getBootContext();
2298
- const { specs } = get();
2299
- if (!client2 || !boot) return;
2300
- const spec = specs.find((item) => item.id === specificationId);
2301
- if (!spec) {
2302
- appendSessionLog("[error] refine failed: specification not found in current list");
2303
- setSessionStatusLine("Refinement failed");
2304
- return;
2305
- }
2306
- const specContent = (spec.content ?? "").trim();
2307
- if (!specContent) {
2308
- appendSessionLog("[error] refine failed: selected specification has no content");
2309
- setSessionStatusLine("Refinement failed");
2310
- return;
2311
- }
2312
- setSessionStatusLine("Refining specification with AI...");
2313
- const service2 = getService();
2314
- try {
2315
- const refinedContent = await service2.refineSpecificationWithAi(client2, {
2316
- projectId: boot.projectId,
2317
- specContent,
2318
- userMessage,
2319
- agentType: "codex"
2320
- });
2321
- await service2.updateSpecificationContent(client2, boot.projectId, specificationId, refinedContent);
2322
- appendSessionLog("[specs] AI refinement applied and saved");
2323
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-BVFDAWOB.mjs");
2324
- await useSessionStore2.getState().refresh();
2325
- } catch (error) {
2326
- const message = error instanceof Error ? error.message : String(error);
2327
- appendSessionLog(`[error] AI refinement failed: ${message}`);
2328
- setSessionStatusLine("AI refinement failed");
2329
- refreshOnAuthenticationError(message);
2330
- }
2331
- }, "refineSpecificationWithAi"),
2332
- resolveDecision: /* @__PURE__ */ __name(async (decisionId, status, reason, existingRationale, options) => {
2333
- const client2 = getClient();
2334
- const boot = getBootContext();
2335
- if (!client2 || !boot) {
2336
- throw new Error("Decision update unavailable: project context is not initialized.");
2337
- }
2338
- setSessionStatusLine(`Resolving decision as ${status}...`);
2339
- try {
2340
- await getService().resolveDecision(client2, boot.projectId, decisionId, status, reason, existingRationale);
2341
- appendSessionLog(`[decisions] ${decisionId} -> ${status}`);
2342
- if (options?.refresh !== false) {
2343
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-BVFDAWOB.mjs");
2344
- await useSessionStore2.getState().refresh();
2345
- }
2346
- } catch (error) {
2347
- const message = error instanceof Error ? error.message : String(error);
2348
- appendSessionLog(`[error] decision resolution failed: ${message}`);
2349
- setSessionStatusLine("Decision resolution failed");
2350
- refreshOnAuthenticationError(message);
2351
- throw error;
2352
- }
2353
- }, "resolveDecision"),
2354
- deleteDecision: /* @__PURE__ */ __name(async (decisionId, mode = "archive", options) => {
2355
- const client2 = getClient();
2356
- const boot = getBootContext();
2357
- if (!client2 || !boot) {
2358
- throw new Error("Decision delete unavailable: project context is not initialized.");
2359
- }
2360
- setSessionStatusLine(mode === "delete" ? "Deleting decision permanently..." : "Archiving decision...");
2361
- try {
2362
- await getService().deleteDecision(client2, boot.projectId, decisionId, mode);
2363
- appendSessionLog(mode === "delete" ? `[decisions] ${decisionId} deleted permanently` : `[decisions] ${decisionId} archived`);
2364
- if (options?.refresh !== false) {
2365
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-BVFDAWOB.mjs");
2366
- await useSessionStore2.getState().refresh();
2367
- }
2368
- } catch (error) {
2369
- const message = error instanceof Error ? error.message : String(error);
2370
- appendSessionLog(`[error] decision ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2371
- setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2372
- refreshOnAuthenticationError(message);
2373
- throw error;
2374
- }
2375
- }, "deleteDecision")
2376
- })));
2377
-
2378
- // src/store/use-export-store.ts
2379
- import { create as create4 } from "zustand";
2380
- import { subscribeWithSelector as subscribeWithSelector4 } from "zustand/middleware";
2381
-
2382
- // src/utils/clipboard.ts
2383
- import { spawnSync } from "child_process";
2384
- function clipboardAttempts() {
2385
- if (process.platform === "darwin") {
2386
- return [
2387
- {
2388
- cmd: "pbcopy",
2389
- args: []
2390
- }
2391
- ];
2392
- }
2393
- if (process.platform === "win32") {
2394
- return [
2395
- {
2396
- cmd: "clip",
2397
- args: []
2398
- }
2399
- ];
2400
- }
2401
- return [
2402
- {
2403
- cmd: "wl-copy",
2404
- args: []
2405
- },
2406
- {
2407
- cmd: "xclip",
2408
- args: [
2409
- "-selection",
2410
- "clipboard"
2411
- ]
2412
- },
2413
- {
2414
- cmd: "xsel",
2415
- args: [
2416
- "--clipboard",
2417
- "--input"
2418
- ]
2419
- }
2420
- ];
2421
- }
2422
- __name(clipboardAttempts, "clipboardAttempts");
2423
- function copyTextToClipboard(text) {
2424
- const attempts = clipboardAttempts();
2425
- let lastError = "No clipboard command available.";
2426
- for (const attempt of attempts) {
2427
- const result = spawnSync(attempt.cmd, attempt.args, {
2428
- input: text,
2429
- encoding: "utf8",
2430
- stdio: [
2431
- "pipe",
2432
- "ignore",
2433
- "pipe"
2434
- ]
2435
- });
2436
- if (!result.error && result.status === 0) {
2437
- return {
2438
- ok: true
2439
- };
2440
- }
2441
- lastError = (result.error?.message ?? result.stderr?.trim()) || `${attempt.cmd} exited with status ${result.status}`;
2442
- }
2443
- return {
2444
- ok: false,
2445
- error: lastError
2446
- };
2447
- }
2448
- __name(copyTextToClipboard, "copyTextToClipboard");
2449
-
2450
- // src/store/use-export-store.ts
2451
- var EMPTY_EXPORT_JOB = {
2452
- action: null,
2453
- status: "idle"
2454
- };
2455
- async function runExport(action) {
2456
- const state = useExportStore.getState();
2457
- const boot = getBootContext();
2458
- if (!boot) return;
2459
- if (state.exportInFlight) {
2460
- appendSessionLog("[warn] Export already in progress");
2461
- return;
2462
- }
2463
- const format = state.exportFormat;
2464
- useExportStore.setState({
2465
- exportInFlight: true,
2466
- exportJob: {
2467
- action,
2468
- status: "running",
2469
- format
2470
- }
2471
- });
2472
- setSessionStatusLine(action === "preview" ? "Previewing export..." : "Generating export...");
2473
- const service2 = getService();
2474
- const client2 = getClient();
2475
- try {
2476
- if (action === "status") {
2477
- const status = await service2.exportStatus(boot.projectId, format, {
2478
- mode: state.exportMode,
2479
- scopePath: state.exportScopePath || void 0,
2480
- organizationId: boot.organizationId
2481
- });
2482
- useExportStore.setState({
2483
- exportStatus: status,
2484
- exportJob: {
2485
- action,
2486
- status: "success",
2487
- format
2488
- }
2489
- });
2490
- setSessionStatusLine(`Export status: ${status.overall}`);
2491
- appendSessionLog(`[export] Status ${format}: ${status.overall}`);
2492
- return;
2493
- }
2494
- if (action === "commit" || action === "pr") {
2495
- const delivery = action === "commit" ? "commit" : "pr";
2496
- const result = await service2.deliverExport(boot.projectId, format, delivery, {
2497
- mode: state.exportMode,
2498
- scopePath: state.exportScopePath || void 0,
2499
- organizationId: boot.organizationId
2500
- });
2501
- useExportStore.setState({
2502
- exportJob: {
2503
- action,
2504
- status: "success",
2505
- format
2506
- }
2507
- });
2508
- setSessionStatusLine(result.message);
2509
- appendSessionLog(`[export] ${result.message}`);
2510
- return;
2511
- }
2512
- const output = action === "preview" ? await service2.previewExport(client2, boot.projectId, format) : await service2.generateExport(client2, boot.projectId, format);
2513
- useExportStore.setState({
2514
- exportPreview: output,
2515
- exportJob: {
2516
- action,
2517
- status: "success",
2518
- format
2519
- }
2520
- });
2521
- setSessionStatusLine(action === "preview" ? "Export preview ready" : "Export generated");
2522
- const verb = action === "preview" ? "Previewed" : "Generated";
2523
- appendSessionLog(`[export] ${verb} ${format} (${output.anchorCount} anchors)`);
2524
- } catch (error) {
2525
- const message = error instanceof Error ? error.message : String(error);
2526
- useExportStore.setState({
2527
- exportJob: {
2528
- action,
2529
- status: "error",
2530
- format,
2531
- error: message
2532
- }
2533
- });
2534
- setSessionStatusLine(action === "preview" ? "Export preview failed" : "Export generation failed");
2535
- appendSessionLog(`[error] Export ${action} failed: ${message}`);
2536
- refreshOnAuthenticationError(message);
2537
- } finally {
2538
- useExportStore.setState({
2539
- exportInFlight: false
2540
- });
2541
- }
2542
- }
2543
- __name(runExport, "runExport");
2544
- var useExportStore = create4()(subscribeWithSelector4((set, get) => ({
2545
- exportFormat: "agents-md",
2546
- exportMode: "global",
2547
- exportScopePath: "",
2548
- exportDelivery: "download",
2549
- exportCapabilities: null,
2550
- exportPreview: null,
2551
- exportStatus: null,
2552
- exportValidation: {
2553
- open: false
2554
- },
2555
- exportJob: EMPTY_EXPORT_JOB,
2556
- exportInFlight: false,
2557
- setCapabilities: /* @__PURE__ */ __name((capabilities) => {
2558
- set((prev) => {
2559
- const discoveredFormats = capabilities?.formats?.map((f) => f.id) ?? [];
2560
- const discoveredModes = capabilities?.modes ?? [];
2561
- const resolvedFormat = discoveredFormats.length > 0 ? discoveredFormats.includes(prev.exportFormat) ? prev.exportFormat : discoveredFormats[0] : prev.exportFormat;
2562
- const resolvedMode = discoveredModes.length > 0 ? discoveredModes.includes(prev.exportMode) ? prev.exportMode : discoveredModes[0] : prev.exportMode;
2563
- return {
2564
- exportCapabilities: capabilities,
2565
- exportFormat: resolvedFormat,
2566
- exportMode: resolvedMode
2567
- };
2568
- });
2569
- }, "setCapabilities"),
2570
- setExportFormat: /* @__PURE__ */ __name((format) => {
2571
- set((prev) => {
2572
- const allowedFormats = prev.exportCapabilities?.formats.map((f) => f.id) ?? [];
2573
- if (allowedFormats.length > 0 && !allowedFormats.includes(format)) {
2574
- setSessionStatusLine(`Export format unavailable: ${format}`);
2575
- return prev;
2576
- }
2577
- if (prev.exportFormat === format) return prev;
2578
- setSessionStatusLine(`Export format set to ${format}`);
2579
- return {
2580
- exportFormat: format,
2581
- exportPreview: null,
2582
- exportStatus: null,
2583
- exportValidation: {
2584
- open: false
2585
- },
2586
- exportJob: EMPTY_EXPORT_JOB
2587
- };
2588
- });
2589
- }, "setExportFormat"),
2590
- setExportMode: /* @__PURE__ */ __name((mode) => {
2591
- set((prev) => {
2592
- const allowedModes = prev.exportCapabilities?.modes ?? [];
2593
- if (allowedModes.length > 0 && !allowedModes.includes(mode)) {
2594
- setSessionStatusLine(`Export mode unavailable: ${mode}`);
2595
- return prev;
2596
- }
2597
- setSessionStatusLine(`Export mode set to ${mode}`);
2598
- return {
2599
- exportMode: mode
2600
- };
2601
- });
2602
- }, "setExportMode"),
2603
- setExportScopePath: /* @__PURE__ */ __name((scopePath) => {
2604
- setSessionStatusLine("Updated export scope path");
2605
- set({
2606
- exportScopePath: scopePath
2607
- });
2608
- }, "setExportScopePath"),
2609
- setExportDelivery: /* @__PURE__ */ __name((delivery) => {
2610
- setSessionStatusLine(`Export delivery set to ${delivery}`);
2611
- set({
2612
- exportDelivery: delivery
2613
- });
2614
- }, "setExportDelivery"),
2615
- previewExport: /* @__PURE__ */ __name(async () => {
2616
- await runExport("preview");
2617
- }, "previewExport"),
2618
- generateExport: /* @__PURE__ */ __name(async () => {
2619
- setSessionStatusLine("Confirm export validation to write files to disk");
2620
- set({
2621
- exportValidation: {
2622
- open: true
2623
- }
2624
- });
2625
- }, "generateExport"),
2626
- validateAndWriteExport: /* @__PURE__ */ __name(async () => {
2627
- const state = get();
2628
- const boot = getBootContext();
2629
- if (!boot) return;
2630
- if (state.exportInFlight) {
2631
- appendSessionLog("[warn] Export already in progress");
2632
- return;
2633
- }
2634
- const format = state.exportFormat;
2635
- set({
2636
- exportInFlight: true,
2637
- exportValidation: {
2638
- open: false
2639
- },
2640
- exportJob: {
2641
- action: "generate",
2642
- status: "running",
2643
- format
2644
- }
2645
- });
2646
- setSessionStatusLine("Validating export and writing files...");
2647
- const service2 = getService();
2648
- try {
2649
- const result = await service2.deliverExport(boot.projectId, format, "download", {
2650
- mode: state.exportMode,
2651
- scopePath: state.exportScopePath || void 0,
2652
- organizationId: boot.organizationId
2653
- });
2654
- set((prev) => ({
2655
- exportStatus: result.localStatus ?? prev.exportStatus,
2656
- exportJob: {
2657
- action: "generate",
2658
- status: "success",
2659
- format
2660
- }
2661
- }));
2662
- setSessionStatusLine(result.message);
2663
- appendSessionLog(`[export] ${result.message}`);
2664
- } catch (error) {
2665
- const message = error instanceof Error ? error.message : String(error);
2666
- set({
2667
- exportJob: {
2668
- action: "generate",
2669
- status: "error",
2670
- format,
2671
- error: message
2672
- }
2673
- });
2674
- setSessionStatusLine("Export validation/write failed");
2675
- appendSessionLog(`[error] Export validate/write failed: ${message}`);
2676
- refreshOnAuthenticationError(message);
2677
- } finally {
2678
- set({
2679
- exportInFlight: false
2680
- });
2681
- }
2682
- }, "validateAndWriteExport"),
2683
- cancelExportValidation: /* @__PURE__ */ __name(() => {
2684
- setSessionStatusLine("Export validation cancelled");
2685
- set({
2686
- exportValidation: {
2687
- open: false
2688
- }
2689
- });
2690
- }, "cancelExportValidation"),
2691
- statusExport: /* @__PURE__ */ __name(async () => {
2692
- await runExport("status");
2693
- }, "statusExport"),
2694
- commitExport: /* @__PURE__ */ __name(async () => {
2695
- await runExport("commit");
2696
- }, "commitExport"),
2697
- createPrExport: /* @__PURE__ */ __name(async () => {
2698
- await runExport("pr");
2699
- }, "createPrExport"),
2700
- copyExportPreview: /* @__PURE__ */ __name(() => {
2701
- const { exportPreview, exportJob } = get();
2702
- const hasGeneratedPreview = exportJob.status === "success" && (exportJob.action === "preview" || exportJob.action === "generate");
2703
- if (!exportPreview?.content || !hasGeneratedPreview) {
2704
- setSessionStatusLine("No generated preview to copy. Run p or g first.");
2705
- appendSessionLog("[warn] export copy requested before preview/generate completed");
2706
- return;
2707
- }
2708
- const copied = copyTextToClipboard(exportPreview.content);
2709
- if (copied.ok) {
2710
- setSessionStatusLine("Copied preview to clipboard");
2711
- appendSessionLog("[export] copied preview to clipboard");
2712
- return;
2713
- }
2714
- setSessionStatusLine("Clipboard copy failed");
2715
- appendSessionLog(`[error] clipboard copy failed: ${copied.error}`);
2716
- }, "copyExportPreview")
2717
- })));
2718
-
2719
- // src/store/use-bridge-store.ts
2720
- import { create as create5 } from "zustand";
2721
- import { subscribeWithSelector as subscribeWithSelector5 } from "zustand/middleware";
2722
- var useBridgeStore = create5()(subscribeWithSelector5((set, get) => ({
2723
- bridge: null,
2724
- localBridge: null,
2725
- bridgeLogs: [],
2726
- bridgeLogsSince: 0,
2727
- startedByTui: false,
2728
- webmcpChannels: [],
2729
- setBridgeData: /* @__PURE__ */ __name((bridge, localBridge) => set({
2730
- bridge,
2731
- localBridge
2732
- }), "setBridgeData"),
2733
- setLocalBridge: /* @__PURE__ */ __name((localBridge) => set({
2734
- localBridge
2735
- }), "setLocalBridge"),
2736
- setBridgeLogs: /* @__PURE__ */ __name((logs) => {
2737
- if (logs.length === 0) return;
2738
- const lastTimestamp = logs[logs.length - 1].timestamp;
2739
- set((prev) => ({
2740
- bridgeLogs: [
2741
- ...prev.bridgeLogs,
2742
- ...logs
2743
- ].slice(-200),
2744
- bridgeLogsSince: lastTimestamp
2745
- }));
2746
- }, "setBridgeLogs"),
2747
- clearBridgeLogs: /* @__PURE__ */ __name(() => set({
2748
- bridgeLogs: []
2749
- }), "clearBridgeLogs"),
2750
- setWebMcpChannels: /* @__PURE__ */ __name((channels) => set({
2751
- webmcpChannels: channels
2752
- }), "setWebMcpChannels"),
2753
- bridgeStart: /* @__PURE__ */ __name(() => {
2754
- const service2 = getService();
2755
- service2.startLocalBridgeDetached();
2756
- set({
2757
- startedByTui: true
2758
- });
2759
- appendSessionLog("[bridge] Started local bridge process (detached)");
2760
- setSessionStatusLine("Bridge start triggered (detached)");
2761
- }, "bridgeStart"),
2762
- bridgeStop: /* @__PURE__ */ __name(async () => {
2763
- const service2 = getService();
2764
- const { localBridge } = get();
2765
- await service2.stopLocalBridge(localBridge?.port);
2766
- if (localBridge) {
2767
- set({
2768
- localBridge: {
2769
- ...localBridge,
2770
- running: false,
2771
- uptimeSec: 0
2772
- },
2773
- webmcpChannels: []
2774
- });
2775
- }
2776
- appendSessionLog("[bridge] Stop signal sent");
2777
- setSessionStatusLine("Bridge stop signal sent");
2778
- }, "bridgeStop")
2779
- })));
2780
-
2781
- // src/store/store-effects.ts
2782
- function dispatchRefreshComplete(data) {
2783
- useProjectDataStore.getState().setProjectData(data.specs, data.decisions, data.workflow, data.navPolicy);
2784
- useExportStore.getState().setCapabilities(data.exportCapabilities);
2785
- useBridgeStore.getState().setBridgeData(data.bridge, data.localBridge);
2786
- }
2787
- __name(dispatchRefreshComplete, "dispatchRefreshComplete");
2788
- function dispatchClearProjectData() {
2789
- useProjectDataStore.getState().clearProjectData();
2790
- }
2791
- __name(dispatchClearProjectData, "dispatchClearProjectData");
2792
- function refreshOnAuthenticationError(message) {
2793
- if (!isAuthenticationError(message)) return;
2794
- const { appendLog, refresh } = useSessionStore.getState();
2795
- useSessionStore.setState({
2796
- statusLine: "Authentication required. Refreshing context..."
2797
- });
2798
- appendLog("[auth] action requires authentication, refreshing context");
2799
- void refresh();
2800
- }
2801
- __name(refreshOnAuthenticationError, "refreshOnAuthenticationError");
2802
- async function withSessionFeedback(opts) {
2803
- const { appendLog, refresh } = useSessionStore.getState();
2804
- useSessionStore.setState({
2805
- statusLine: opts.statusLine
2806
- });
2807
- try {
2808
- const result = await opts.action();
2809
- appendLog(opts.successLog);
2810
- if (opts.refresh !== false) {
2811
- await refresh();
2812
- }
2813
- return result;
2814
- } catch (error) {
2815
- const message = error instanceof Error ? error.message : String(error);
2816
- appendLog(`${opts.failureLog}: ${message}`);
2817
- useSessionStore.setState({
2818
- statusLine: opts.failureStatusLine
2819
- });
2820
- refreshOnAuthenticationError(message);
2821
- throw error;
2822
- }
2823
- }
2824
- __name(withSessionFeedback, "withSessionFeedback");
2825
- function getBootContext() {
2826
- return useSessionStore.getState().boot;
2827
- }
2828
- __name(getBootContext, "getBootContext");
2829
- function setSessionStatusLine(line) {
2830
- useSessionStore.setState({
2831
- statusLine: line
2832
- });
2833
- }
2834
- __name(setSessionStatusLine, "setSessionStatusLine");
2835
- function appendSessionLog(entry) {
2836
- useSessionStore.getState().appendLog(entry);
2837
- }
2838
- __name(appendSessionLog, "appendSessionLog");
2839
-
2840
- // src/store/use-session-store.ts
2841
- var onboardingInteractionResolver = null;
2842
- function requestOnboardingInteraction(request) {
2843
- return new Promise((resolve) => {
2844
- onboardingInteractionResolver = resolve;
2845
- useSessionStore.setState((prev) => ({
2846
- onboarding: prev.onboarding ? {
2847
- ...prev.onboarding,
2848
- interaction: request
2849
- } : prev.onboarding
2850
- }));
2851
- });
2852
- }
2853
- __name(requestOnboardingInteraction, "requestOnboardingInteraction");
2854
- function refreshOnAuthenticationError2(message) {
2855
- if (!isAuthenticationError(message)) return;
2856
- const { appendLog, refresh } = useSessionStore.getState();
2857
- useSessionStore.setState({
2858
- statusLine: "Authentication required. Refreshing context..."
2859
- });
2860
- appendLog("[auth] action requires authentication, refreshing context");
2861
- void refresh();
2862
- }
2863
- __name(refreshOnAuthenticationError2, "refreshOnAuthenticationError");
2864
- async function buildOnboardingState(mode) {
2865
- const service2 = getService();
2866
- const boot = useSessionStore.getState().boot;
2867
- const organizations = await service2.listOrganizations();
2868
- if (organizations.length === 0) {
2869
- return {
2870
- mode,
2871
- step: "create-organization",
2872
- attachCurrentFolder: mode === "initial-setup",
2873
- organizations: [],
2874
- projects: [],
2875
- availableAgents: [],
2876
- canCreateProject: false,
2877
- error: void 0
2878
- };
2879
- }
2880
- const preferredOrganizationId = boot?.organizationId;
2881
- const selectedOrganization = organizations.find((org) => org.id === preferredOrganizationId) ?? organizations[0];
2882
- const projects = await service2.listProjects(selectedOrganization.id);
2883
- return {
2884
- mode,
2885
- step: organizations.length === 1 ? "project" : "organization",
2886
- attachCurrentFolder: mode === "initial-setup",
2887
- organizations,
2888
- projects,
2889
- availableAgents: [],
2890
- canCreateProject: service2.canCreateProject(selectedOrganization),
2891
- selectedOrganizationId: selectedOrganization.id,
2892
- interaction: void 0,
2893
- error: void 0
2894
- };
2895
- }
2896
- __name(buildOnboardingState, "buildOnboardingState");
2897
- var useSessionStore = create6()(subscribeWithSelector6((set, get) => ({
2898
- boot: null,
2899
- auth: null,
2900
- onboarding: null,
2901
- loading: true,
2902
- error: null,
2903
- statusLine: "Bootstrapping...",
2904
- logs: [],
2905
- appendLog: /* @__PURE__ */ __name((entry) => {
2906
- const screen = useTuiUiStore.getState().screen;
2907
- const level = entry.startsWith("[error]") ? "error" : entry.startsWith("[warn]") ? "warn" : "info";
2908
- appendGlobalStructuredLog({
2909
- source: "tui.event-log",
2910
- level,
2911
- message: entry,
2912
- details: {
2913
- screen
2914
- }
2915
- });
2916
- set((prev) => ({
2917
- logs: [
2918
- entry,
2919
- ...prev.logs
2920
- ].slice(0, 40)
2921
- }));
2922
- }, "appendLog"),
2923
- setStatusLine: /* @__PURE__ */ __name((line) => set({
2924
- statusLine: line
2925
- }), "setStatusLine"),
2926
- setLoading: /* @__PURE__ */ __name((loading) => set({
2927
- loading
2928
- }), "setLoading"),
2929
- setError: /* @__PURE__ */ __name((error) => set({
2930
- error
2931
- }), "setError"),
2932
- authenticate: /* @__PURE__ */ __name(async () => {
2933
- const { appendLog } = get();
2934
- const service2 = getService();
2935
- set({
2936
- loading: false,
2937
- auth: {
2938
- status: "authenticating"
2939
- },
2940
- statusLine: "Starting browser login flow..."
2941
- });
2942
- appendLog("[auth] starting login flow");
2943
- const ok = await service2.authenticateViaCli((line) => {
2944
- appendLog(`[auth] ${line}`);
2945
- });
2946
- if (!ok) {
2947
- set({
2948
- auth: {
2949
- status: "auth_failed",
2950
- error: "Authentication failed. Check logs and try again."
2951
- },
2952
- statusLine: "Authentication failed"
2953
- });
2954
- appendLog("[auth] login flow failed");
2955
- return;
2956
- }
2957
- appendLog("[auth] login flow completed");
2958
- await get().refresh();
2959
- }, "authenticate"),
2960
- refresh: /* @__PURE__ */ __name(async (projectId) => {
2961
- const service2 = getService();
2962
- set((prev) => ({
2963
- loading: prev.boot ? false : true,
2964
- statusLine: "Loading context..."
2965
- }));
2966
- try {
2967
- const token = await service2.checkAuthentication();
2968
- if (!token) {
2969
- set({
2970
- loading: false,
2971
- error: null,
2972
- auth: {
2973
- status: "unauthenticated",
2974
- error: "No valid credentials. Please run `spekn auth login` to authenticate."
2975
- },
2976
- statusLine: "Authentication required"
2977
- });
2978
- return;
2979
- }
2980
- set({
2981
- auth: {
2982
- status: "authenticated",
2983
- userEmail: service2.extractUserEmail(token),
2984
- tokenExpiresAt: service2.extractTokenExpiry(token)
2985
- }
2986
- });
2987
- if (!projectId && !service2.hasLocalProjectContext()) {
2988
- const onboarding = await buildOnboardingState("initial-setup");
2989
- set({
2990
- loading: false,
2991
- error: null,
2992
- onboarding,
2993
- statusLine: "Project setup required"
2994
- });
2995
- return;
2996
- }
2997
- let bootstrapResult;
2998
- try {
2999
- bootstrapResult = await service2.bootstrap(projectId);
3000
- } catch (bootstrapError) {
3001
- if (bootstrapError instanceof Error && bootstrapError.message === "ONBOARDING_REQUIRED") {
3002
- const onboarding = await buildOnboardingState("initial-setup");
3003
- set({
3004
- loading: false,
3005
- error: null,
3006
- onboarding,
3007
- statusLine: "Project setup required"
3008
- });
3009
- return;
3010
- }
3011
- throw bootstrapError;
3012
- }
3013
- const { boot, client: client2 } = bootstrapResult;
3014
- setClient(client2);
3015
- const [specs, decisions, workflow, bridge, localBridge, exportCapabilities] = await Promise.all([
3016
- service2.loadSpecs(client2, boot.projectId),
3017
- service2.loadDecisions(client2, boot.projectId),
3018
- service2.loadWorkflowSummary(client2, boot.projectId),
3019
- service2.loadBridgeSummary(client2),
3020
- service2.loadLocalBridgeSummary(),
3021
- service2.discoverExportCapabilities(boot.projectId, boot.organizationId).catch(() => null)
3022
- ]);
3023
- const capabilityContext = {
3024
- plan: boot.plan,
3025
- role: boot.role,
3026
- workflowPhase: workflow.currentPhase,
3027
- permissions: boot.permissions
3028
- };
3029
- const navPolicy = resolveNavPolicy(capabilityContext);
3030
- dispatchRefreshComplete({
3031
- specs,
3032
- decisions,
3033
- workflow,
3034
- navPolicy,
3035
- exportCapabilities,
3036
- bridge,
3037
- localBridge
3038
- });
3039
- set({
3040
- boot,
3041
- loading: false,
3042
- error: null,
3043
- onboarding: null,
3044
- statusLine: "Ready"
3045
- });
3046
- } catch (error) {
3047
- const message = error instanceof Error ? error.message : String(error);
3048
- let authStatus = null;
3049
- if (message.includes("credentials") || message.includes("auth") || message.includes("token")) {
3050
- authStatus = {
3051
- status: "auth_failed",
3052
- error: message
3053
- };
3054
- }
3055
- set((prev) => ({
3056
- loading: false,
3057
- error: message,
3058
- auth: authStatus || prev.auth,
3059
- statusLine: "Error"
3060
- }));
3061
- get().appendLog(`[error] ${message}`);
3062
- }
3063
- }, "refresh"),
3064
- switchContext: /* @__PURE__ */ __name(async () => {
3065
- const { appendLog } = get();
3066
- set({
3067
- loading: true,
3068
- error: null,
3069
- statusLine: "Loading organizations..."
3070
- });
3071
- try {
3072
- const onboarding = await buildOnboardingState("switch-context");
3073
- set({
3074
- loading: false,
3075
- onboarding,
3076
- statusLine: "Switch organization/project"
3077
- });
3078
- appendLog("[context] switch mode opened");
3079
- } catch (error) {
3080
- const message = error instanceof Error ? error.message : String(error);
3081
- set({
3082
- loading: false,
3083
- statusLine: "Context switch failed",
3084
- error: message
3085
- });
3086
- appendLog(`[error] context switch failed: ${message}`);
3087
- refreshOnAuthenticationError2(message);
3088
- }
3089
- }, "switchContext"),
3090
- detachRepoContext: /* @__PURE__ */ __name(async () => {
3091
- const { boot, appendLog, refresh } = get();
3092
- const service2 = getService();
3093
- const result = await service2.detachContextViaCli(boot?.projectId, process.cwd());
3094
- if (!result.success) {
3095
- appendLog(`[error] Failed to detach context: ${result.output}`);
3096
- set({
3097
- statusLine: "Context detach failed"
3098
- });
3099
- return;
3100
- }
3101
- if (result.output) {
3102
- appendLog(`[context] ${result.output}`);
3103
- }
3104
- appendLog("[context] Detached repository from local project context");
3105
- set({
3106
- boot: null,
3107
- statusLine: "Repository detached. Select a project to attach."
3108
- });
3109
- dispatchClearProjectData();
3110
- await refresh();
3111
- }, "detachRepoContext"),
3112
- syncRepository: /* @__PURE__ */ __name(async (options) => {
3113
- const { boot, appendLog, refresh } = get();
3114
- const service2 = getService();
3115
- if (!boot) {
3116
- appendLog("[error] repository sync unavailable: no active project context");
3117
- set({
3118
- statusLine: "Repository sync unavailable"
3119
- });
3120
- return false;
3121
- }
3122
- appendLog("[repo] running sync (metadata + drift analysis)");
3123
- set({
3124
- statusLine: "Syncing repository..."
3125
- });
3126
- const result = await service2.syncRepositoryViaCli(boot.organizationId, boot.projectId, boot.repoPath, {
3127
- analyze: options?.analyze ?? true,
3128
- importToProject: options?.importToProject,
3129
- maxFiles: options?.maxFiles,
3130
- analysisEngine: options?.analysisEngine,
3131
- agent: options?.agent,
3132
- requestInteraction: options?.requestInteraction,
3133
- onProgress: /* @__PURE__ */ __name((line) => {
3134
- appendLog(`[repo] ${line}`);
3135
- options?.onProgress?.(line);
3136
- }, "onProgress"),
3137
- onActivity: /* @__PURE__ */ __name((event) => {
3138
- options?.onActivity?.(event);
3139
- }, "onActivity")
3140
- });
3141
- if (!result.success) {
3142
- appendLog(`[error] repository sync failed (exit ${result.exitCode})`);
3143
- set({
3144
- statusLine: "Repository sync failed"
3145
- });
3146
- refreshOnAuthenticationError2(result.output);
3147
- return false;
3148
- }
3149
- appendLog("[repo] sync completed");
3150
- set({
3151
- statusLine: "Repository sync completed"
3152
- });
3153
- await refresh();
3154
- return true;
3155
- }, "syncRepository"),
3156
- // Onboarding actions
3157
- selectOnboardingOrganization: /* @__PURE__ */ __name(async (index) => {
3158
- const { onboarding, appendLog } = get();
3159
- const service2 = getService();
3160
- if (!onboarding) return;
3161
- if (index < 0 || index >= onboarding.organizations.length) {
3162
- set((prev) => ({
3163
- onboarding: prev.onboarding ? {
3164
- ...prev.onboarding,
3165
- error: `Invalid organization index: ${index + 1}`
3166
- } : prev.onboarding
3167
- }));
3168
- return;
3169
- }
3170
- const selectedOrganization = onboarding.organizations[index];
3171
- set((prev) => ({
3172
- loading: true,
3173
- statusLine: "Loading projects...",
3174
- onboarding: prev.onboarding ? {
3175
- ...prev.onboarding,
3176
- selectedOrganizationId: selectedOrganization.id,
3177
- error: void 0
3178
- } : prev.onboarding
3179
- }));
3180
- try {
3181
- const projects = await service2.listProjects(selectedOrganization.id);
3182
- set((prev) => ({
3183
- loading: false,
3184
- statusLine: "Select a project",
3185
- onboarding: prev.onboarding ? {
3186
- ...prev.onboarding,
3187
- step: "project",
3188
- attachCurrentFolder: prev.onboarding.attachCurrentFolder,
3189
- projects,
3190
- availableAgents: prev.onboarding?.availableAgents ?? [],
3191
- canCreateProject: service2.canCreateProject(selectedOrganization),
3192
- selectedOrganizationId: selectedOrganization.id,
3193
- interaction: void 0,
3194
- error: projects.length === 0 ? "No projects found in selected organization." : void 0
3195
- } : prev.onboarding
3196
- }));
3197
- } catch (error) {
3198
- const message = error instanceof Error ? error.message : String(error);
3199
- set((prev) => ({
3200
- loading: false,
3201
- statusLine: "Setup error",
3202
- onboarding: prev.onboarding ? {
3203
- ...prev.onboarding,
3204
- error: message
3205
- } : prev.onboarding
3206
- }));
3207
- }
3208
- }, "selectOnboardingOrganization"),
3209
- registerOnboardingProject: /* @__PURE__ */ __name(async (index) => {
3210
- const { onboarding, appendLog, refresh } = get();
3211
- const service2 = getService();
3212
- if (!onboarding || !onboarding.selectedOrganizationId) return;
3213
- if (index < 0 || index >= onboarding.projects.length) {
3214
- set((prev) => ({
3215
- onboarding: prev.onboarding ? {
3216
- ...prev.onboarding,
3217
- error: `Invalid project index: ${index + 1}`
3218
- } : prev.onboarding
3219
- }));
3220
- return;
3221
- }
3222
- const selectedProject = onboarding.projects[index];
3223
- if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
3224
- set((prev) => ({
3225
- loading: true,
3226
- statusLine: "Switching context...",
3227
- onboarding: prev.onboarding ? {
3228
- ...prev.onboarding,
3229
- error: void 0
3230
- } : prev.onboarding
3231
- }));
3232
- try {
3233
- service2.persistContext(onboarding.selectedOrganizationId, selectedProject.id);
3234
- appendLog(`[context] switched to ${selectedProject.name}`);
3235
- await refresh();
3236
- } catch (error) {
3237
- const message = error instanceof Error ? error.message : String(error);
3238
- set((prev) => ({
3239
- loading: false,
3240
- statusLine: "Context switch failed",
3241
- onboarding: prev.onboarding ? {
3242
- ...prev.onboarding,
3243
- step: "project",
3244
- error: message
3245
- } : prev.onboarding
3246
- }));
3247
- }
3248
- return;
3249
- }
3250
- set((prev) => ({
3251
- loading: true,
3252
- statusLine: "Linking repository...",
3253
- onboarding: prev.onboarding ? {
3254
- ...prev.onboarding,
3255
- error: void 0
3256
- } : prev.onboarding
3257
- }));
3258
- try {
3259
- persistProjectContext(process.cwd(), {
3260
- projectId: selectedProject.id,
3261
- organizationId: onboarding.selectedOrganizationId
3262
- });
3263
- appendLog(`[context] linked to ${selectedProject.name}`);
3264
- await refresh();
3265
- } catch (error) {
3266
- const message = error instanceof Error ? error.message : String(error);
3267
- set((prev) => ({
3268
- loading: false,
3269
- statusLine: "Setup error",
3270
- onboarding: prev.onboarding ? {
3271
- ...prev.onboarding,
3272
- step: "project",
3273
- error: message
3274
- } : prev.onboarding
3275
- }));
3276
- }
3277
- }, "registerOnboardingProject"),
3278
- createOnboardingProject: /* @__PURE__ */ __name(async (name) => {
3279
- const { onboarding, appendLog, refresh } = get();
3280
- const service2 = getService();
3281
- if (!onboarding || !onboarding.selectedOrganizationId) return;
3282
- const trimmed = name.trim();
3283
- if (!onboarding.canCreateProject) {
3284
- set((prev) => ({
3285
- onboarding: prev.onboarding ? {
3286
- ...prev.onboarding,
3287
- error: "You are not authorized to create projects in this organization."
3288
- } : prev.onboarding
3289
- }));
3290
- return;
3291
- }
3292
- if (trimmed.length < 2) {
3293
- set((prev) => ({
3294
- onboarding: prev.onboarding ? {
3295
- ...prev.onboarding,
3296
- error: "Project name must be at least 2 characters."
3297
- } : prev.onboarding
3298
- }));
3299
- return;
3300
- }
3301
- set((prev) => ({
3302
- loading: true,
3303
- statusLine: "Creating project...",
3304
- onboarding: prev.onboarding ? {
3305
- ...prev.onboarding,
3306
- error: void 0
3307
- } : prev.onboarding
3308
- }));
3309
- try {
3310
- const created = await service2.createProject(onboarding.selectedOrganizationId, trimmed);
3311
- appendLog(`[setup] Created project "${created.name}"`);
3312
- if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
3313
- service2.persistContext(onboarding.selectedOrganizationId, created.id);
3314
- appendLog(`[context] switched to ${created.name}`);
3315
- await refresh();
3316
- return;
3317
- }
3318
- const registerStartedAt = Date.now();
3319
- set((prev) => ({
3320
- loading: true,
3321
- statusLine: "Registering repository...",
3322
- onboarding: prev.onboarding ? {
3323
- ...prev.onboarding,
3324
- step: "registering",
3325
- availableAgents: prev.onboarding?.availableAgents ?? [],
3326
- selectedProjectId: created.id,
3327
- runLines: [],
3328
- runStatus: "running",
3329
- startedAt: registerStartedAt,
3330
- interaction: void 0,
3331
- error: void 0
3332
- } : prev.onboarding
3333
- }));
3334
- useOnboardingWindow.getState().setStartedAt(registerStartedAt);
3335
- await attachRepositoryFromOnboardingZustand({
3336
- organizationId: onboarding.selectedOrganizationId,
3337
- projectId: created.id
3338
- });
3339
- await refresh();
3340
- } catch (error) {
3341
- const message = error instanceof Error ? error.message : String(error);
3342
- set((prev) => ({
3343
- loading: false,
3344
- statusLine: "Setup error",
3345
- onboarding: prev.onboarding ? {
3346
- ...prev.onboarding,
3347
- error: message
3348
- } : prev.onboarding
3349
- }));
3350
- }
3351
- }, "createOnboardingProject"),
3352
- resolveOnboardingInteraction: /* @__PURE__ */ __name((value) => {
3353
- const resolver = onboardingInteractionResolver;
3354
- onboardingInteractionResolver = null;
3355
- set((prev) => ({
3356
- onboarding: prev.onboarding ? {
3357
- ...prev.onboarding,
3358
- interaction: void 0
3359
- } : prev.onboarding
3360
- }));
3361
- if (resolver) resolver(value);
3362
- }, "resolveOnboardingInteraction"),
3363
- setOnboardingAttachCurrentFolder: /* @__PURE__ */ __name((attach) => {
3364
- set((prev) => ({
3365
- onboarding: prev.onboarding ? prev.onboarding.attachCurrentFolder === attach ? prev.onboarding : {
3366
- ...prev.onboarding,
3367
- attachCurrentFolder: attach
3368
- } : prev.onboarding
3369
- }));
3370
- }, "setOnboardingAttachCurrentFolder")
3371
- })));
3372
- async function attachRepositoryFromOnboardingZustand(input) {
3373
- const service2 = getService();
3374
- const { appendLog } = useSessionStore.getState();
3375
- const result = await service2.attachOrSyncCurrentRepository(input.organizationId, input.projectId, (line) => {
3376
- appendLog(`[setup] ${line}`);
3377
- useSessionStore.setState((prev) => ({
3378
- statusLine: line.slice(0, 100),
3379
- onboarding: prev.onboarding ? {
3380
- ...prev.onboarding,
3381
- runLines: [
3382
- ...prev.onboarding.runLines ?? [],
3383
- line
3384
- ].slice(-400)
3385
- } : prev.onboarding
3386
- }));
3387
- }, void 0, requestOnboardingInteraction, (event) => {
3388
- const { upsertToolCall, setActiveThought } = useOnboardingWindow.getState();
3389
- if (event.event === "tool_call" || event.event === "tool_call_update") {
3390
- upsertToolCall(event);
3391
- } else if (event.event === "agent_thought") {
3392
- setActiveThought(event.text);
3393
- } else if (event.event === "agent_chunk" && event.text) {
3394
- useSessionStore.setState((prev) => {
3395
- if (!prev.onboarding) return prev;
3396
- const lines = [
3397
- ...prev.onboarding.runLines ?? []
3398
- ];
3399
- const parts = event.text.split("\n");
3400
- if (lines.length === 0) {
3401
- lines.push(parts[0]);
3402
- } else {
3403
- lines[lines.length - 1] += parts[0];
3404
- }
3405
- for (let i = 1; i < parts.length; i++) {
3406
- lines.push(parts[i]);
3407
- }
3408
- return {
3409
- onboarding: {
3410
- ...prev.onboarding,
3411
- runLines: lines.slice(-400)
3412
- }
3413
- };
3414
- });
3415
- }
3416
- });
3417
- useSessionStore.setState((prev) => ({
3418
- onboarding: prev.onboarding ? {
3419
- ...prev.onboarding,
3420
- runStatus: result.warning ? "error" : "success"
3421
- } : prev.onboarding
3422
- }));
3423
- logOnboardingAttachResult(appendLog, result);
3424
- }
3425
- __name(attachRepositoryFromOnboardingZustand, "attachRepositoryFromOnboardingZustand");
3426
-
3427
- export {
3428
- __name,
3429
- appendGlobalStructuredLog,
3430
- loadWebMcpChannels,
3431
- initServiceBridge,
3432
- getService,
3433
- getClient,
3434
- setInitialScreen,
3435
- useTuiUiStore,
3436
- resolveNavPolicy,
3437
- useOnboardingWindow,
3438
- buildOnboardingState,
3439
- useSessionStore,
3440
- useProjectDataStore,
3441
- useExportStore,
3442
- useBridgeStore
3443
- };