@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,3444 +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
- generationNumber: typeof spec.generationNumber === "number" ? spec.generationNumber : 1,
1612
- generationStatus: typeof spec.generationStatus === "string" ? spec.generationStatus : spec.status,
1613
- updatedAt: spec.updatedAt,
1614
- type: typeof frontmatter.type === "string" ? frontmatter.type : void 0,
1615
- content: typeof spec.content === "string" ? spec.content : void 0,
1616
- tags: tags.length > 0 ? tags : void 0,
1617
- author: typeof frontmatter.author === "string" ? frontmatter.author : void 0,
1618
- hintCounts: {
1619
- constraints: countArray(hints.constraints),
1620
- requirements: countArray(hints.requirements),
1621
- technical: countArray(hints.technical),
1622
- guidance: countArray(hints.guidance)
1623
- },
1624
- relationCounts: {
1625
- dependsOn: countArray(frontmatter.dependsOn),
1626
- conflictsWith: countArray(frontmatter.conflictsWith),
1627
- compatibleWith: countArray(frontmatter.compatibleWith)
1628
- },
1629
- acpPolicyMode: typeof acp.policyMode === "string" ? acp.policyMode : void 0,
1630
- acpAllowedAgents: acpAllowedAgents.length > 0 ? acpAllowedAgents : void 0,
1631
- aiTokenBudget: typeof aiContext.tokenBudget === "number" ? aiContext.tokenBudget : void 0,
1632
- aiFocusAreas: aiFocusAreas.length > 0 ? aiFocusAreas : void 0
1633
- };
1634
- });
1635
- }
1636
- async updateSpecificationContent(client2, projectId, specificationId, content) {
1637
- await client2.specification.update.mutate({
1638
- projectId,
1639
- id: specificationId,
1640
- data: {
1641
- content,
1642
- changeType: "patch",
1643
- changeDescription: "Edited from TUI editor"
1644
- }
1645
- });
1646
- }
1647
- async updateSpecificationStatus(client2, projectId, specificationId, status) {
1648
- await client2.specification.update.mutate({
1649
- projectId,
1650
- id: specificationId,
1651
- data: {
1652
- status,
1653
- changeType: "metadata",
1654
- changeDescription: `Status changed to ${status} from TUI`
1655
- }
1656
- });
1657
- }
1658
- async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1659
- const deleteMutation = client2?.specification?.delete?.mutate;
1660
- if (typeof deleteMutation !== "function") {
1661
- throw new Error("Specification delete route is unavailable.");
1662
- }
1663
- await deleteMutation({
1664
- projectId,
1665
- id: specificationId,
1666
- mode
1667
- });
1668
- }
1669
- async refineSpecificationWithAi(client2, input) {
1670
- const refineMutation = client2?.specification?.refine?.mutate;
1671
- if (typeof refineMutation !== "function") {
1672
- throw new Error("Specification refine route is unavailable.");
1673
- }
1674
- const result = await refineMutation({
1675
- projectId: input.projectId,
1676
- specificationContent: input.specContent,
1677
- userMessage: input.userMessage,
1678
- agentType: input.agentType
1679
- });
1680
- if (typeof result?.content !== "string") {
1681
- throw new Error("AI refinement response was missing content.");
1682
- }
1683
- return result.content;
1684
- }
1685
- };
1686
-
1687
- // src/services/context-service.ts
1688
- var TuiContextService = class {
1689
- static {
1690
- __name(this, "TuiContextService");
1691
- }
1692
- apiUrl;
1693
- authService;
1694
- bootstrapService;
1695
- bridgeService;
1696
- decisionService;
1697
- exportService;
1698
- organizationService;
1699
- repoService;
1700
- specService;
1701
- constructor(apiUrl) {
1702
- this.apiUrl = apiUrl;
1703
- this.authService = new AuthService(apiUrl);
1704
- this.bootstrapService = new BootstrapService(apiUrl);
1705
- this.bridgeService = new BridgeService(apiUrl);
1706
- this.decisionService = new DecisionService();
1707
- this.exportService = new ExportService(apiUrl);
1708
- this.organizationService = new OrganizationService(apiUrl);
1709
- this.repoService = new RepoService(apiUrl);
1710
- this.specService = new SpecService();
1711
- }
1712
- // ── Bootstrap ──────────────────────────────────────────────────────
1713
- async bootstrap(projectIdArg) {
1714
- return this.bootstrapService.bootstrap(projectIdArg);
1715
- }
1716
- hasDeclaredProjectContext(projectIdArg) {
1717
- return this.bootstrapService.hasDeclaredProjectContext(projectIdArg);
1718
- }
1719
- hasLocalProjectContext(repoPath) {
1720
- return this.bootstrapService.hasLocalProjectContext(repoPath);
1721
- }
1722
- async loadWorkflowSummary(client2, projectId) {
1723
- return this.bootstrapService.loadWorkflowSummary(client2, projectId);
1724
- }
1725
- persistContext(organizationId, projectId) {
1726
- this.bootstrapService.persistContext(organizationId, projectId);
1727
- }
1728
- // ── Auth ───────────────────────────────────────────────────────────
1729
- async checkAuthentication() {
1730
- return this.authService.checkAuthentication();
1731
- }
1732
- async authenticateViaCli(onProgress) {
1733
- return this.authService.authenticateViaCli(onProgress);
1734
- }
1735
- extractUserEmail(token) {
1736
- return this.authService.extractUserEmail(token);
1737
- }
1738
- extractTokenExpiry(token) {
1739
- return this.authService.extractTokenExpiry(token);
1740
- }
1741
- // ── Organization & Project ─────────────────────────────────────────
1742
- async listOrganizations() {
1743
- return this.organizationService.listOrganizations();
1744
- }
1745
- async createOrganization(input) {
1746
- return this.organizationService.createOrganization(input);
1747
- }
1748
- async listProjects(organizationId) {
1749
- return this.organizationService.listProjects(organizationId);
1750
- }
1751
- async createProject(organizationId, name) {
1752
- return this.organizationService.createProject(organizationId, name);
1753
- }
1754
- canCreateProject(org) {
1755
- return this.organizationService.canCreateProject(org);
1756
- }
1757
- // ── Specs ──────────────────────────────────────────────────────────
1758
- async loadSpecs(client2, projectId) {
1759
- return this.specService.loadSpecs(client2, projectId);
1760
- }
1761
- async updateSpecificationContent(client2, projectId, specificationId, content) {
1762
- return this.specService.updateSpecificationContent(client2, projectId, specificationId, content);
1763
- }
1764
- async updateSpecificationStatus(client2, projectId, specificationId, status) {
1765
- return this.specService.updateSpecificationStatus(client2, projectId, specificationId, status);
1766
- }
1767
- async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1768
- return this.specService.deleteSpecification(client2, projectId, specificationId, mode);
1769
- }
1770
- async refineSpecificationWithAi(client2, input) {
1771
- return this.specService.refineSpecificationWithAi(client2, input);
1772
- }
1773
- // ── Decisions ──────────────────────────────────────────────────────
1774
- async loadDecisions(client2, projectId) {
1775
- return this.decisionService.loadDecisions(client2, projectId);
1776
- }
1777
- async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1778
- return this.decisionService.resolveDecision(client2, projectId, decisionId, status, reason, existingRationale);
1779
- }
1780
- async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1781
- return this.decisionService.deleteDecision(client2, projectId, decisionId, mode);
1782
- }
1783
- // ── Export ─────────────────────────────────────────────────────────
1784
- async previewExport(client2, projectId, format) {
1785
- return this.exportService.previewExport(client2, projectId, format);
1786
- }
1787
- async generateExport(client2, projectId, format) {
1788
- return this.exportService.generateExport(client2, projectId, format);
1789
- }
1790
- async discoverExportCapabilities(projectId, organizationId) {
1791
- return this.exportService.discoverExportCapabilities(projectId, organizationId);
1792
- }
1793
- async exportStatus(projectId, format, options) {
1794
- return this.exportService.exportStatus(projectId, format, options);
1795
- }
1796
- async deliverExport(projectId, format, delivery, options) {
1797
- return this.exportService.deliverExport(projectId, format, delivery, options);
1798
- }
1799
- // ── Bridge ─────────────────────────────────────────────────────────
1800
- async loadBridgeSummary(client2) {
1801
- return this.bridgeService.loadBridgeSummary(client2);
1802
- }
1803
- async loadLocalBridgeSummary() {
1804
- return this.bridgeService.loadLocalBridgeSummary();
1805
- }
1806
- startLocalBridgeDetached() {
1807
- this.bridgeService.startLocalBridgeDetached();
1808
- }
1809
- async stopLocalBridge(configPort) {
1810
- return this.bridgeService.stopLocalBridge(configPort);
1811
- }
1812
- async loadBridgeLogs(port, since) {
1813
- return this.bridgeService.loadBridgeLogs(port, since);
1814
- }
1815
- // ── Repository ─────────────────────────────────────────────────────
1816
- attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
1817
- return this.repoService.attachOrSyncCurrentRepository(organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity);
1818
- }, "attachOrSyncCurrentRepository");
1819
- async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1820
- return this.repoService.syncRepositoryViaCli(organizationId, projectId, repoPathInput, options);
1821
- }
1822
- async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1823
- return this.repoService.detachContextViaCli(_projectId, repoPath);
1824
- }
1825
- };
1826
-
1827
- // src/store/service-bridge.ts
1828
- var service = null;
1829
- var client = null;
1830
- function initServiceBridge(apiUrl) {
1831
- if (!service) {
1832
- service = new TuiContextService(apiUrl);
1833
- }
1834
- return service;
1835
- }
1836
- __name(initServiceBridge, "initServiceBridge");
1837
- function getService() {
1838
- if (!service) {
1839
- throw new Error("Service bridge not initialized. Call initServiceBridge() first.");
1840
- }
1841
- return service;
1842
- }
1843
- __name(getService, "getService");
1844
- function getClient() {
1845
- return client;
1846
- }
1847
- __name(getClient, "getClient");
1848
- function setClient(c) {
1849
- client = c;
1850
- }
1851
- __name(setClient, "setClient");
1852
-
1853
- // src/store/use-tui-ui-store.ts
1854
- import { create } from "zustand";
1855
- import { subscribeWithSelector } from "zustand/middleware";
1856
- var _initialScreen = "home";
1857
- function setInitialScreen(screen) {
1858
- _initialScreen = screen;
1859
- }
1860
- __name(setInitialScreen, "setInitialScreen");
1861
- var initialState = {
1862
- screen: _initialScreen,
1863
- showHelp: false,
1864
- commandMode: false,
1865
- searchQuery: "",
1866
- navMode: "content",
1867
- cursorSpec: null,
1868
- cursorDecision: null,
1869
- openedSpecId: void 0,
1870
- editorMenuOpen: false,
1871
- statusMenuOpen: false,
1872
- aiRefineMenuOpen: false,
1873
- editorLaunching: false,
1874
- selectedEditor: "",
1875
- selectedOrganizationIndex: void 0,
1876
- selectedProjectIndex: void 0,
1877
- newProjectName: void 0,
1878
- selectedAnalysisAgent: "auto"
1879
- };
1880
- var useTuiUiStore = create()(subscribeWithSelector((set) => ({
1881
- ...initialState,
1882
- screen: _initialScreen,
1883
- setScreen: /* @__PURE__ */ __name((screen) => set({
1884
- screen
1885
- }), "setScreen"),
1886
- toggleHelp: /* @__PURE__ */ __name(() => set((prev) => ({
1887
- showHelp: !prev.showHelp
1888
- })), "toggleHelp"),
1889
- setShowHelp: /* @__PURE__ */ __name((show) => set({
1890
- showHelp: show
1891
- }), "setShowHelp"),
1892
- setCommandMode: /* @__PURE__ */ __name((enabled) => set({
1893
- commandMode: enabled
1894
- }), "setCommandMode"),
1895
- setSearchQuery: /* @__PURE__ */ __name((query) => set({
1896
- searchQuery: query
1897
- }), "setSearchQuery"),
1898
- setNavMode: /* @__PURE__ */ __name((mode) => set({
1899
- navMode: mode
1900
- }), "setNavMode"),
1901
- setCursorSpec: /* @__PURE__ */ __name((spec) => set({
1902
- cursorSpec: spec
1903
- }), "setCursorSpec"),
1904
- setCursorDecision: /* @__PURE__ */ __name((decision) => set({
1905
- cursorDecision: decision
1906
- }), "setCursorDecision"),
1907
- setOpenedSpecId: /* @__PURE__ */ __name((specId) => set({
1908
- openedSpecId: specId
1909
- }), "setOpenedSpecId"),
1910
- setSelectedEditor: /* @__PURE__ */ __name((editor) => set({
1911
- selectedEditor: editor
1912
- }), "setSelectedEditor"),
1913
- setEditorMenuOpen: /* @__PURE__ */ __name((open) => set({
1914
- editorMenuOpen: open
1915
- }), "setEditorMenuOpen"),
1916
- setStatusMenuOpen: /* @__PURE__ */ __name((open) => set({
1917
- statusMenuOpen: open
1918
- }), "setStatusMenuOpen"),
1919
- setAiRefineMenuOpen: /* @__PURE__ */ __name((open) => set({
1920
- aiRefineMenuOpen: open
1921
- }), "setAiRefineMenuOpen"),
1922
- setEditorLaunching: /* @__PURE__ */ __name((launching) => set({
1923
- editorLaunching: launching
1924
- }), "setEditorLaunching"),
1925
- openEditorMenuForSpec: /* @__PURE__ */ __name((specId, editor) => set({
1926
- openedSpecId: specId,
1927
- selectedEditor: editor,
1928
- editorMenuOpen: true
1929
- }), "openEditorMenuForSpec"),
1930
- resetSpecsUi: /* @__PURE__ */ __name(() => set({
1931
- openedSpecId: void 0,
1932
- cursorSpec: null,
1933
- editorMenuOpen: false,
1934
- statusMenuOpen: false,
1935
- aiRefineMenuOpen: false,
1936
- editorLaunching: false
1937
- }), "resetSpecsUi"),
1938
- setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
1939
- selectedOrganizationIndex: index
1940
- }), "setSelectedOrganizationIndex"),
1941
- setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
1942
- selectedProjectIndex: index
1943
- }), "setSelectedProjectIndex"),
1944
- setNewProjectName: /* @__PURE__ */ __name((name) => set({
1945
- newProjectName: name
1946
- }), "setNewProjectName"),
1947
- setSelectedAnalysisAgent: /* @__PURE__ */ __name((agent) => set({
1948
- selectedAnalysisAgent: agent
1949
- }), "setSelectedAnalysisAgent"),
1950
- resetOnboardingUi: /* @__PURE__ */ __name(() => set({
1951
- selectedOrganizationIndex: void 0,
1952
- selectedProjectIndex: void 0,
1953
- newProjectName: void 0,
1954
- selectedAnalysisAgent: "auto"
1955
- }), "resetOnboardingUi"),
1956
- showTooltip: /* @__PURE__ */ __name((message, duration = 3e3) => set((state) => {
1957
- if (state.tooltipTimeout) {
1958
- clearTimeout(state.tooltipTimeout);
1959
- }
1960
- const timeout = setTimeout(() => {
1961
- useTuiUiStore.getState().clearTooltip();
1962
- }, duration);
1963
- return {
1964
- tooltip: message,
1965
- tooltipTimeout: timeout
1966
- };
1967
- }), "showTooltip"),
1968
- clearTooltip: /* @__PURE__ */ __name(() => set((state) => {
1969
- if (state.tooltipTimeout) {
1970
- clearTimeout(state.tooltipTimeout);
1971
- }
1972
- return {
1973
- tooltip: void 0,
1974
- tooltipTimeout: void 0
1975
- };
1976
- }), "clearTooltip")
1977
- })));
1978
-
1979
- // src/capabilities/policy.ts
1980
- var TIER_ORDER = {
1981
- [OrganizationPlan.FREE]: 0,
1982
- [OrganizationPlan.PRO]: 1,
1983
- [OrganizationPlan.TEAM]: 2,
1984
- [OrganizationPlan.ENTERPRISE]: 3
1985
- };
1986
- var NAV_DEFINITIONS = [
1987
- {
1988
- id: "home",
1989
- label: "Home",
1990
- description: "Next actions and workflow pulse",
1991
- requiredPlan: OrganizationPlan.FREE
1992
- },
1993
- {
1994
- id: "specs",
1995
- label: "Specs",
1996
- description: "Manage governed specifications",
1997
- requiredPlan: OrganizationPlan.FREE
1998
- },
1999
- {
2000
- id: "decisions",
2001
- label: "Decision Log",
2002
- description: "Review decisions and rationale",
2003
- requiredPlan: OrganizationPlan.FREE
2004
- },
2005
- {
2006
- id: "export",
2007
- label: "Export",
2008
- description: "Generate AGENTS.md / CLAUDE.md / .cursorrules",
2009
- requiredPlan: OrganizationPlan.FREE
2010
- },
2011
- {
2012
- id: "bridge",
2013
- label: "Local Bridge",
2014
- description: "Bridge status and controls",
2015
- requiredPlan: OrganizationPlan.FREE
2016
- },
2017
- {
2018
- id: "active-runs",
2019
- label: "Active Runs",
2020
- description: "Realtime orchestration dashboard",
2021
- requiredPlan: OrganizationPlan.TEAM
2022
- },
2023
- {
2024
- id: "phase-gates",
2025
- label: "Phase Gates",
2026
- description: "Approve and unblock workflow phases",
2027
- requiredPlan: OrganizationPlan.TEAM
2028
- },
2029
- {
2030
- id: "skills-marketplace",
2031
- label: "Skills Marketplace",
2032
- description: "Manage shared managed skills",
2033
- requiredPlan: OrganizationPlan.TEAM
2034
- },
2035
- {
2036
- id: "org-governance",
2037
- label: "Org Governance",
2038
- description: "Compliance, policy, deployment gates",
2039
- requiredPlan: OrganizationPlan.ENTERPRISE
2040
- }
2041
- ];
2042
- var GATE_DISABLED_PHASES = [
2043
- WorkflowPhase.SPECIFY,
2044
- WorkflowPhase.CLARIFY
2045
- ];
2046
- function meetsMinimumTier(current, required) {
2047
- return TIER_ORDER[current] >= TIER_ORDER[required];
2048
- }
2049
- __name(meetsMinimumTier, "meetsMinimumTier");
2050
- function resolveNavPolicy(ctx) {
2051
- return NAV_DEFINITIONS.map((item) => {
2052
- if (!meetsMinimumTier(ctx.plan, item.requiredPlan)) {
2053
- return {
2054
- ...item,
2055
- state: "locked",
2056
- reason: `Requires ${item.requiredPlan.toUpperCase()} tier`
2057
- };
2058
- }
2059
- if (item.id === "phase-gates" && ctx.role === "viewer") {
2060
- return {
2061
- ...item,
2062
- state: "disabled",
2063
- reason: "Viewer role cannot approve gates"
2064
- };
2065
- }
2066
- if (item.id === "phase-gates" && ctx.workflowPhase && GATE_DISABLED_PHASES.includes(ctx.workflowPhase)) {
2067
- return {
2068
- ...item,
2069
- state: "disabled",
2070
- reason: `Gate approvals are unavailable in ${ctx.workflowPhase} phase`
2071
- };
2072
- }
2073
- return {
2074
- ...item,
2075
- state: "enabled"
2076
- };
2077
- });
2078
- }
2079
- __name(resolveNavPolicy, "resolveNavPolicy");
2080
-
2081
- // src/state/onboarding-utils.ts
2082
- function logOnboardingAttachResult(appendLog, result) {
2083
- if (result.warning) {
2084
- appendLog(`[warn] ${result.warning}`);
2085
- }
2086
- if (result.analyzed) {
2087
- appendLog("[setup] Repository attached and analysis complete.");
2088
- } else if (result.warning) {
2089
- appendLog("[setup] Repository attached; analysis did not fully complete.");
2090
- } else {
2091
- appendLog("[setup] Repository already attached. Metadata sync complete (analysis skipped).");
2092
- }
2093
- }
2094
- __name(logOnboardingAttachResult, "logOnboardingAttachResult");
2095
-
2096
- // src/store/windows/use-onboarding-window.ts
2097
- import { create as create2 } from "zustand";
2098
- import { subscribeWithSelector as subscribeWithSelector2 } from "zustand/middleware";
2099
- var useOnboardingWindow = create2()(subscribeWithSelector2((set) => ({
2100
- mode: "initial-setup",
2101
- step: "organization",
2102
- attachCurrentFolder: true,
2103
- runLines: [],
2104
- runStatus: "running",
2105
- startedAt: null,
2106
- availableAgents: [],
2107
- canCreateProject: false,
2108
- toolCalls: {},
2109
- setMode: /* @__PURE__ */ __name((mode) => set({
2110
- mode
2111
- }), "setMode"),
2112
- setStep: /* @__PURE__ */ __name((step) => set({
2113
- step
2114
- }), "setStep"),
2115
- setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
2116
- selectedOrganizationIndex: index
2117
- }), "setSelectedOrganizationIndex"),
2118
- setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
2119
- selectedProjectIndex: index
2120
- }), "setSelectedProjectIndex"),
2121
- setNewProjectName: /* @__PURE__ */ __name((name) => set({
2122
- newProjectName: name
2123
- }), "setNewProjectName"),
2124
- setAttachCurrentFolder: /* @__PURE__ */ __name((attach) => set({
2125
- attachCurrentFolder: attach
2126
- }), "setAttachCurrentFolder"),
2127
- setRunLines: /* @__PURE__ */ __name((lines) => set({
2128
- runLines: lines
2129
- }), "setRunLines"),
2130
- addRunLine: /* @__PURE__ */ __name((line) => set((state) => ({
2131
- runLines: [
2132
- ...state.runLines,
2133
- line
2134
- ].slice(-400)
2135
- })), "addRunLine"),
2136
- setRunStatus: /* @__PURE__ */ __name((status) => set({
2137
- runStatus: status
2138
- }), "setRunStatus"),
2139
- setStartedAt: /* @__PURE__ */ __name((ts) => set({
2140
- startedAt: ts
2141
- }), "setStartedAt"),
2142
- setInteraction: /* @__PURE__ */ __name((interaction) => set({
2143
- interaction
2144
- }), "setInteraction"),
2145
- setError: /* @__PURE__ */ __name((error) => set({
2146
- error
2147
- }), "setError"),
2148
- setSelectedOrganizationId: /* @__PURE__ */ __name((id) => set({
2149
- selectedOrganizationId: id
2150
- }), "setSelectedOrganizationId"),
2151
- setSelectedProjectId: /* @__PURE__ */ __name((id) => set({
2152
- selectedProjectId: id
2153
- }), "setSelectedProjectId"),
2154
- setAvailableAgents: /* @__PURE__ */ __name((agents) => set({
2155
- availableAgents: agents
2156
- }), "setAvailableAgents"),
2157
- setCanCreateProject: /* @__PURE__ */ __name((canCreate) => set({
2158
- canCreateProject: canCreate
2159
- }), "setCanCreateProject"),
2160
- upsertToolCall: /* @__PURE__ */ __name((event) => set((state) => {
2161
- const id = event.toolCallId ?? `tc-${Date.now()}`;
2162
- const existing = state.toolCalls[id];
2163
- const updated = existing ? {
2164
- ...existing,
2165
- status: event.status ?? existing.status,
2166
- title: event.title ?? existing.title,
2167
- locations: event.locations ?? existing.locations,
2168
- completedAt: event.status === "completed" || event.status === "failed" ? Date.now() : existing.completedAt
2169
- } : {
2170
- toolCallId: id,
2171
- title: event.title ?? event.toolName ?? "Tool call",
2172
- toolName: event.toolName,
2173
- kind: event.kind ?? "other",
2174
- status: event.status ?? "in_progress",
2175
- locations: event.locations ?? [],
2176
- startedAt: Date.now()
2177
- };
2178
- return {
2179
- toolCalls: {
2180
- ...state.toolCalls,
2181
- [id]: updated
2182
- }
2183
- };
2184
- }), "upsertToolCall"),
2185
- setActiveThought: /* @__PURE__ */ __name((text) => set({
2186
- activeThought: text
2187
- }), "setActiveThought"),
2188
- reset: /* @__PURE__ */ __name(() => set({
2189
- mode: "initial-setup",
2190
- step: "organization",
2191
- selectedOrganizationIndex: void 0,
2192
- selectedProjectIndex: void 0,
2193
- newProjectName: void 0,
2194
- attachCurrentFolder: true,
2195
- runLines: [],
2196
- runStatus: "running",
2197
- startedAt: null,
2198
- interaction: void 0,
2199
- error: void 0,
2200
- selectedOrganizationId: void 0,
2201
- selectedProjectId: void 0,
2202
- availableAgents: [],
2203
- canCreateProject: false,
2204
- toolCalls: {},
2205
- activeThought: void 0
2206
- }), "reset")
2207
- })));
2208
-
2209
- // src/store/auth-utils.ts
2210
- function isAuthenticationError(message) {
2211
- const normalized = message.toLowerCase();
2212
- 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");
2213
- }
2214
- __name(isAuthenticationError, "isAuthenticationError");
2215
-
2216
- // src/store/use-project-data-store.ts
2217
- import { create as create3 } from "zustand";
2218
- import { subscribeWithSelector as subscribeWithSelector3 } from "zustand/middleware";
2219
- var EMPTY_WORKFLOW = {
2220
- currentPhase: null,
2221
- blockedCount: 0,
2222
- hasPlanningArtifacts: false,
2223
- hasVerificationEvidence: false
2224
- };
2225
- var useProjectDataStore = create3()(subscribeWithSelector3((set, get) => ({
2226
- specs: [],
2227
- decisions: [],
2228
- workflow: EMPTY_WORKFLOW,
2229
- navPolicy: [],
2230
- setProjectData: /* @__PURE__ */ __name((specs, decisions, workflow, navPolicy) => set({
2231
- specs,
2232
- decisions,
2233
- workflow,
2234
- navPolicy
2235
- }), "setProjectData"),
2236
- setPollingData: /* @__PURE__ */ __name((workflow, navPolicy) => set({
2237
- workflow,
2238
- navPolicy
2239
- }), "setPollingData"),
2240
- clearProjectData: /* @__PURE__ */ __name(() => set({
2241
- specs: [],
2242
- decisions: [],
2243
- workflow: EMPTY_WORKFLOW,
2244
- navPolicy: []
2245
- }), "clearProjectData"),
2246
- updateSpecificationContent: /* @__PURE__ */ __name(async (specificationId, content) => {
2247
- const client2 = getClient();
2248
- const boot = getBootContext();
2249
- if (!client2 || !boot) return;
2250
- await withSessionFeedback({
2251
- statusLine: "Saving specification...",
2252
- action: /* @__PURE__ */ __name(() => getService().updateSpecificationContent(client2, boot.projectId, specificationId, content), "action"),
2253
- successLog: "[specs] saved specification changes",
2254
- failureLog: "[error] save failed",
2255
- failureStatusLine: "Save failed"
2256
- });
2257
- }, "updateSpecificationContent"),
2258
- updateSpecificationStatus: /* @__PURE__ */ __name(async (specificationId, status, options) => {
2259
- const client2 = getClient();
2260
- const boot = getBootContext();
2261
- if (!client2 || !boot) return;
2262
- setSessionStatusLine(`Updating status to ${status}...`);
2263
- try {
2264
- await getService().updateSpecificationStatus(client2, boot.projectId, specificationId, status);
2265
- appendSessionLog(`[specs] status updated to ${status}`);
2266
- if (options?.refresh !== false) {
2267
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KGAFXCKI.mjs");
2268
- await useSessionStore2.getState().refresh();
2269
- }
2270
- } catch (error) {
2271
- const message = error instanceof Error ? error.message : String(error);
2272
- appendSessionLog(`[error] status update failed: ${message}`);
2273
- setSessionStatusLine("Status update failed");
2274
- refreshOnAuthenticationError(message);
2275
- }
2276
- }, "updateSpecificationStatus"),
2277
- deleteSpecification: /* @__PURE__ */ __name(async (specificationId, mode = "archive", options) => {
2278
- const client2 = getClient();
2279
- const boot = getBootContext();
2280
- if (!client2 || !boot) return;
2281
- setSessionStatusLine(mode === "delete" ? "Deleting specification permanently..." : "Archiving specification...");
2282
- try {
2283
- await getService().deleteSpecification(client2, boot.projectId, specificationId, mode);
2284
- appendSessionLog(mode === "delete" ? "[specs] specification deleted permanently" : "[specs] specification archived");
2285
- if (options?.refresh !== false) {
2286
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KGAFXCKI.mjs");
2287
- await useSessionStore2.getState().refresh();
2288
- }
2289
- } catch (error) {
2290
- const message = error instanceof Error ? error.message : String(error);
2291
- appendSessionLog(`[error] specification ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2292
- setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2293
- refreshOnAuthenticationError(message);
2294
- }
2295
- }, "deleteSpecification"),
2296
- refineSpecificationWithAi: /* @__PURE__ */ __name(async (specificationId, userMessage) => {
2297
- const client2 = getClient();
2298
- const boot = getBootContext();
2299
- const { specs } = get();
2300
- if (!client2 || !boot) return;
2301
- const spec = specs.find((item) => item.id === specificationId);
2302
- if (!spec) {
2303
- appendSessionLog("[error] refine failed: specification not found in current list");
2304
- setSessionStatusLine("Refinement failed");
2305
- return;
2306
- }
2307
- const specContent = (spec.content ?? "").trim();
2308
- if (!specContent) {
2309
- appendSessionLog("[error] refine failed: selected specification has no content");
2310
- setSessionStatusLine("Refinement failed");
2311
- return;
2312
- }
2313
- setSessionStatusLine("Refining specification with AI...");
2314
- const service2 = getService();
2315
- try {
2316
- const refinedContent = await service2.refineSpecificationWithAi(client2, {
2317
- projectId: boot.projectId,
2318
- specContent,
2319
- userMessage,
2320
- agentType: "codex"
2321
- });
2322
- await service2.updateSpecificationContent(client2, boot.projectId, specificationId, refinedContent);
2323
- appendSessionLog("[specs] AI refinement applied and saved");
2324
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KGAFXCKI.mjs");
2325
- await useSessionStore2.getState().refresh();
2326
- } catch (error) {
2327
- const message = error instanceof Error ? error.message : String(error);
2328
- appendSessionLog(`[error] AI refinement failed: ${message}`);
2329
- setSessionStatusLine("AI refinement failed");
2330
- refreshOnAuthenticationError(message);
2331
- }
2332
- }, "refineSpecificationWithAi"),
2333
- resolveDecision: /* @__PURE__ */ __name(async (decisionId, status, reason, existingRationale, options) => {
2334
- const client2 = getClient();
2335
- const boot = getBootContext();
2336
- if (!client2 || !boot) {
2337
- throw new Error("Decision update unavailable: project context is not initialized.");
2338
- }
2339
- setSessionStatusLine(`Resolving decision as ${status}...`);
2340
- try {
2341
- await getService().resolveDecision(client2, boot.projectId, decisionId, status, reason, existingRationale);
2342
- appendSessionLog(`[decisions] ${decisionId} -> ${status}`);
2343
- if (options?.refresh !== false) {
2344
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KGAFXCKI.mjs");
2345
- await useSessionStore2.getState().refresh();
2346
- }
2347
- } catch (error) {
2348
- const message = error instanceof Error ? error.message : String(error);
2349
- appendSessionLog(`[error] decision resolution failed: ${message}`);
2350
- setSessionStatusLine("Decision resolution failed");
2351
- refreshOnAuthenticationError(message);
2352
- throw error;
2353
- }
2354
- }, "resolveDecision"),
2355
- deleteDecision: /* @__PURE__ */ __name(async (decisionId, mode = "archive", options) => {
2356
- const client2 = getClient();
2357
- const boot = getBootContext();
2358
- if (!client2 || !boot) {
2359
- throw new Error("Decision delete unavailable: project context is not initialized.");
2360
- }
2361
- setSessionStatusLine(mode === "delete" ? "Deleting decision permanently..." : "Archiving decision...");
2362
- try {
2363
- await getService().deleteDecision(client2, boot.projectId, decisionId, mode);
2364
- appendSessionLog(mode === "delete" ? `[decisions] ${decisionId} deleted permanently` : `[decisions] ${decisionId} archived`);
2365
- if (options?.refresh !== false) {
2366
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KGAFXCKI.mjs");
2367
- await useSessionStore2.getState().refresh();
2368
- }
2369
- } catch (error) {
2370
- const message = error instanceof Error ? error.message : String(error);
2371
- appendSessionLog(`[error] decision ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2372
- setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2373
- refreshOnAuthenticationError(message);
2374
- throw error;
2375
- }
2376
- }, "deleteDecision")
2377
- })));
2378
-
2379
- // src/store/use-export-store.ts
2380
- import { create as create4 } from "zustand";
2381
- import { subscribeWithSelector as subscribeWithSelector4 } from "zustand/middleware";
2382
-
2383
- // src/utils/clipboard.ts
2384
- import { spawnSync } from "child_process";
2385
- function clipboardAttempts() {
2386
- if (process.platform === "darwin") {
2387
- return [
2388
- {
2389
- cmd: "pbcopy",
2390
- args: []
2391
- }
2392
- ];
2393
- }
2394
- if (process.platform === "win32") {
2395
- return [
2396
- {
2397
- cmd: "clip",
2398
- args: []
2399
- }
2400
- ];
2401
- }
2402
- return [
2403
- {
2404
- cmd: "wl-copy",
2405
- args: []
2406
- },
2407
- {
2408
- cmd: "xclip",
2409
- args: [
2410
- "-selection",
2411
- "clipboard"
2412
- ]
2413
- },
2414
- {
2415
- cmd: "xsel",
2416
- args: [
2417
- "--clipboard",
2418
- "--input"
2419
- ]
2420
- }
2421
- ];
2422
- }
2423
- __name(clipboardAttempts, "clipboardAttempts");
2424
- function copyTextToClipboard(text) {
2425
- const attempts = clipboardAttempts();
2426
- let lastError = "No clipboard command available.";
2427
- for (const attempt of attempts) {
2428
- const result = spawnSync(attempt.cmd, attempt.args, {
2429
- input: text,
2430
- encoding: "utf8",
2431
- stdio: [
2432
- "pipe",
2433
- "ignore",
2434
- "pipe"
2435
- ]
2436
- });
2437
- if (!result.error && result.status === 0) {
2438
- return {
2439
- ok: true
2440
- };
2441
- }
2442
- lastError = (result.error?.message ?? result.stderr?.trim()) || `${attempt.cmd} exited with status ${result.status}`;
2443
- }
2444
- return {
2445
- ok: false,
2446
- error: lastError
2447
- };
2448
- }
2449
- __name(copyTextToClipboard, "copyTextToClipboard");
2450
-
2451
- // src/store/use-export-store.ts
2452
- var EMPTY_EXPORT_JOB = {
2453
- action: null,
2454
- status: "idle"
2455
- };
2456
- async function runExport(action) {
2457
- const state = useExportStore.getState();
2458
- const boot = getBootContext();
2459
- if (!boot) return;
2460
- if (state.exportInFlight) {
2461
- appendSessionLog("[warn] Export already in progress");
2462
- return;
2463
- }
2464
- const format = state.exportFormat;
2465
- useExportStore.setState({
2466
- exportInFlight: true,
2467
- exportJob: {
2468
- action,
2469
- status: "running",
2470
- format
2471
- }
2472
- });
2473
- setSessionStatusLine(action === "preview" ? "Previewing export..." : "Generating export...");
2474
- const service2 = getService();
2475
- const client2 = getClient();
2476
- try {
2477
- if (action === "status") {
2478
- const status = await service2.exportStatus(boot.projectId, format, {
2479
- mode: state.exportMode,
2480
- scopePath: state.exportScopePath || void 0,
2481
- organizationId: boot.organizationId
2482
- });
2483
- useExportStore.setState({
2484
- exportStatus: status,
2485
- exportJob: {
2486
- action,
2487
- status: "success",
2488
- format
2489
- }
2490
- });
2491
- setSessionStatusLine(`Export status: ${status.overall}`);
2492
- appendSessionLog(`[export] Status ${format}: ${status.overall}`);
2493
- return;
2494
- }
2495
- if (action === "commit" || action === "pr") {
2496
- const delivery = action === "commit" ? "commit" : "pr";
2497
- const result = await service2.deliverExport(boot.projectId, format, delivery, {
2498
- mode: state.exportMode,
2499
- scopePath: state.exportScopePath || void 0,
2500
- organizationId: boot.organizationId
2501
- });
2502
- useExportStore.setState({
2503
- exportJob: {
2504
- action,
2505
- status: "success",
2506
- format
2507
- }
2508
- });
2509
- setSessionStatusLine(result.message);
2510
- appendSessionLog(`[export] ${result.message}`);
2511
- return;
2512
- }
2513
- const output = action === "preview" ? await service2.previewExport(client2, boot.projectId, format) : await service2.generateExport(client2, boot.projectId, format);
2514
- useExportStore.setState({
2515
- exportPreview: output,
2516
- exportJob: {
2517
- action,
2518
- status: "success",
2519
- format
2520
- }
2521
- });
2522
- setSessionStatusLine(action === "preview" ? "Export preview ready" : "Export generated");
2523
- const verb = action === "preview" ? "Previewed" : "Generated";
2524
- appendSessionLog(`[export] ${verb} ${format} (${output.anchorCount} anchors)`);
2525
- } catch (error) {
2526
- const message = error instanceof Error ? error.message : String(error);
2527
- useExportStore.setState({
2528
- exportJob: {
2529
- action,
2530
- status: "error",
2531
- format,
2532
- error: message
2533
- }
2534
- });
2535
- setSessionStatusLine(action === "preview" ? "Export preview failed" : "Export generation failed");
2536
- appendSessionLog(`[error] Export ${action} failed: ${message}`);
2537
- refreshOnAuthenticationError(message);
2538
- } finally {
2539
- useExportStore.setState({
2540
- exportInFlight: false
2541
- });
2542
- }
2543
- }
2544
- __name(runExport, "runExport");
2545
- var useExportStore = create4()(subscribeWithSelector4((set, get) => ({
2546
- exportFormat: "agents-md",
2547
- exportMode: "global",
2548
- exportScopePath: "",
2549
- exportDelivery: "download",
2550
- exportCapabilities: null,
2551
- exportPreview: null,
2552
- exportStatus: null,
2553
- exportValidation: {
2554
- open: false
2555
- },
2556
- exportJob: EMPTY_EXPORT_JOB,
2557
- exportInFlight: false,
2558
- setCapabilities: /* @__PURE__ */ __name((capabilities) => {
2559
- set((prev) => {
2560
- const discoveredFormats = capabilities?.formats?.map((f) => f.id) ?? [];
2561
- const discoveredModes = capabilities?.modes ?? [];
2562
- const resolvedFormat = discoveredFormats.length > 0 ? discoveredFormats.includes(prev.exportFormat) ? prev.exportFormat : discoveredFormats[0] : prev.exportFormat;
2563
- const resolvedMode = discoveredModes.length > 0 ? discoveredModes.includes(prev.exportMode) ? prev.exportMode : discoveredModes[0] : prev.exportMode;
2564
- return {
2565
- exportCapabilities: capabilities,
2566
- exportFormat: resolvedFormat,
2567
- exportMode: resolvedMode
2568
- };
2569
- });
2570
- }, "setCapabilities"),
2571
- setExportFormat: /* @__PURE__ */ __name((format) => {
2572
- set((prev) => {
2573
- const allowedFormats = prev.exportCapabilities?.formats.map((f) => f.id) ?? [];
2574
- if (allowedFormats.length > 0 && !allowedFormats.includes(format)) {
2575
- setSessionStatusLine(`Export format unavailable: ${format}`);
2576
- return prev;
2577
- }
2578
- if (prev.exportFormat === format) return prev;
2579
- setSessionStatusLine(`Export format set to ${format}`);
2580
- return {
2581
- exportFormat: format,
2582
- exportPreview: null,
2583
- exportStatus: null,
2584
- exportValidation: {
2585
- open: false
2586
- },
2587
- exportJob: EMPTY_EXPORT_JOB
2588
- };
2589
- });
2590
- }, "setExportFormat"),
2591
- setExportMode: /* @__PURE__ */ __name((mode) => {
2592
- set((prev) => {
2593
- const allowedModes = prev.exportCapabilities?.modes ?? [];
2594
- if (allowedModes.length > 0 && !allowedModes.includes(mode)) {
2595
- setSessionStatusLine(`Export mode unavailable: ${mode}`);
2596
- return prev;
2597
- }
2598
- setSessionStatusLine(`Export mode set to ${mode}`);
2599
- return {
2600
- exportMode: mode
2601
- };
2602
- });
2603
- }, "setExportMode"),
2604
- setExportScopePath: /* @__PURE__ */ __name((scopePath) => {
2605
- setSessionStatusLine("Updated export scope path");
2606
- set({
2607
- exportScopePath: scopePath
2608
- });
2609
- }, "setExportScopePath"),
2610
- setExportDelivery: /* @__PURE__ */ __name((delivery) => {
2611
- setSessionStatusLine(`Export delivery set to ${delivery}`);
2612
- set({
2613
- exportDelivery: delivery
2614
- });
2615
- }, "setExportDelivery"),
2616
- previewExport: /* @__PURE__ */ __name(async () => {
2617
- await runExport("preview");
2618
- }, "previewExport"),
2619
- generateExport: /* @__PURE__ */ __name(async () => {
2620
- setSessionStatusLine("Confirm export validation to write files to disk");
2621
- set({
2622
- exportValidation: {
2623
- open: true
2624
- }
2625
- });
2626
- }, "generateExport"),
2627
- validateAndWriteExport: /* @__PURE__ */ __name(async () => {
2628
- const state = get();
2629
- const boot = getBootContext();
2630
- if (!boot) return;
2631
- if (state.exportInFlight) {
2632
- appendSessionLog("[warn] Export already in progress");
2633
- return;
2634
- }
2635
- const format = state.exportFormat;
2636
- set({
2637
- exportInFlight: true,
2638
- exportValidation: {
2639
- open: false
2640
- },
2641
- exportJob: {
2642
- action: "generate",
2643
- status: "running",
2644
- format
2645
- }
2646
- });
2647
- setSessionStatusLine("Validating export and writing files...");
2648
- const service2 = getService();
2649
- try {
2650
- const result = await service2.deliverExport(boot.projectId, format, "download", {
2651
- mode: state.exportMode,
2652
- scopePath: state.exportScopePath || void 0,
2653
- organizationId: boot.organizationId
2654
- });
2655
- set((prev) => ({
2656
- exportStatus: result.localStatus ?? prev.exportStatus,
2657
- exportJob: {
2658
- action: "generate",
2659
- status: "success",
2660
- format
2661
- }
2662
- }));
2663
- setSessionStatusLine(result.message);
2664
- appendSessionLog(`[export] ${result.message}`);
2665
- } catch (error) {
2666
- const message = error instanceof Error ? error.message : String(error);
2667
- set({
2668
- exportJob: {
2669
- action: "generate",
2670
- status: "error",
2671
- format,
2672
- error: message
2673
- }
2674
- });
2675
- setSessionStatusLine("Export validation/write failed");
2676
- appendSessionLog(`[error] Export validate/write failed: ${message}`);
2677
- refreshOnAuthenticationError(message);
2678
- } finally {
2679
- set({
2680
- exportInFlight: false
2681
- });
2682
- }
2683
- }, "validateAndWriteExport"),
2684
- cancelExportValidation: /* @__PURE__ */ __name(() => {
2685
- setSessionStatusLine("Export validation cancelled");
2686
- set({
2687
- exportValidation: {
2688
- open: false
2689
- }
2690
- });
2691
- }, "cancelExportValidation"),
2692
- statusExport: /* @__PURE__ */ __name(async () => {
2693
- await runExport("status");
2694
- }, "statusExport"),
2695
- commitExport: /* @__PURE__ */ __name(async () => {
2696
- await runExport("commit");
2697
- }, "commitExport"),
2698
- createPrExport: /* @__PURE__ */ __name(async () => {
2699
- await runExport("pr");
2700
- }, "createPrExport"),
2701
- copyExportPreview: /* @__PURE__ */ __name(() => {
2702
- const { exportPreview, exportJob } = get();
2703
- const hasGeneratedPreview = exportJob.status === "success" && (exportJob.action === "preview" || exportJob.action === "generate");
2704
- if (!exportPreview?.content || !hasGeneratedPreview) {
2705
- setSessionStatusLine("No generated preview to copy. Run p or g first.");
2706
- appendSessionLog("[warn] export copy requested before preview/generate completed");
2707
- return;
2708
- }
2709
- const copied = copyTextToClipboard(exportPreview.content);
2710
- if (copied.ok) {
2711
- setSessionStatusLine("Copied preview to clipboard");
2712
- appendSessionLog("[export] copied preview to clipboard");
2713
- return;
2714
- }
2715
- setSessionStatusLine("Clipboard copy failed");
2716
- appendSessionLog(`[error] clipboard copy failed: ${copied.error}`);
2717
- }, "copyExportPreview")
2718
- })));
2719
-
2720
- // src/store/use-bridge-store.ts
2721
- import { create as create5 } from "zustand";
2722
- import { subscribeWithSelector as subscribeWithSelector5 } from "zustand/middleware";
2723
- var useBridgeStore = create5()(subscribeWithSelector5((set, get) => ({
2724
- bridge: null,
2725
- localBridge: null,
2726
- bridgeLogs: [],
2727
- bridgeLogsSince: 0,
2728
- startedByTui: false,
2729
- webmcpChannels: [],
2730
- setBridgeData: /* @__PURE__ */ __name((bridge, localBridge) => set({
2731
- bridge,
2732
- localBridge
2733
- }), "setBridgeData"),
2734
- setLocalBridge: /* @__PURE__ */ __name((localBridge) => set({
2735
- localBridge
2736
- }), "setLocalBridge"),
2737
- setBridgeLogs: /* @__PURE__ */ __name((logs) => {
2738
- if (logs.length === 0) return;
2739
- const lastTimestamp = logs[logs.length - 1].timestamp;
2740
- set((prev) => ({
2741
- bridgeLogs: [
2742
- ...prev.bridgeLogs,
2743
- ...logs
2744
- ].slice(-200),
2745
- bridgeLogsSince: lastTimestamp
2746
- }));
2747
- }, "setBridgeLogs"),
2748
- clearBridgeLogs: /* @__PURE__ */ __name(() => set({
2749
- bridgeLogs: []
2750
- }), "clearBridgeLogs"),
2751
- setWebMcpChannels: /* @__PURE__ */ __name((channels) => set({
2752
- webmcpChannels: channels
2753
- }), "setWebMcpChannels"),
2754
- bridgeStart: /* @__PURE__ */ __name(() => {
2755
- const service2 = getService();
2756
- service2.startLocalBridgeDetached();
2757
- set({
2758
- startedByTui: true
2759
- });
2760
- appendSessionLog("[bridge] Started local bridge process (detached)");
2761
- setSessionStatusLine("Bridge start triggered (detached)");
2762
- }, "bridgeStart"),
2763
- bridgeStop: /* @__PURE__ */ __name(async () => {
2764
- const service2 = getService();
2765
- const { localBridge } = get();
2766
- await service2.stopLocalBridge(localBridge?.port);
2767
- if (localBridge) {
2768
- set({
2769
- localBridge: {
2770
- ...localBridge,
2771
- running: false,
2772
- uptimeSec: 0
2773
- },
2774
- webmcpChannels: []
2775
- });
2776
- }
2777
- appendSessionLog("[bridge] Stop signal sent");
2778
- setSessionStatusLine("Bridge stop signal sent");
2779
- }, "bridgeStop")
2780
- })));
2781
-
2782
- // src/store/store-effects.ts
2783
- function dispatchRefreshComplete(data) {
2784
- useProjectDataStore.getState().setProjectData(data.specs, data.decisions, data.workflow, data.navPolicy);
2785
- useExportStore.getState().setCapabilities(data.exportCapabilities);
2786
- useBridgeStore.getState().setBridgeData(data.bridge, data.localBridge);
2787
- }
2788
- __name(dispatchRefreshComplete, "dispatchRefreshComplete");
2789
- function dispatchClearProjectData() {
2790
- useProjectDataStore.getState().clearProjectData();
2791
- }
2792
- __name(dispatchClearProjectData, "dispatchClearProjectData");
2793
- function refreshOnAuthenticationError(message) {
2794
- if (!isAuthenticationError(message)) return;
2795
- const { appendLog, refresh } = useSessionStore.getState();
2796
- useSessionStore.setState({
2797
- statusLine: "Authentication required. Refreshing context..."
2798
- });
2799
- appendLog("[auth] action requires authentication, refreshing context");
2800
- void refresh();
2801
- }
2802
- __name(refreshOnAuthenticationError, "refreshOnAuthenticationError");
2803
- async function withSessionFeedback(opts) {
2804
- const { appendLog, refresh } = useSessionStore.getState();
2805
- useSessionStore.setState({
2806
- statusLine: opts.statusLine
2807
- });
2808
- try {
2809
- const result = await opts.action();
2810
- appendLog(opts.successLog);
2811
- if (opts.refresh !== false) {
2812
- await refresh();
2813
- }
2814
- return result;
2815
- } catch (error) {
2816
- const message = error instanceof Error ? error.message : String(error);
2817
- appendLog(`${opts.failureLog}: ${message}`);
2818
- useSessionStore.setState({
2819
- statusLine: opts.failureStatusLine
2820
- });
2821
- refreshOnAuthenticationError(message);
2822
- throw error;
2823
- }
2824
- }
2825
- __name(withSessionFeedback, "withSessionFeedback");
2826
- function getBootContext() {
2827
- return useSessionStore.getState().boot;
2828
- }
2829
- __name(getBootContext, "getBootContext");
2830
- function setSessionStatusLine(line) {
2831
- useSessionStore.setState({
2832
- statusLine: line
2833
- });
2834
- }
2835
- __name(setSessionStatusLine, "setSessionStatusLine");
2836
- function appendSessionLog(entry) {
2837
- useSessionStore.getState().appendLog(entry);
2838
- }
2839
- __name(appendSessionLog, "appendSessionLog");
2840
-
2841
- // src/store/use-session-store.ts
2842
- var onboardingInteractionResolver = null;
2843
- function requestOnboardingInteraction(request) {
2844
- return new Promise((resolve) => {
2845
- onboardingInteractionResolver = resolve;
2846
- useSessionStore.setState((prev) => ({
2847
- onboarding: prev.onboarding ? {
2848
- ...prev.onboarding,
2849
- interaction: request
2850
- } : prev.onboarding
2851
- }));
2852
- });
2853
- }
2854
- __name(requestOnboardingInteraction, "requestOnboardingInteraction");
2855
- function refreshOnAuthenticationError2(message) {
2856
- if (!isAuthenticationError(message)) return;
2857
- const { appendLog, refresh } = useSessionStore.getState();
2858
- useSessionStore.setState({
2859
- statusLine: "Authentication required. Refreshing context..."
2860
- });
2861
- appendLog("[auth] action requires authentication, refreshing context");
2862
- void refresh();
2863
- }
2864
- __name(refreshOnAuthenticationError2, "refreshOnAuthenticationError");
2865
- async function buildOnboardingState(mode) {
2866
- const service2 = getService();
2867
- const boot = useSessionStore.getState().boot;
2868
- const organizations = await service2.listOrganizations();
2869
- if (organizations.length === 0) {
2870
- return {
2871
- mode,
2872
- step: "create-organization",
2873
- attachCurrentFolder: mode === "initial-setup",
2874
- organizations: [],
2875
- projects: [],
2876
- availableAgents: [],
2877
- canCreateProject: false,
2878
- error: void 0
2879
- };
2880
- }
2881
- const preferredOrganizationId = boot?.organizationId;
2882
- const selectedOrganization = organizations.find((org) => org.id === preferredOrganizationId) ?? organizations[0];
2883
- const projects = await service2.listProjects(selectedOrganization.id);
2884
- return {
2885
- mode,
2886
- step: organizations.length === 1 ? "project" : "organization",
2887
- attachCurrentFolder: mode === "initial-setup",
2888
- organizations,
2889
- projects,
2890
- availableAgents: [],
2891
- canCreateProject: service2.canCreateProject(selectedOrganization),
2892
- selectedOrganizationId: selectedOrganization.id,
2893
- interaction: void 0,
2894
- error: void 0
2895
- };
2896
- }
2897
- __name(buildOnboardingState, "buildOnboardingState");
2898
- var useSessionStore = create6()(subscribeWithSelector6((set, get) => ({
2899
- boot: null,
2900
- auth: null,
2901
- onboarding: null,
2902
- loading: true,
2903
- error: null,
2904
- statusLine: "Bootstrapping...",
2905
- logs: [],
2906
- appendLog: /* @__PURE__ */ __name((entry) => {
2907
- const screen = useTuiUiStore.getState().screen;
2908
- const level = entry.startsWith("[error]") ? "error" : entry.startsWith("[warn]") ? "warn" : "info";
2909
- appendGlobalStructuredLog({
2910
- source: "tui.event-log",
2911
- level,
2912
- message: entry,
2913
- details: {
2914
- screen
2915
- }
2916
- });
2917
- set((prev) => ({
2918
- logs: [
2919
- entry,
2920
- ...prev.logs
2921
- ].slice(0, 40)
2922
- }));
2923
- }, "appendLog"),
2924
- setStatusLine: /* @__PURE__ */ __name((line) => set({
2925
- statusLine: line
2926
- }), "setStatusLine"),
2927
- setLoading: /* @__PURE__ */ __name((loading) => set({
2928
- loading
2929
- }), "setLoading"),
2930
- setError: /* @__PURE__ */ __name((error) => set({
2931
- error
2932
- }), "setError"),
2933
- authenticate: /* @__PURE__ */ __name(async () => {
2934
- const { appendLog } = get();
2935
- const service2 = getService();
2936
- set({
2937
- loading: false,
2938
- auth: {
2939
- status: "authenticating"
2940
- },
2941
- statusLine: "Starting browser login flow..."
2942
- });
2943
- appendLog("[auth] starting login flow");
2944
- const ok = await service2.authenticateViaCli((line) => {
2945
- appendLog(`[auth] ${line}`);
2946
- });
2947
- if (!ok) {
2948
- set({
2949
- auth: {
2950
- status: "auth_failed",
2951
- error: "Authentication failed. Check logs and try again."
2952
- },
2953
- statusLine: "Authentication failed"
2954
- });
2955
- appendLog("[auth] login flow failed");
2956
- return;
2957
- }
2958
- appendLog("[auth] login flow completed");
2959
- await get().refresh();
2960
- }, "authenticate"),
2961
- refresh: /* @__PURE__ */ __name(async (projectId) => {
2962
- const service2 = getService();
2963
- set((prev) => ({
2964
- loading: prev.boot ? false : true,
2965
- statusLine: "Loading context..."
2966
- }));
2967
- try {
2968
- const token = await service2.checkAuthentication();
2969
- if (!token) {
2970
- set({
2971
- loading: false,
2972
- error: null,
2973
- auth: {
2974
- status: "unauthenticated",
2975
- error: "No valid credentials. Please run `spekn auth login` to authenticate."
2976
- },
2977
- statusLine: "Authentication required"
2978
- });
2979
- return;
2980
- }
2981
- set({
2982
- auth: {
2983
- status: "authenticated",
2984
- userEmail: service2.extractUserEmail(token),
2985
- tokenExpiresAt: service2.extractTokenExpiry(token)
2986
- }
2987
- });
2988
- if (!projectId && !service2.hasLocalProjectContext()) {
2989
- const onboarding = await buildOnboardingState("initial-setup");
2990
- set({
2991
- loading: false,
2992
- error: null,
2993
- onboarding,
2994
- statusLine: "Project setup required"
2995
- });
2996
- return;
2997
- }
2998
- let bootstrapResult;
2999
- try {
3000
- bootstrapResult = await service2.bootstrap(projectId);
3001
- } catch (bootstrapError) {
3002
- if (bootstrapError instanceof Error && bootstrapError.message === "ONBOARDING_REQUIRED") {
3003
- const onboarding = await buildOnboardingState("initial-setup");
3004
- set({
3005
- loading: false,
3006
- error: null,
3007
- onboarding,
3008
- statusLine: "Project setup required"
3009
- });
3010
- return;
3011
- }
3012
- throw bootstrapError;
3013
- }
3014
- const { boot, client: client2 } = bootstrapResult;
3015
- setClient(client2);
3016
- const [specs, decisions, workflow, bridge, localBridge, exportCapabilities] = await Promise.all([
3017
- service2.loadSpecs(client2, boot.projectId),
3018
- service2.loadDecisions(client2, boot.projectId),
3019
- service2.loadWorkflowSummary(client2, boot.projectId),
3020
- service2.loadBridgeSummary(client2),
3021
- service2.loadLocalBridgeSummary(),
3022
- service2.discoverExportCapabilities(boot.projectId, boot.organizationId).catch(() => null)
3023
- ]);
3024
- const capabilityContext = {
3025
- plan: boot.plan,
3026
- role: boot.role,
3027
- workflowPhase: workflow.currentPhase,
3028
- permissions: boot.permissions
3029
- };
3030
- const navPolicy = resolveNavPolicy(capabilityContext);
3031
- dispatchRefreshComplete({
3032
- specs,
3033
- decisions,
3034
- workflow,
3035
- navPolicy,
3036
- exportCapabilities,
3037
- bridge,
3038
- localBridge
3039
- });
3040
- set({
3041
- boot,
3042
- loading: false,
3043
- error: null,
3044
- onboarding: null,
3045
- statusLine: "Ready"
3046
- });
3047
- } catch (error) {
3048
- const message = error instanceof Error ? error.message : String(error);
3049
- let authStatus = null;
3050
- if (message.includes("credentials") || message.includes("auth") || message.includes("token")) {
3051
- authStatus = {
3052
- status: "auth_failed",
3053
- error: message
3054
- };
3055
- }
3056
- set((prev) => ({
3057
- loading: false,
3058
- error: message,
3059
- auth: authStatus || prev.auth,
3060
- statusLine: "Error"
3061
- }));
3062
- get().appendLog(`[error] ${message}`);
3063
- }
3064
- }, "refresh"),
3065
- switchContext: /* @__PURE__ */ __name(async () => {
3066
- const { appendLog } = get();
3067
- set({
3068
- loading: true,
3069
- error: null,
3070
- statusLine: "Loading organizations..."
3071
- });
3072
- try {
3073
- const onboarding = await buildOnboardingState("switch-context");
3074
- set({
3075
- loading: false,
3076
- onboarding,
3077
- statusLine: "Switch organization/project"
3078
- });
3079
- appendLog("[context] switch mode opened");
3080
- } catch (error) {
3081
- const message = error instanceof Error ? error.message : String(error);
3082
- set({
3083
- loading: false,
3084
- statusLine: "Context switch failed",
3085
- error: message
3086
- });
3087
- appendLog(`[error] context switch failed: ${message}`);
3088
- refreshOnAuthenticationError2(message);
3089
- }
3090
- }, "switchContext"),
3091
- detachRepoContext: /* @__PURE__ */ __name(async () => {
3092
- const { boot, appendLog, refresh } = get();
3093
- const service2 = getService();
3094
- const result = await service2.detachContextViaCli(boot?.projectId, process.cwd());
3095
- if (!result.success) {
3096
- appendLog(`[error] Failed to detach context: ${result.output}`);
3097
- set({
3098
- statusLine: "Context detach failed"
3099
- });
3100
- return;
3101
- }
3102
- if (result.output) {
3103
- appendLog(`[context] ${result.output}`);
3104
- }
3105
- appendLog("[context] Detached repository from local project context");
3106
- set({
3107
- boot: null,
3108
- statusLine: "Repository detached. Select a project to attach."
3109
- });
3110
- dispatchClearProjectData();
3111
- await refresh();
3112
- }, "detachRepoContext"),
3113
- syncRepository: /* @__PURE__ */ __name(async (options) => {
3114
- const { boot, appendLog, refresh } = get();
3115
- const service2 = getService();
3116
- if (!boot) {
3117
- appendLog("[error] repository sync unavailable: no active project context");
3118
- set({
3119
- statusLine: "Repository sync unavailable"
3120
- });
3121
- return false;
3122
- }
3123
- appendLog("[repo] running sync (metadata + drift analysis)");
3124
- set({
3125
- statusLine: "Syncing repository..."
3126
- });
3127
- const result = await service2.syncRepositoryViaCli(boot.organizationId, boot.projectId, boot.repoPath, {
3128
- analyze: options?.analyze ?? true,
3129
- importToProject: options?.importToProject,
3130
- maxFiles: options?.maxFiles,
3131
- analysisEngine: options?.analysisEngine,
3132
- agent: options?.agent,
3133
- requestInteraction: options?.requestInteraction,
3134
- onProgress: /* @__PURE__ */ __name((line) => {
3135
- appendLog(`[repo] ${line}`);
3136
- options?.onProgress?.(line);
3137
- }, "onProgress"),
3138
- onActivity: /* @__PURE__ */ __name((event) => {
3139
- options?.onActivity?.(event);
3140
- }, "onActivity")
3141
- });
3142
- if (!result.success) {
3143
- appendLog(`[error] repository sync failed (exit ${result.exitCode})`);
3144
- set({
3145
- statusLine: "Repository sync failed"
3146
- });
3147
- refreshOnAuthenticationError2(result.output);
3148
- return false;
3149
- }
3150
- appendLog("[repo] sync completed");
3151
- set({
3152
- statusLine: "Repository sync completed"
3153
- });
3154
- await refresh();
3155
- return true;
3156
- }, "syncRepository"),
3157
- // Onboarding actions
3158
- selectOnboardingOrganization: /* @__PURE__ */ __name(async (index) => {
3159
- const { onboarding, appendLog } = get();
3160
- const service2 = getService();
3161
- if (!onboarding) return;
3162
- if (index < 0 || index >= onboarding.organizations.length) {
3163
- set((prev) => ({
3164
- onboarding: prev.onboarding ? {
3165
- ...prev.onboarding,
3166
- error: `Invalid organization index: ${index + 1}`
3167
- } : prev.onboarding
3168
- }));
3169
- return;
3170
- }
3171
- const selectedOrganization = onboarding.organizations[index];
3172
- set((prev) => ({
3173
- loading: true,
3174
- statusLine: "Loading projects...",
3175
- onboarding: prev.onboarding ? {
3176
- ...prev.onboarding,
3177
- selectedOrganizationId: selectedOrganization.id,
3178
- error: void 0
3179
- } : prev.onboarding
3180
- }));
3181
- try {
3182
- const projects = await service2.listProjects(selectedOrganization.id);
3183
- set((prev) => ({
3184
- loading: false,
3185
- statusLine: "Select a project",
3186
- onboarding: prev.onboarding ? {
3187
- ...prev.onboarding,
3188
- step: "project",
3189
- attachCurrentFolder: prev.onboarding.attachCurrentFolder,
3190
- projects,
3191
- availableAgents: prev.onboarding?.availableAgents ?? [],
3192
- canCreateProject: service2.canCreateProject(selectedOrganization),
3193
- selectedOrganizationId: selectedOrganization.id,
3194
- interaction: void 0,
3195
- error: projects.length === 0 ? "No projects found in selected organization." : void 0
3196
- } : prev.onboarding
3197
- }));
3198
- } catch (error) {
3199
- const message = error instanceof Error ? error.message : String(error);
3200
- set((prev) => ({
3201
- loading: false,
3202
- statusLine: "Setup error",
3203
- onboarding: prev.onboarding ? {
3204
- ...prev.onboarding,
3205
- error: message
3206
- } : prev.onboarding
3207
- }));
3208
- }
3209
- }, "selectOnboardingOrganization"),
3210
- registerOnboardingProject: /* @__PURE__ */ __name(async (index) => {
3211
- const { onboarding, appendLog, refresh } = get();
3212
- const service2 = getService();
3213
- if (!onboarding || !onboarding.selectedOrganizationId) return;
3214
- if (index < 0 || index >= onboarding.projects.length) {
3215
- set((prev) => ({
3216
- onboarding: prev.onboarding ? {
3217
- ...prev.onboarding,
3218
- error: `Invalid project index: ${index + 1}`
3219
- } : prev.onboarding
3220
- }));
3221
- return;
3222
- }
3223
- const selectedProject = onboarding.projects[index];
3224
- if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
3225
- set((prev) => ({
3226
- loading: true,
3227
- statusLine: "Switching context...",
3228
- onboarding: prev.onboarding ? {
3229
- ...prev.onboarding,
3230
- error: void 0
3231
- } : prev.onboarding
3232
- }));
3233
- try {
3234
- service2.persistContext(onboarding.selectedOrganizationId, selectedProject.id);
3235
- appendLog(`[context] switched to ${selectedProject.name}`);
3236
- await refresh();
3237
- } catch (error) {
3238
- const message = error instanceof Error ? error.message : String(error);
3239
- set((prev) => ({
3240
- loading: false,
3241
- statusLine: "Context switch failed",
3242
- onboarding: prev.onboarding ? {
3243
- ...prev.onboarding,
3244
- step: "project",
3245
- error: message
3246
- } : prev.onboarding
3247
- }));
3248
- }
3249
- return;
3250
- }
3251
- set((prev) => ({
3252
- loading: true,
3253
- statusLine: "Linking repository...",
3254
- onboarding: prev.onboarding ? {
3255
- ...prev.onboarding,
3256
- error: void 0
3257
- } : prev.onboarding
3258
- }));
3259
- try {
3260
- persistProjectContext(process.cwd(), {
3261
- projectId: selectedProject.id,
3262
- organizationId: onboarding.selectedOrganizationId
3263
- });
3264
- appendLog(`[context] linked to ${selectedProject.name}`);
3265
- await refresh();
3266
- } catch (error) {
3267
- const message = error instanceof Error ? error.message : String(error);
3268
- set((prev) => ({
3269
- loading: false,
3270
- statusLine: "Setup error",
3271
- onboarding: prev.onboarding ? {
3272
- ...prev.onboarding,
3273
- step: "project",
3274
- error: message
3275
- } : prev.onboarding
3276
- }));
3277
- }
3278
- }, "registerOnboardingProject"),
3279
- createOnboardingProject: /* @__PURE__ */ __name(async (name) => {
3280
- const { onboarding, appendLog, refresh } = get();
3281
- const service2 = getService();
3282
- if (!onboarding || !onboarding.selectedOrganizationId) return;
3283
- const trimmed = name.trim();
3284
- if (!onboarding.canCreateProject) {
3285
- set((prev) => ({
3286
- onboarding: prev.onboarding ? {
3287
- ...prev.onboarding,
3288
- error: "You are not authorized to create projects in this organization."
3289
- } : prev.onboarding
3290
- }));
3291
- return;
3292
- }
3293
- if (trimmed.length < 2) {
3294
- set((prev) => ({
3295
- onboarding: prev.onboarding ? {
3296
- ...prev.onboarding,
3297
- error: "Project name must be at least 2 characters."
3298
- } : prev.onboarding
3299
- }));
3300
- return;
3301
- }
3302
- set((prev) => ({
3303
- loading: true,
3304
- statusLine: "Creating project...",
3305
- onboarding: prev.onboarding ? {
3306
- ...prev.onboarding,
3307
- error: void 0
3308
- } : prev.onboarding
3309
- }));
3310
- try {
3311
- const created = await service2.createProject(onboarding.selectedOrganizationId, trimmed);
3312
- appendLog(`[setup] Created project "${created.name}"`);
3313
- if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
3314
- service2.persistContext(onboarding.selectedOrganizationId, created.id);
3315
- appendLog(`[context] switched to ${created.name}`);
3316
- await refresh();
3317
- return;
3318
- }
3319
- const registerStartedAt = Date.now();
3320
- set((prev) => ({
3321
- loading: true,
3322
- statusLine: "Registering repository...",
3323
- onboarding: prev.onboarding ? {
3324
- ...prev.onboarding,
3325
- step: "registering",
3326
- availableAgents: prev.onboarding?.availableAgents ?? [],
3327
- selectedProjectId: created.id,
3328
- runLines: [],
3329
- runStatus: "running",
3330
- startedAt: registerStartedAt,
3331
- interaction: void 0,
3332
- error: void 0
3333
- } : prev.onboarding
3334
- }));
3335
- useOnboardingWindow.getState().setStartedAt(registerStartedAt);
3336
- await attachRepositoryFromOnboardingZustand({
3337
- organizationId: onboarding.selectedOrganizationId,
3338
- projectId: created.id
3339
- });
3340
- await refresh();
3341
- } catch (error) {
3342
- const message = error instanceof Error ? error.message : String(error);
3343
- set((prev) => ({
3344
- loading: false,
3345
- statusLine: "Setup error",
3346
- onboarding: prev.onboarding ? {
3347
- ...prev.onboarding,
3348
- error: message
3349
- } : prev.onboarding
3350
- }));
3351
- }
3352
- }, "createOnboardingProject"),
3353
- resolveOnboardingInteraction: /* @__PURE__ */ __name((value) => {
3354
- const resolver = onboardingInteractionResolver;
3355
- onboardingInteractionResolver = null;
3356
- set((prev) => ({
3357
- onboarding: prev.onboarding ? {
3358
- ...prev.onboarding,
3359
- interaction: void 0
3360
- } : prev.onboarding
3361
- }));
3362
- if (resolver) resolver(value);
3363
- }, "resolveOnboardingInteraction"),
3364
- setOnboardingAttachCurrentFolder: /* @__PURE__ */ __name((attach) => {
3365
- set((prev) => ({
3366
- onboarding: prev.onboarding ? prev.onboarding.attachCurrentFolder === attach ? prev.onboarding : {
3367
- ...prev.onboarding,
3368
- attachCurrentFolder: attach
3369
- } : prev.onboarding
3370
- }));
3371
- }, "setOnboardingAttachCurrentFolder")
3372
- })));
3373
- async function attachRepositoryFromOnboardingZustand(input) {
3374
- const service2 = getService();
3375
- const { appendLog } = useSessionStore.getState();
3376
- const result = await service2.attachOrSyncCurrentRepository(input.organizationId, input.projectId, (line) => {
3377
- appendLog(`[setup] ${line}`);
3378
- useSessionStore.setState((prev) => ({
3379
- statusLine: line.slice(0, 100),
3380
- onboarding: prev.onboarding ? {
3381
- ...prev.onboarding,
3382
- runLines: [
3383
- ...prev.onboarding.runLines ?? [],
3384
- line
3385
- ].slice(-400)
3386
- } : prev.onboarding
3387
- }));
3388
- }, void 0, requestOnboardingInteraction, (event) => {
3389
- const { upsertToolCall, setActiveThought } = useOnboardingWindow.getState();
3390
- if (event.event === "tool_call" || event.event === "tool_call_update") {
3391
- upsertToolCall(event);
3392
- } else if (event.event === "agent_thought") {
3393
- setActiveThought(event.text);
3394
- } else if (event.event === "agent_chunk" && event.text) {
3395
- useSessionStore.setState((prev) => {
3396
- if (!prev.onboarding) return prev;
3397
- const lines = [
3398
- ...prev.onboarding.runLines ?? []
3399
- ];
3400
- const parts = event.text.split("\n");
3401
- if (lines.length === 0) {
3402
- lines.push(parts[0]);
3403
- } else {
3404
- lines[lines.length - 1] += parts[0];
3405
- }
3406
- for (let i = 1; i < parts.length; i++) {
3407
- lines.push(parts[i]);
3408
- }
3409
- return {
3410
- onboarding: {
3411
- ...prev.onboarding,
3412
- runLines: lines.slice(-400)
3413
- }
3414
- };
3415
- });
3416
- }
3417
- });
3418
- useSessionStore.setState((prev) => ({
3419
- onboarding: prev.onboarding ? {
3420
- ...prev.onboarding,
3421
- runStatus: result.warning ? "error" : "success"
3422
- } : prev.onboarding
3423
- }));
3424
- logOnboardingAttachResult(appendLog, result);
3425
- }
3426
- __name(attachRepositoryFromOnboardingZustand, "attachRepositoryFromOnboardingZustand");
3427
-
3428
- export {
3429
- __name,
3430
- appendGlobalStructuredLog,
3431
- loadWebMcpChannels,
3432
- initServiceBridge,
3433
- getService,
3434
- getClient,
3435
- setInitialScreen,
3436
- useTuiUiStore,
3437
- resolveNavPolicy,
3438
- useOnboardingWindow,
3439
- buildOnboardingState,
3440
- useSessionStore,
3441
- useProjectDataStore,
3442
- useExportStore,
3443
- useBridgeStore
3444
- };