@spekn/cli 1.0.3 → 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 (37) hide show
  1. package/dist/main.js +72 -49
  2. package/dist/resources/prompts/repo-sync-analysis.prompt.md +1 -1
  3. package/dist/tui/index.mjs +4745 -537
  4. package/package.json +3 -3
  5. package/dist/tui/chunk-4WEASLXY.mjs +0 -3444
  6. package/dist/tui/chunk-755CADEG.mjs +0 -3401
  7. package/dist/tui/chunk-BUJQVTY5.mjs +0 -3409
  8. package/dist/tui/chunk-BZKKMGFB.mjs +0 -1959
  9. package/dist/tui/chunk-DJYOBCNM.mjs +0 -3159
  10. package/dist/tui/chunk-GTFTFDY4.mjs +0 -3417
  11. package/dist/tui/chunk-IMEBD2KA.mjs +0 -3444
  12. package/dist/tui/chunk-IX6DR5SW.mjs +0 -3433
  13. package/dist/tui/chunk-JKFOY4IF.mjs +0 -2003
  14. package/dist/tui/chunk-OXXZ3O5L.mjs +0 -3378
  15. package/dist/tui/chunk-SHJNIAAJ.mjs +0 -1697
  16. package/dist/tui/chunk-V4SNDRUS.mjs +0 -1666
  17. package/dist/tui/chunk-VXVHNZST.mjs +0 -1666
  18. package/dist/tui/chunk-WCTSFKTA.mjs +0 -3459
  19. package/dist/tui/chunk-X2XP5ACW.mjs +0 -3443
  20. package/dist/tui/chunk-YUYJ7VBG.mjs +0 -2029
  21. package/dist/tui/chunk-ZM3EI5IA.mjs +0 -3384
  22. package/dist/tui/chunk-ZYOX64HP.mjs +0 -1653
  23. package/dist/tui/use-session-store-63YUGUFA.mjs +0 -8
  24. package/dist/tui/use-session-store-ACO2SMJC.mjs +0 -8
  25. package/dist/tui/use-session-store-BVFDAWOB.mjs +0 -8
  26. package/dist/tui/use-session-store-DJIZ3FQZ.mjs +0 -9
  27. package/dist/tui/use-session-store-EAIQA4UG.mjs +0 -9
  28. package/dist/tui/use-session-store-EFBAXC3G.mjs +0 -8
  29. package/dist/tui/use-session-store-FJOR4KTG.mjs +0 -8
  30. package/dist/tui/use-session-store-IJE5KVOC.mjs +0 -8
  31. package/dist/tui/use-session-store-KGAFXCKI.mjs +0 -8
  32. package/dist/tui/use-session-store-KS4DPNDY.mjs +0 -8
  33. package/dist/tui/use-session-store-MMHJENNL.mjs +0 -8
  34. package/dist/tui/use-session-store-OZ6HC4I2.mjs +0 -9
  35. package/dist/tui/use-session-store-PTMWISNJ.mjs +0 -8
  36. package/dist/tui/use-session-store-VCDECQMW.mjs +0 -8
  37. package/dist/tui/use-session-store-VOK5ML5J.mjs +0 -9
@@ -1,3401 +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
- var BridgeService = class {
938
- static {
939
- __name(this, "BridgeService");
940
- }
941
- cliRunner;
942
- constructor(apiUrl) {
943
- this.cliRunner = new CliRunner(apiUrl);
944
- }
945
- async loadBridgeSummary(client2) {
946
- const [flag, devices, metrics] = await Promise.all([
947
- client2.bridge.getFeatureFlag.query().catch(() => ({
948
- enabled: false
949
- })),
950
- client2.bridge.listDevices.query().catch(() => []),
951
- client2.bridge.getMetrics.query().catch(() => ({
952
- connectedDevices: 0,
953
- authFailures: 0
954
- }))
955
- ]);
956
- return {
957
- featureEnabled: Boolean(flag.enabled),
958
- devices: Array.isArray(devices) ? devices.map((device) => ({
959
- id: device.id,
960
- name: device.name,
961
- status: device.status,
962
- isDefault: Boolean(device.isDefault),
963
- lastSeenAt: device.lastSeenAt
964
- })) : [],
965
- connectedDevices: Number(metrics.connectedDevices ?? 0),
966
- authFailures: Number(metrics.authFailures ?? 0)
967
- };
968
- }
969
- async loadLocalBridgeSummary() {
970
- const config = loadLocalBridgeConfig();
971
- let running = false;
972
- let uptimeSec;
973
- try {
974
- const response = await fetch(`http://127.0.0.1:${config.port}/health`);
975
- if (response.ok) {
976
- const payload = await response.json();
977
- running = true;
978
- uptimeSec = Number(payload.uptime ?? 0);
979
- }
980
- } catch {
981
- running = false;
982
- }
983
- return {
984
- paired: config.pairing !== null,
985
- deviceId: config.pairing?.deviceId,
986
- deviceName: config.pairing?.deviceName,
987
- port: config.port,
988
- running,
989
- uptimeSec
990
- };
991
- }
992
- startLocalBridgeDetached() {
993
- const cliEntry = this.cliRunner.resolveCliEntry();
994
- if (!cliEntry) return;
995
- const args = [
996
- cliEntry,
997
- "bridge",
998
- "start"
999
- ];
1000
- const child = spawn2(process.execPath, args, {
1001
- detached: true,
1002
- stdio: "ignore"
1003
- });
1004
- child.unref();
1005
- }
1006
- async stopLocalBridge(configPort) {
1007
- const port = configPort ?? loadLocalBridgeConfig().port;
1008
- try {
1009
- await fetch(`http://127.0.0.1:${port}/shutdown`, {
1010
- method: "POST"
1011
- });
1012
- } catch {
1013
- }
1014
- }
1015
- async loadBridgeLogs(port, since) {
1016
- const p = port ?? loadLocalBridgeConfig().port;
1017
- try {
1018
- const url = since ? `http://127.0.0.1:${p}/logs?since=${since}` : `http://127.0.0.1:${p}/logs`;
1019
- const res = await fetch(url);
1020
- if (!res.ok) return [];
1021
- const data = await res.json();
1022
- return data.logs;
1023
- } catch {
1024
- return [];
1025
- }
1026
- }
1027
- };
1028
-
1029
- // src/services/decision-service.ts
1030
- var DecisionService = class {
1031
- static {
1032
- __name(this, "DecisionService");
1033
- }
1034
- async loadDecisions(client2, projectId) {
1035
- const result = await client2.decision.getAll.query({
1036
- projectId,
1037
- limit: 50,
1038
- offset: 0
1039
- });
1040
- const decisions = Array.isArray(result?.decisions) ? result.decisions : [];
1041
- return decisions.map((decision) => ({
1042
- id: decision.id,
1043
- title: decision.title,
1044
- status: decision.status,
1045
- decisionType: decision.decisionType,
1046
- specAnchor: decision.specAnchor,
1047
- createdAt: decision.createdAt
1048
- }));
1049
- }
1050
- async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1051
- await client2.decision.update.mutate({
1052
- projectId,
1053
- id: decisionId,
1054
- data: {
1055
- status,
1056
- rationale: reason || existingRationale
1057
- }
1058
- });
1059
- }
1060
- async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1061
- const deleteMutation = client2?.decision?.delete?.mutate;
1062
- if (typeof deleteMutation !== "function") {
1063
- throw new Error("Decision delete route is unavailable.");
1064
- }
1065
- await deleteMutation({
1066
- projectId,
1067
- id: decisionId,
1068
- mode
1069
- });
1070
- }
1071
- };
1072
-
1073
- // src/services/export-service.ts
1074
- var ExportService = class {
1075
- static {
1076
- __name(this, "ExportService");
1077
- }
1078
- apiUrl;
1079
- cliRunner;
1080
- constructor(apiUrl) {
1081
- this.apiUrl = apiUrl;
1082
- this.cliRunner = new CliRunner(apiUrl);
1083
- }
1084
- async previewExport(client2, projectId, format) {
1085
- const result = await client2.export.preview.query({
1086
- projectId,
1087
- formatId: format
1088
- });
1089
- return {
1090
- content: String(result.content ?? ""),
1091
- anchorCount: Number(result.anchorCount ?? 0),
1092
- specVersion: typeof result.specVersion === "string" ? result.specVersion : void 0,
1093
- warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
1094
- };
1095
- }
1096
- async generateExport(client2, projectId, format) {
1097
- const result = await client2.export.generate.mutate({
1098
- projectId,
1099
- formatId: format
1100
- });
1101
- return {
1102
- content: String(result.content ?? ""),
1103
- anchorCount: Number(result.anchorCount ?? 0),
1104
- specVersion: typeof result.specVersion === "string" ? result.specVersion : void 0,
1105
- warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
1106
- };
1107
- }
1108
- async discoverExportCapabilities(projectId, organizationId) {
1109
- const fallback = {
1110
- plan: "free",
1111
- modes: [
1112
- "global"
1113
- ],
1114
- formats: [
1115
- {
1116
- id: "agents-md"
1117
- },
1118
- {
1119
- id: "claude-md"
1120
- },
1121
- {
1122
- id: "cursorrules"
1123
- },
1124
- {
1125
- id: "gemini-md"
1126
- }
1127
- ]
1128
- };
1129
- const cliResult = await this.cliRunner.runCliJson([
1130
- "export",
1131
- "discover",
1132
- "--project",
1133
- projectId,
1134
- "--api-url",
1135
- this.apiUrl,
1136
- "--json"
1137
- ], void 0, organizationId);
1138
- if (!cliResult.ok) {
1139
- return fallback;
1140
- }
1141
- const result = cliResult.value;
1142
- const modes = Array.isArray(result?.modes) ? result.modes.filter((mode) => mode === "global" || mode === "scoped") : fallback.modes;
1143
- const formats = Array.isArray(result?.formats) ? result.formats.map((format) => {
1144
- if (format?.id !== "agents-md" && format?.id !== "claude-md" && format?.id !== "cursorrules" && format?.id !== "gemini-md") {
1145
- return null;
1146
- }
1147
- const formatModes = Array.isArray(format?.modes) ? format.modes.filter((mode) => mode === "global" || mode === "scoped") : void 0;
1148
- return {
1149
- id: format.id,
1150
- name: typeof format?.name === "string" ? format.name : void 0,
1151
- filename: typeof format?.filename === "string" ? format.filename : void 0,
1152
- modes: formatModes
1153
- };
1154
- }).filter((format) => format !== null) : fallback.formats;
1155
- return {
1156
- plan: result?.plan === "pro" || result?.plan === "team" || result?.plan === "enterprise" ? result.plan : "free",
1157
- modes: modes.length > 0 ? modes : fallback.modes,
1158
- formats: formats.length > 0 ? formats : fallback.formats
1159
- };
1160
- }
1161
- async exportStatus(projectId, format, options) {
1162
- const args = [
1163
- "export",
1164
- "status",
1165
- "--project",
1166
- projectId,
1167
- "--format",
1168
- format,
1169
- "--api-url",
1170
- this.apiUrl,
1171
- "--json"
1172
- ];
1173
- if (options?.mode) args.push("--mode", options.mode);
1174
- if (options?.scopePath) args.push("--scope", options.scopePath);
1175
- const cliResult = await this.cliRunner.runCliJson(args, void 0, options?.organizationId);
1176
- if (!cliResult.ok) {
1177
- return {
1178
- overall: "missing",
1179
- targets: []
1180
- };
1181
- }
1182
- const result = cliResult.value;
1183
- const overall = result?.overall === "diverged" || result?.overall === "outdated" || result?.overall === "up-to-date" ? result.overall : "missing";
1184
- const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1185
- const status = target?.status === "diverged" || target?.status === "outdated" || target?.status === "up-to-date" ? target.status : "missing";
1186
- const kind = target?.kind === "canonical" ? "canonical" : "entrypoint";
1187
- if (typeof target?.path !== "string") return null;
1188
- return {
1189
- path: target.path,
1190
- kind,
1191
- status
1192
- };
1193
- }).filter((target) => target !== null) : [];
1194
- return {
1195
- overall,
1196
- targets
1197
- };
1198
- }
1199
- async deliverExport(projectId, format, delivery, options) {
1200
- const args = [
1201
- "export",
1202
- "--project",
1203
- projectId,
1204
- "--format",
1205
- format,
1206
- "--delivery",
1207
- delivery,
1208
- "--api-url",
1209
- this.apiUrl,
1210
- "--json"
1211
- ];
1212
- if (options?.mode) args.push("--mode", options.mode);
1213
- if (options?.scopePath) args.push("--scope", options.scopePath);
1214
- const exportCwd = delivery === "download" ? resolveContextWorkspaceRoot({
1215
- projectId,
1216
- fallbackDir: process.cwd()
1217
- }) : process.cwd();
1218
- const cliResult = await this.cliRunner.runCliJson(args, exportCwd, options?.organizationId);
1219
- if (!cliResult.ok) {
1220
- throw new Error(cliResult.error);
1221
- }
1222
- const result = cliResult.value;
1223
- if (delivery === "commit") {
1224
- return {
1225
- message: typeof result?.commitSha === "string" ? `Committed to ${result.branch ?? "branch"}: ${result.commitSha}` : "Export commit completed."
1226
- };
1227
- }
1228
- if (delivery === "pr") {
1229
- return {
1230
- message: typeof result?.prUrl === "string" ? `PR #${result.prNumber ?? "?"}: ${result.prUrl}` : "Export PR created."
1231
- };
1232
- }
1233
- if (delivery === "download") {
1234
- const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1235
- if (typeof target?.path !== "string") return null;
1236
- return {
1237
- path: target.path,
1238
- kind: target?.kind === "canonical" ? "canonical" : "entrypoint",
1239
- status: "up-to-date"
1240
- };
1241
- }).filter((target) => target !== null) : [];
1242
- const count = targets.length;
1243
- return {
1244
- message: `Wrote ${count} export file(s) to ${exportCwd}.`,
1245
- localStatus: {
1246
- overall: "up-to-date",
1247
- targets
1248
- }
1249
- };
1250
- }
1251
- return {
1252
- message: "Export copy payload generated."
1253
- };
1254
- }
1255
- };
1256
-
1257
- // src/services/organization-service.ts
1258
- var OrganizationService = class {
1259
- static {
1260
- __name(this, "OrganizationService");
1261
- }
1262
- apiUrl;
1263
- credentialsStore = new CredentialsStore();
1264
- constructor(apiUrl) {
1265
- this.apiUrl = apiUrl;
1266
- }
1267
- async listOrganizations() {
1268
- const token = await this.credentialsStore.getValidToken();
1269
- if (!token) {
1270
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1271
- }
1272
- const stored = this.credentialsStore.load();
1273
- const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
1274
- const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
1275
- const orgs = await bootstrapClient.organization.list.query();
1276
- return orgs.map((org) => ({
1277
- id: org.id,
1278
- name: org.name,
1279
- plan: org.plan,
1280
- role: org.role
1281
- }));
1282
- }
1283
- async createOrganization(input) {
1284
- const token = await this.credentialsStore.getValidToken();
1285
- if (!token) {
1286
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1287
- }
1288
- const stored = this.credentialsStore.load();
1289
- const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
1290
- const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
1291
- const createdOrg = await bootstrapClient.organization.create.mutate(input);
1292
- return {
1293
- id: createdOrg.id,
1294
- name: createdOrg.name,
1295
- plan: createdOrg.plan,
1296
- role: "owner"
1297
- };
1298
- }
1299
- async listProjects(organizationId) {
1300
- const token = await this.credentialsStore.getValidToken();
1301
- if (!token) {
1302
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1303
- }
1304
- const client2 = createApiClient(this.apiUrl, token, organizationId);
1305
- const projects = await client2.project.list.query({
1306
- limit: 100,
1307
- offset: 0
1308
- });
1309
- return projects.map((project) => ({
1310
- id: project.id,
1311
- name: project.name
1312
- }));
1313
- }
1314
- async createProject(organizationId, name) {
1315
- try {
1316
- const token = await this.credentialsStore.getValidToken();
1317
- if (!token) {
1318
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1319
- }
1320
- const client2 = createApiClient(this.apiUrl, token, organizationId);
1321
- const created = await client2.project.create.mutate({
1322
- name: name.trim()
1323
- });
1324
- return {
1325
- id: created.id,
1326
- name: String(created.name ?? name.trim())
1327
- };
1328
- } catch (error) {
1329
- const message = error instanceof Error ? error.message : String(error);
1330
- appendGlobalErrorLog({
1331
- source: "wizard.createProject",
1332
- message,
1333
- details: {
1334
- apiUrl: this.apiUrl,
1335
- organizationId,
1336
- projectName: name.trim(),
1337
- cwd: process.cwd()
1338
- }
1339
- });
1340
- throw error;
1341
- }
1342
- }
1343
- canCreateProject(org) {
1344
- const role = String(org?.role ?? "").toLowerCase();
1345
- return role === "owner" || role === "admin";
1346
- }
1347
- };
1348
-
1349
- // src/services/repo-service.ts
1350
- import { execFileSync } from "child_process";
1351
- import path4 from "path";
1352
- var RepoService = class {
1353
- static {
1354
- __name(this, "RepoService");
1355
- }
1356
- apiUrl;
1357
- credentialsStore = new CredentialsStore();
1358
- cliRunner;
1359
- constructor(apiUrl) {
1360
- this.apiUrl = apiUrl;
1361
- this.cliRunner = new CliRunner(apiUrl);
1362
- }
1363
- attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
1364
- const repoPath = process.cwd();
1365
- let args = [];
1366
- let lastOutputLines = [];
1367
- try {
1368
- const remoteUrl = this.execGit(repoPath, [
1369
- "remote",
1370
- "get-url",
1371
- "origin"
1372
- ]);
1373
- const token = await this.credentialsStore.getValidToken();
1374
- if (!token) {
1375
- throw new Error("No valid credentials. Run `spekn auth login` first.");
1376
- }
1377
- const client2 = createApiClient(this.apiUrl, token, organizationId);
1378
- const repos = await client2.gitRepository.list.query({
1379
- projectId,
1380
- limit: 100,
1381
- offset: 0
1382
- });
1383
- const isAlreadyAttached = repos.some((repo) => repo.repositoryUrl === remoteUrl);
1384
- const cliEntry = this.cliRunner.resolveCliEntry();
1385
- if (!cliEntry) {
1386
- throw new Error("Could not resolve CLI entrypoint for repo register.");
1387
- }
1388
- const runAnalyze = !isAlreadyAttached;
1389
- args = isAlreadyAttached ? [
1390
- cliEntry,
1391
- "repo",
1392
- "sync",
1393
- "--project-id",
1394
- projectId,
1395
- "--path",
1396
- repoPath,
1397
- "--api-url",
1398
- this.apiUrl,
1399
- "--no-analyze"
1400
- ] : [
1401
- cliEntry,
1402
- "repo",
1403
- "register",
1404
- "--project-id",
1405
- projectId,
1406
- "--path",
1407
- repoPath,
1408
- "--api-url",
1409
- this.apiUrl,
1410
- "--analyze"
1411
- ];
1412
- if (isAlreadyAttached) {
1413
- onProgress?.("Repository already attached to this project. Syncing metadata only (no analysis)...");
1414
- } else {
1415
- onProgress?.("Repository not attached yet. Registering and running analysis...");
1416
- }
1417
- const runResult = await this.cliRunner.runCliCommand(args.slice(1), {
1418
- cwd: repoPath,
1419
- organizationId,
1420
- onProgress,
1421
- requestInteraction,
1422
- onActivity
1423
- });
1424
- lastOutputLines = runResult.outputLines;
1425
- const exitCode = runResult.exitCode;
1426
- if (exitCode !== 0) {
1427
- appendGlobalErrorLog({
1428
- source: "wizard.registerCurrentRepository",
1429
- message: `Repository registration/analysis failed (exit ${exitCode}).`,
1430
- details: {
1431
- apiUrl: this.apiUrl,
1432
- organizationId,
1433
- projectId,
1434
- repoPath,
1435
- command: process.execPath,
1436
- args,
1437
- lastOutputLines: lastOutputLines.slice(-80)
1438
- }
1439
- });
1440
- throw new Error(`Repository registration/analysis failed (exit ${exitCode}).`);
1441
- }
1442
- if (runAnalyze) {
1443
- persistProjectContext(repoPath, {
1444
- projectId,
1445
- organizationId
1446
- });
1447
- } else {
1448
- persistProjectContextWithoutRepoPath(repoPath, {
1449
- projectId,
1450
- organizationId
1451
- });
1452
- }
1453
- return {
1454
- success: true,
1455
- analyzed: runAnalyze
1456
- };
1457
- } catch (error) {
1458
- const message = error instanceof Error ? error.message : String(error);
1459
- appendGlobalErrorLog({
1460
- source: "wizard.registerCurrentRepository",
1461
- message,
1462
- details: {
1463
- apiUrl: this.apiUrl,
1464
- organizationId,
1465
- projectId,
1466
- repoPath,
1467
- command: process.execPath,
1468
- args,
1469
- lastOutputLines: lastOutputLines.slice(-80)
1470
- }
1471
- });
1472
- throw error;
1473
- }
1474
- }, "attachOrSyncCurrentRepository");
1475
- async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1476
- const repoPath = path4.resolve(repoPathInput || process.cwd());
1477
- if (!this.cliRunner.resolveCliEntry()) {
1478
- return {
1479
- success: false,
1480
- output: "Could not resolve CLI entrypoint.",
1481
- exitCode: 1
1482
- };
1483
- }
1484
- const token = await this.credentialsStore.getValidToken();
1485
- if (!token) {
1486
- return {
1487
- success: false,
1488
- output: "No valid credentials. Run `spekn auth login` first.",
1489
- exitCode: 1
1490
- };
1491
- }
1492
- const args = [
1493
- "repo",
1494
- "sync",
1495
- "--project-id",
1496
- projectId,
1497
- "--path",
1498
- repoPath,
1499
- "--api-url",
1500
- this.apiUrl
1501
- ];
1502
- if (options?.analyze === false) {
1503
- args.push("--no-analyze");
1504
- }
1505
- if (options?.importToProject) {
1506
- args.push("--import-to-project");
1507
- }
1508
- if (typeof options?.maxFiles === "number" && Number.isFinite(options.maxFiles)) {
1509
- args.push("--max-files", String(Math.max(1, Math.floor(options.maxFiles))));
1510
- }
1511
- if (options?.analysisEngine) {
1512
- args.push("--analysis-engine", options.analysisEngine);
1513
- }
1514
- if (options?.agent && options.agent.trim().length > 0) {
1515
- args.push("--agent", options.agent.trim());
1516
- }
1517
- try {
1518
- const runResult = await this.cliRunner.runCliCommand(args, {
1519
- cwd: repoPath,
1520
- organizationId,
1521
- onProgress: options?.onProgress,
1522
- requestInteraction: options?.requestInteraction,
1523
- onActivity: options?.onActivity
1524
- });
1525
- return {
1526
- success: runResult.success,
1527
- output: runResult.output,
1528
- exitCode: runResult.exitCode
1529
- };
1530
- } catch (error) {
1531
- const message = error instanceof Error ? error.message : String(error);
1532
- return {
1533
- success: false,
1534
- output: message,
1535
- exitCode: 1
1536
- };
1537
- }
1538
- }
1539
- async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1540
- const result = await this.cliRunner.runCliCommand([
1541
- "repo",
1542
- "detach",
1543
- "--path",
1544
- repoPath
1545
- ], {
1546
- cwd: repoPath,
1547
- includeAuthToken: false
1548
- });
1549
- return {
1550
- success: result.success,
1551
- output: result.output || result.error || "Unknown detach error"
1552
- };
1553
- }
1554
- execGit(repoPath, args) {
1555
- try {
1556
- return execFileSync("git", [
1557
- "-C",
1558
- repoPath,
1559
- ...args
1560
- ], {
1561
- encoding: "utf-8",
1562
- stdio: [
1563
- "pipe",
1564
- "pipe",
1565
- "pipe"
1566
- ]
1567
- }).trim();
1568
- } catch {
1569
- throw new Error("Could not read git metadata. Run TUI from a git repository with an 'origin' remote.");
1570
- }
1571
- }
1572
- };
1573
-
1574
- // src/services/spec-service.ts
1575
- var SpecService = class {
1576
- static {
1577
- __name(this, "SpecService");
1578
- }
1579
- async loadSpecs(client2, projectId) {
1580
- const specs = await client2.specification.list.query({
1581
- projectId,
1582
- limit: 50,
1583
- offset: 0
1584
- });
1585
- return (Array.isArray(specs) ? specs : []).map((spec) => {
1586
- const frontmatter = spec.frontmatter ?? {};
1587
- const hints = frontmatter.hints ?? {};
1588
- const aiContext = frontmatter.aiContext ?? {};
1589
- const acp = frontmatter.acp ?? {};
1590
- const tags = Array.isArray(frontmatter.tags) ? frontmatter.tags.filter((tag) => typeof tag === "string") : [];
1591
- const aiFocusAreas = Array.isArray(aiContext.focusAreas) ? aiContext.focusAreas.filter((area) => typeof area === "string") : [];
1592
- const acpAllowedAgents = Array.isArray(acp.allowedAgents) ? acp.allowedAgents.filter((agent) => typeof agent === "string") : [];
1593
- const countArray = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.length : 0, "countArray");
1594
- return {
1595
- id: spec.id,
1596
- specRef: typeof frontmatter.specRef === "string" ? frontmatter.specRef : typeof spec.specRef === "string" ? spec.specRef : void 0,
1597
- frontmatter,
1598
- title: spec.title,
1599
- status: spec.status,
1600
- version: spec.version,
1601
- updatedAt: spec.updatedAt,
1602
- type: typeof frontmatter.type === "string" ? frontmatter.type : void 0,
1603
- content: typeof spec.content === "string" ? spec.content : void 0,
1604
- tags: tags.length > 0 ? tags : void 0,
1605
- author: typeof frontmatter.author === "string" ? frontmatter.author : void 0,
1606
- hintCounts: {
1607
- constraints: countArray(hints.constraints),
1608
- requirements: countArray(hints.requirements),
1609
- technical: countArray(hints.technical),
1610
- guidance: countArray(hints.guidance)
1611
- },
1612
- relationCounts: {
1613
- dependsOn: countArray(frontmatter.dependsOn),
1614
- conflictsWith: countArray(frontmatter.conflictsWith),
1615
- compatibleWith: countArray(frontmatter.compatibleWith)
1616
- },
1617
- acpPolicyMode: typeof acp.policyMode === "string" ? acp.policyMode : void 0,
1618
- acpAllowedAgents: acpAllowedAgents.length > 0 ? acpAllowedAgents : void 0,
1619
- aiTokenBudget: typeof aiContext.tokenBudget === "number" ? aiContext.tokenBudget : void 0,
1620
- aiFocusAreas: aiFocusAreas.length > 0 ? aiFocusAreas : void 0
1621
- };
1622
- });
1623
- }
1624
- async updateSpecificationContent(client2, projectId, specificationId, content) {
1625
- await client2.specification.update.mutate({
1626
- projectId,
1627
- id: specificationId,
1628
- data: {
1629
- content,
1630
- changeType: "patch",
1631
- changeDescription: "Edited from TUI editor"
1632
- }
1633
- });
1634
- }
1635
- async updateSpecificationStatus(client2, projectId, specificationId, status) {
1636
- await client2.specification.update.mutate({
1637
- projectId,
1638
- id: specificationId,
1639
- data: {
1640
- status,
1641
- changeType: "metadata",
1642
- changeDescription: `Status changed to ${status} from TUI`
1643
- }
1644
- });
1645
- }
1646
- async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1647
- const deleteMutation = client2?.specification?.delete?.mutate;
1648
- if (typeof deleteMutation !== "function") {
1649
- throw new Error("Specification delete route is unavailable.");
1650
- }
1651
- await deleteMutation({
1652
- projectId,
1653
- id: specificationId,
1654
- mode
1655
- });
1656
- }
1657
- async refineSpecificationWithAi(client2, input) {
1658
- const refineMutation = client2?.specification?.refine?.mutate;
1659
- if (typeof refineMutation !== "function") {
1660
- throw new Error("Specification refine route is unavailable.");
1661
- }
1662
- const result = await refineMutation({
1663
- projectId: input.projectId,
1664
- specificationContent: input.specContent,
1665
- userMessage: input.userMessage,
1666
- agentType: input.agentType
1667
- });
1668
- if (typeof result?.content !== "string") {
1669
- throw new Error("AI refinement response was missing content.");
1670
- }
1671
- return result.content;
1672
- }
1673
- };
1674
-
1675
- // src/services/context-service.ts
1676
- var TuiContextService = class {
1677
- static {
1678
- __name(this, "TuiContextService");
1679
- }
1680
- apiUrl;
1681
- authService;
1682
- bootstrapService;
1683
- bridgeService;
1684
- decisionService;
1685
- exportService;
1686
- organizationService;
1687
- repoService;
1688
- specService;
1689
- constructor(apiUrl) {
1690
- this.apiUrl = apiUrl;
1691
- this.authService = new AuthService(apiUrl);
1692
- this.bootstrapService = new BootstrapService(apiUrl);
1693
- this.bridgeService = new BridgeService(apiUrl);
1694
- this.decisionService = new DecisionService();
1695
- this.exportService = new ExportService(apiUrl);
1696
- this.organizationService = new OrganizationService(apiUrl);
1697
- this.repoService = new RepoService(apiUrl);
1698
- this.specService = new SpecService();
1699
- }
1700
- // ── Bootstrap ──────────────────────────────────────────────────────
1701
- async bootstrap(projectIdArg) {
1702
- return this.bootstrapService.bootstrap(projectIdArg);
1703
- }
1704
- hasDeclaredProjectContext(projectIdArg) {
1705
- return this.bootstrapService.hasDeclaredProjectContext(projectIdArg);
1706
- }
1707
- hasLocalProjectContext(repoPath) {
1708
- return this.bootstrapService.hasLocalProjectContext(repoPath);
1709
- }
1710
- async loadWorkflowSummary(client2, projectId) {
1711
- return this.bootstrapService.loadWorkflowSummary(client2, projectId);
1712
- }
1713
- persistContext(organizationId, projectId) {
1714
- this.bootstrapService.persistContext(organizationId, projectId);
1715
- }
1716
- // ── Auth ───────────────────────────────────────────────────────────
1717
- async checkAuthentication() {
1718
- return this.authService.checkAuthentication();
1719
- }
1720
- async authenticateViaCli(onProgress) {
1721
- return this.authService.authenticateViaCli(onProgress);
1722
- }
1723
- extractUserEmail(token) {
1724
- return this.authService.extractUserEmail(token);
1725
- }
1726
- extractTokenExpiry(token) {
1727
- return this.authService.extractTokenExpiry(token);
1728
- }
1729
- // ── Organization & Project ─────────────────────────────────────────
1730
- async listOrganizations() {
1731
- return this.organizationService.listOrganizations();
1732
- }
1733
- async createOrganization(input) {
1734
- return this.organizationService.createOrganization(input);
1735
- }
1736
- async listProjects(organizationId) {
1737
- return this.organizationService.listProjects(organizationId);
1738
- }
1739
- async createProject(organizationId, name) {
1740
- return this.organizationService.createProject(organizationId, name);
1741
- }
1742
- canCreateProject(org) {
1743
- return this.organizationService.canCreateProject(org);
1744
- }
1745
- // ── Specs ──────────────────────────────────────────────────────────
1746
- async loadSpecs(client2, projectId) {
1747
- return this.specService.loadSpecs(client2, projectId);
1748
- }
1749
- async updateSpecificationContent(client2, projectId, specificationId, content) {
1750
- return this.specService.updateSpecificationContent(client2, projectId, specificationId, content);
1751
- }
1752
- async updateSpecificationStatus(client2, projectId, specificationId, status) {
1753
- return this.specService.updateSpecificationStatus(client2, projectId, specificationId, status);
1754
- }
1755
- async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1756
- return this.specService.deleteSpecification(client2, projectId, specificationId, mode);
1757
- }
1758
- async refineSpecificationWithAi(client2, input) {
1759
- return this.specService.refineSpecificationWithAi(client2, input);
1760
- }
1761
- // ── Decisions ──────────────────────────────────────────────────────
1762
- async loadDecisions(client2, projectId) {
1763
- return this.decisionService.loadDecisions(client2, projectId);
1764
- }
1765
- async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1766
- return this.decisionService.resolveDecision(client2, projectId, decisionId, status, reason, existingRationale);
1767
- }
1768
- async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1769
- return this.decisionService.deleteDecision(client2, projectId, decisionId, mode);
1770
- }
1771
- // ── Export ─────────────────────────────────────────────────────────
1772
- async previewExport(client2, projectId, format) {
1773
- return this.exportService.previewExport(client2, projectId, format);
1774
- }
1775
- async generateExport(client2, projectId, format) {
1776
- return this.exportService.generateExport(client2, projectId, format);
1777
- }
1778
- async discoverExportCapabilities(projectId, organizationId) {
1779
- return this.exportService.discoverExportCapabilities(projectId, organizationId);
1780
- }
1781
- async exportStatus(projectId, format, options) {
1782
- return this.exportService.exportStatus(projectId, format, options);
1783
- }
1784
- async deliverExport(projectId, format, delivery, options) {
1785
- return this.exportService.deliverExport(projectId, format, delivery, options);
1786
- }
1787
- // ── Bridge ─────────────────────────────────────────────────────────
1788
- async loadBridgeSummary(client2) {
1789
- return this.bridgeService.loadBridgeSummary(client2);
1790
- }
1791
- async loadLocalBridgeSummary() {
1792
- return this.bridgeService.loadLocalBridgeSummary();
1793
- }
1794
- startLocalBridgeDetached() {
1795
- this.bridgeService.startLocalBridgeDetached();
1796
- }
1797
- async stopLocalBridge(configPort) {
1798
- return this.bridgeService.stopLocalBridge(configPort);
1799
- }
1800
- async loadBridgeLogs(port, since) {
1801
- return this.bridgeService.loadBridgeLogs(port, since);
1802
- }
1803
- // ── Repository ─────────────────────────────────────────────────────
1804
- attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
1805
- return this.repoService.attachOrSyncCurrentRepository(organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity);
1806
- }, "attachOrSyncCurrentRepository");
1807
- async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1808
- return this.repoService.syncRepositoryViaCli(organizationId, projectId, repoPathInput, options);
1809
- }
1810
- async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1811
- return this.repoService.detachContextViaCli(_projectId, repoPath);
1812
- }
1813
- };
1814
-
1815
- // src/store/service-bridge.ts
1816
- var service = null;
1817
- var client = null;
1818
- function initServiceBridge(apiUrl) {
1819
- if (!service) {
1820
- service = new TuiContextService(apiUrl);
1821
- }
1822
- return service;
1823
- }
1824
- __name(initServiceBridge, "initServiceBridge");
1825
- function getService() {
1826
- if (!service) {
1827
- throw new Error("Service bridge not initialized. Call initServiceBridge() first.");
1828
- }
1829
- return service;
1830
- }
1831
- __name(getService, "getService");
1832
- function getClient() {
1833
- return client;
1834
- }
1835
- __name(getClient, "getClient");
1836
- function setClient(c) {
1837
- client = c;
1838
- }
1839
- __name(setClient, "setClient");
1840
-
1841
- // src/store/use-tui-ui-store.ts
1842
- import { create } from "zustand";
1843
- import { subscribeWithSelector } from "zustand/middleware";
1844
- var _initialScreen = "home";
1845
- function setInitialScreen(screen) {
1846
- _initialScreen = screen;
1847
- }
1848
- __name(setInitialScreen, "setInitialScreen");
1849
- var initialState = {
1850
- screen: _initialScreen,
1851
- showHelp: false,
1852
- commandMode: false,
1853
- searchQuery: "",
1854
- navMode: "content",
1855
- cursorSpec: null,
1856
- cursorDecision: null,
1857
- openedSpecId: void 0,
1858
- editorMenuOpen: false,
1859
- statusMenuOpen: false,
1860
- aiRefineMenuOpen: false,
1861
- editorLaunching: false,
1862
- selectedEditor: "",
1863
- selectedOrganizationIndex: void 0,
1864
- selectedProjectIndex: void 0,
1865
- newProjectName: void 0,
1866
- selectedAnalysisAgent: "auto"
1867
- };
1868
- var useTuiUiStore = create()(subscribeWithSelector((set) => ({
1869
- ...initialState,
1870
- screen: _initialScreen,
1871
- setScreen: /* @__PURE__ */ __name((screen) => set({
1872
- screen
1873
- }), "setScreen"),
1874
- toggleHelp: /* @__PURE__ */ __name(() => set((prev) => ({
1875
- showHelp: !prev.showHelp
1876
- })), "toggleHelp"),
1877
- setShowHelp: /* @__PURE__ */ __name((show) => set({
1878
- showHelp: show
1879
- }), "setShowHelp"),
1880
- setCommandMode: /* @__PURE__ */ __name((enabled) => set({
1881
- commandMode: enabled
1882
- }), "setCommandMode"),
1883
- setSearchQuery: /* @__PURE__ */ __name((query) => set({
1884
- searchQuery: query
1885
- }), "setSearchQuery"),
1886
- setNavMode: /* @__PURE__ */ __name((mode) => set({
1887
- navMode: mode
1888
- }), "setNavMode"),
1889
- setCursorSpec: /* @__PURE__ */ __name((spec) => set({
1890
- cursorSpec: spec
1891
- }), "setCursorSpec"),
1892
- setCursorDecision: /* @__PURE__ */ __name((decision) => set({
1893
- cursorDecision: decision
1894
- }), "setCursorDecision"),
1895
- setOpenedSpecId: /* @__PURE__ */ __name((specId) => set({
1896
- openedSpecId: specId
1897
- }), "setOpenedSpecId"),
1898
- setSelectedEditor: /* @__PURE__ */ __name((editor) => set({
1899
- selectedEditor: editor
1900
- }), "setSelectedEditor"),
1901
- setEditorMenuOpen: /* @__PURE__ */ __name((open) => set({
1902
- editorMenuOpen: open
1903
- }), "setEditorMenuOpen"),
1904
- setStatusMenuOpen: /* @__PURE__ */ __name((open) => set({
1905
- statusMenuOpen: open
1906
- }), "setStatusMenuOpen"),
1907
- setAiRefineMenuOpen: /* @__PURE__ */ __name((open) => set({
1908
- aiRefineMenuOpen: open
1909
- }), "setAiRefineMenuOpen"),
1910
- setEditorLaunching: /* @__PURE__ */ __name((launching) => set({
1911
- editorLaunching: launching
1912
- }), "setEditorLaunching"),
1913
- openEditorMenuForSpec: /* @__PURE__ */ __name((specId, editor) => set({
1914
- openedSpecId: specId,
1915
- selectedEditor: editor,
1916
- editorMenuOpen: true
1917
- }), "openEditorMenuForSpec"),
1918
- resetSpecsUi: /* @__PURE__ */ __name(() => set({
1919
- openedSpecId: void 0,
1920
- cursorSpec: null,
1921
- editorMenuOpen: false,
1922
- statusMenuOpen: false,
1923
- aiRefineMenuOpen: false,
1924
- editorLaunching: false
1925
- }), "resetSpecsUi"),
1926
- setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
1927
- selectedOrganizationIndex: index
1928
- }), "setSelectedOrganizationIndex"),
1929
- setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
1930
- selectedProjectIndex: index
1931
- }), "setSelectedProjectIndex"),
1932
- setNewProjectName: /* @__PURE__ */ __name((name) => set({
1933
- newProjectName: name
1934
- }), "setNewProjectName"),
1935
- setSelectedAnalysisAgent: /* @__PURE__ */ __name((agent) => set({
1936
- selectedAnalysisAgent: agent
1937
- }), "setSelectedAnalysisAgent"),
1938
- resetOnboardingUi: /* @__PURE__ */ __name(() => set({
1939
- selectedOrganizationIndex: void 0,
1940
- selectedProjectIndex: void 0,
1941
- newProjectName: void 0,
1942
- selectedAnalysisAgent: "auto"
1943
- }), "resetOnboardingUi"),
1944
- showTooltip: /* @__PURE__ */ __name((message, duration = 3e3) => set((state) => {
1945
- if (state.tooltipTimeout) {
1946
- clearTimeout(state.tooltipTimeout);
1947
- }
1948
- const timeout = setTimeout(() => {
1949
- useTuiUiStore.getState().clearTooltip();
1950
- }, duration);
1951
- return {
1952
- tooltip: message,
1953
- tooltipTimeout: timeout
1954
- };
1955
- }), "showTooltip"),
1956
- clearTooltip: /* @__PURE__ */ __name(() => set((state) => {
1957
- if (state.tooltipTimeout) {
1958
- clearTimeout(state.tooltipTimeout);
1959
- }
1960
- return {
1961
- tooltip: void 0,
1962
- tooltipTimeout: void 0
1963
- };
1964
- }), "clearTooltip")
1965
- })));
1966
-
1967
- // src/capabilities/policy.ts
1968
- var TIER_ORDER = {
1969
- [OrganizationPlan.FREE]: 0,
1970
- [OrganizationPlan.PRO]: 1,
1971
- [OrganizationPlan.TEAM]: 2,
1972
- [OrganizationPlan.ENTERPRISE]: 3
1973
- };
1974
- var NAV_DEFINITIONS = [
1975
- {
1976
- id: "home",
1977
- label: "Home",
1978
- description: "Next actions and workflow pulse",
1979
- requiredPlan: OrganizationPlan.FREE
1980
- },
1981
- {
1982
- id: "specs",
1983
- label: "Specs",
1984
- description: "Manage governed specifications",
1985
- requiredPlan: OrganizationPlan.FREE
1986
- },
1987
- {
1988
- id: "decisions",
1989
- label: "Decision Log",
1990
- description: "Review decisions and rationale",
1991
- requiredPlan: OrganizationPlan.FREE
1992
- },
1993
- {
1994
- id: "export",
1995
- label: "Export",
1996
- description: "Generate AGENTS.md / CLAUDE.md / .cursorrules",
1997
- requiredPlan: OrganizationPlan.FREE
1998
- },
1999
- {
2000
- id: "bridge",
2001
- label: "Local Bridge",
2002
- description: "Bridge status and controls",
2003
- requiredPlan: OrganizationPlan.FREE
2004
- },
2005
- {
2006
- id: "active-runs",
2007
- label: "Active Runs",
2008
- description: "Realtime orchestration dashboard",
2009
- requiredPlan: OrganizationPlan.TEAM
2010
- },
2011
- {
2012
- id: "phase-gates",
2013
- label: "Phase Gates",
2014
- description: "Approve and unblock workflow phases",
2015
- requiredPlan: OrganizationPlan.TEAM
2016
- },
2017
- {
2018
- id: "skills-marketplace",
2019
- label: "Skills Marketplace",
2020
- description: "Manage shared managed skills",
2021
- requiredPlan: OrganizationPlan.TEAM
2022
- },
2023
- {
2024
- id: "org-governance",
2025
- label: "Org Governance",
2026
- description: "Compliance, policy, deployment gates",
2027
- requiredPlan: OrganizationPlan.ENTERPRISE
2028
- }
2029
- ];
2030
- var GATE_DISABLED_PHASES = [
2031
- WorkflowPhase.SPECIFY,
2032
- WorkflowPhase.CLARIFY
2033
- ];
2034
- function meetsMinimumTier(current, required) {
2035
- return TIER_ORDER[current] >= TIER_ORDER[required];
2036
- }
2037
- __name(meetsMinimumTier, "meetsMinimumTier");
2038
- function resolveNavPolicy(ctx) {
2039
- return NAV_DEFINITIONS.map((item) => {
2040
- if (!meetsMinimumTier(ctx.plan, item.requiredPlan)) {
2041
- return {
2042
- ...item,
2043
- state: "locked",
2044
- reason: `Requires ${item.requiredPlan.toUpperCase()} tier`
2045
- };
2046
- }
2047
- if (item.id === "phase-gates" && ctx.role === "viewer") {
2048
- return {
2049
- ...item,
2050
- state: "disabled",
2051
- reason: "Viewer role cannot approve gates"
2052
- };
2053
- }
2054
- if (item.id === "phase-gates" && ctx.workflowPhase && GATE_DISABLED_PHASES.includes(ctx.workflowPhase)) {
2055
- return {
2056
- ...item,
2057
- state: "disabled",
2058
- reason: `Gate approvals are unavailable in ${ctx.workflowPhase} phase`
2059
- };
2060
- }
2061
- return {
2062
- ...item,
2063
- state: "enabled"
2064
- };
2065
- });
2066
- }
2067
- __name(resolveNavPolicy, "resolveNavPolicy");
2068
-
2069
- // src/state/onboarding-utils.ts
2070
- function logOnboardingAttachResult(appendLog, result) {
2071
- if (result.warning) {
2072
- appendLog(`[warn] ${result.warning}`);
2073
- }
2074
- if (result.analyzed) {
2075
- appendLog("[setup] Repository attached and analysis complete.");
2076
- } else if (result.warning) {
2077
- appendLog("[setup] Repository attached; analysis did not fully complete.");
2078
- } else {
2079
- appendLog("[setup] Repository already attached. Metadata sync complete (analysis skipped).");
2080
- }
2081
- }
2082
- __name(logOnboardingAttachResult, "logOnboardingAttachResult");
2083
-
2084
- // src/store/windows/use-onboarding-window.ts
2085
- import { create as create2 } from "zustand";
2086
- import { subscribeWithSelector as subscribeWithSelector2 } from "zustand/middleware";
2087
- var useOnboardingWindow = create2()(subscribeWithSelector2((set) => ({
2088
- mode: "initial-setup",
2089
- step: "organization",
2090
- attachCurrentFolder: true,
2091
- runLines: [],
2092
- runStatus: "running",
2093
- availableAgents: [],
2094
- canCreateProject: false,
2095
- toolCalls: {},
2096
- setMode: /* @__PURE__ */ __name((mode) => set({
2097
- mode
2098
- }), "setMode"),
2099
- setStep: /* @__PURE__ */ __name((step) => set({
2100
- step
2101
- }), "setStep"),
2102
- setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
2103
- selectedOrganizationIndex: index
2104
- }), "setSelectedOrganizationIndex"),
2105
- setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
2106
- selectedProjectIndex: index
2107
- }), "setSelectedProjectIndex"),
2108
- setNewProjectName: /* @__PURE__ */ __name((name) => set({
2109
- newProjectName: name
2110
- }), "setNewProjectName"),
2111
- setAttachCurrentFolder: /* @__PURE__ */ __name((attach) => set({
2112
- attachCurrentFolder: attach
2113
- }), "setAttachCurrentFolder"),
2114
- setRunLines: /* @__PURE__ */ __name((lines) => set({
2115
- runLines: lines
2116
- }), "setRunLines"),
2117
- addRunLine: /* @__PURE__ */ __name((line) => set((state) => ({
2118
- runLines: [
2119
- ...state.runLines,
2120
- line
2121
- ].slice(-400)
2122
- })), "addRunLine"),
2123
- setRunStatus: /* @__PURE__ */ __name((status) => set({
2124
- runStatus: status
2125
- }), "setRunStatus"),
2126
- setInteraction: /* @__PURE__ */ __name((interaction) => set({
2127
- interaction
2128
- }), "setInteraction"),
2129
- setError: /* @__PURE__ */ __name((error) => set({
2130
- error
2131
- }), "setError"),
2132
- setSelectedOrganizationId: /* @__PURE__ */ __name((id) => set({
2133
- selectedOrganizationId: id
2134
- }), "setSelectedOrganizationId"),
2135
- setSelectedProjectId: /* @__PURE__ */ __name((id) => set({
2136
- selectedProjectId: id
2137
- }), "setSelectedProjectId"),
2138
- setAvailableAgents: /* @__PURE__ */ __name((agents) => set({
2139
- availableAgents: agents
2140
- }), "setAvailableAgents"),
2141
- setCanCreateProject: /* @__PURE__ */ __name((canCreate) => set({
2142
- canCreateProject: canCreate
2143
- }), "setCanCreateProject"),
2144
- upsertToolCall: /* @__PURE__ */ __name((event) => set((state) => {
2145
- const id = event.toolCallId ?? `tc-${Date.now()}`;
2146
- const existing = state.toolCalls[id];
2147
- const updated = existing ? {
2148
- ...existing,
2149
- status: event.status ?? existing.status,
2150
- title: event.title ?? existing.title,
2151
- locations: event.locations ?? existing.locations,
2152
- completedAt: event.status === "completed" || event.status === "failed" ? Date.now() : existing.completedAt
2153
- } : {
2154
- toolCallId: id,
2155
- title: event.title ?? event.toolName ?? "Tool call",
2156
- toolName: event.toolName,
2157
- kind: event.kind ?? "other",
2158
- status: event.status ?? "in_progress",
2159
- locations: event.locations ?? [],
2160
- startedAt: Date.now()
2161
- };
2162
- return {
2163
- toolCalls: {
2164
- ...state.toolCalls,
2165
- [id]: updated
2166
- }
2167
- };
2168
- }), "upsertToolCall"),
2169
- setActiveThought: /* @__PURE__ */ __name((text) => set({
2170
- activeThought: text
2171
- }), "setActiveThought"),
2172
- reset: /* @__PURE__ */ __name(() => set({
2173
- mode: "initial-setup",
2174
- step: "organization",
2175
- selectedOrganizationIndex: void 0,
2176
- selectedProjectIndex: void 0,
2177
- newProjectName: void 0,
2178
- attachCurrentFolder: true,
2179
- runLines: [],
2180
- runStatus: "running",
2181
- interaction: void 0,
2182
- error: void 0,
2183
- selectedOrganizationId: void 0,
2184
- selectedProjectId: void 0,
2185
- availableAgents: [],
2186
- canCreateProject: false,
2187
- toolCalls: {},
2188
- activeThought: void 0
2189
- }), "reset")
2190
- })));
2191
-
2192
- // src/store/auth-utils.ts
2193
- function isAuthenticationError(message) {
2194
- const normalized = message.toLowerCase();
2195
- 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");
2196
- }
2197
- __name(isAuthenticationError, "isAuthenticationError");
2198
-
2199
- // src/store/use-project-data-store.ts
2200
- import { create as create3 } from "zustand";
2201
- import { subscribeWithSelector as subscribeWithSelector3 } from "zustand/middleware";
2202
- var EMPTY_WORKFLOW = {
2203
- currentPhase: null,
2204
- blockedCount: 0,
2205
- hasPlanningArtifacts: false,
2206
- hasVerificationEvidence: false
2207
- };
2208
- var useProjectDataStore = create3()(subscribeWithSelector3((set, get) => ({
2209
- specs: [],
2210
- decisions: [],
2211
- workflow: EMPTY_WORKFLOW,
2212
- navPolicy: [],
2213
- setProjectData: /* @__PURE__ */ __name((specs, decisions, workflow, navPolicy) => set({
2214
- specs,
2215
- decisions,
2216
- workflow,
2217
- navPolicy
2218
- }), "setProjectData"),
2219
- setPollingData: /* @__PURE__ */ __name((workflow, navPolicy) => set({
2220
- workflow,
2221
- navPolicy
2222
- }), "setPollingData"),
2223
- clearProjectData: /* @__PURE__ */ __name(() => set({
2224
- specs: [],
2225
- decisions: [],
2226
- workflow: EMPTY_WORKFLOW,
2227
- navPolicy: []
2228
- }), "clearProjectData"),
2229
- updateSpecificationContent: /* @__PURE__ */ __name(async (specificationId, content) => {
2230
- const client2 = getClient();
2231
- const boot = getBootContext();
2232
- if (!client2 || !boot) return;
2233
- await withSessionFeedback({
2234
- statusLine: "Saving specification...",
2235
- action: /* @__PURE__ */ __name(() => getService().updateSpecificationContent(client2, boot.projectId, specificationId, content), "action"),
2236
- successLog: "[specs] saved specification changes",
2237
- failureLog: "[error] save failed",
2238
- failureStatusLine: "Save failed"
2239
- });
2240
- }, "updateSpecificationContent"),
2241
- updateSpecificationStatus: /* @__PURE__ */ __name(async (specificationId, status, options) => {
2242
- const client2 = getClient();
2243
- const boot = getBootContext();
2244
- if (!client2 || !boot) return;
2245
- setSessionStatusLine(`Updating status to ${status}...`);
2246
- try {
2247
- await getService().updateSpecificationStatus(client2, boot.projectId, specificationId, status);
2248
- appendSessionLog(`[specs] status updated to ${status}`);
2249
- if (options?.refresh !== false) {
2250
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KS4DPNDY.mjs");
2251
- await useSessionStore2.getState().refresh();
2252
- }
2253
- } catch (error) {
2254
- const message = error instanceof Error ? error.message : String(error);
2255
- appendSessionLog(`[error] status update failed: ${message}`);
2256
- setSessionStatusLine("Status update failed");
2257
- refreshOnAuthenticationError(message);
2258
- }
2259
- }, "updateSpecificationStatus"),
2260
- deleteSpecification: /* @__PURE__ */ __name(async (specificationId, mode = "archive", options) => {
2261
- const client2 = getClient();
2262
- const boot = getBootContext();
2263
- if (!client2 || !boot) return;
2264
- setSessionStatusLine(mode === "delete" ? "Deleting specification permanently..." : "Archiving specification...");
2265
- try {
2266
- await getService().deleteSpecification(client2, boot.projectId, specificationId, mode);
2267
- appendSessionLog(mode === "delete" ? "[specs] specification deleted permanently" : "[specs] specification archived");
2268
- if (options?.refresh !== false) {
2269
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KS4DPNDY.mjs");
2270
- await useSessionStore2.getState().refresh();
2271
- }
2272
- } catch (error) {
2273
- const message = error instanceof Error ? error.message : String(error);
2274
- appendSessionLog(`[error] specification ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2275
- setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2276
- refreshOnAuthenticationError(message);
2277
- }
2278
- }, "deleteSpecification"),
2279
- refineSpecificationWithAi: /* @__PURE__ */ __name(async (specificationId, userMessage) => {
2280
- const client2 = getClient();
2281
- const boot = getBootContext();
2282
- const { specs } = get();
2283
- if (!client2 || !boot) return;
2284
- const spec = specs.find((item) => item.id === specificationId);
2285
- if (!spec) {
2286
- appendSessionLog("[error] refine failed: specification not found in current list");
2287
- setSessionStatusLine("Refinement failed");
2288
- return;
2289
- }
2290
- const specContent = (spec.content ?? "").trim();
2291
- if (!specContent) {
2292
- appendSessionLog("[error] refine failed: selected specification has no content");
2293
- setSessionStatusLine("Refinement failed");
2294
- return;
2295
- }
2296
- setSessionStatusLine("Refining specification with AI...");
2297
- const service2 = getService();
2298
- try {
2299
- const refinedContent = await service2.refineSpecificationWithAi(client2, {
2300
- projectId: boot.projectId,
2301
- specContent,
2302
- userMessage,
2303
- agentType: "codex"
2304
- });
2305
- await service2.updateSpecificationContent(client2, boot.projectId, specificationId, refinedContent);
2306
- appendSessionLog("[specs] AI refinement applied and saved");
2307
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KS4DPNDY.mjs");
2308
- await useSessionStore2.getState().refresh();
2309
- } catch (error) {
2310
- const message = error instanceof Error ? error.message : String(error);
2311
- appendSessionLog(`[error] AI refinement failed: ${message}`);
2312
- setSessionStatusLine("AI refinement failed");
2313
- refreshOnAuthenticationError(message);
2314
- }
2315
- }, "refineSpecificationWithAi"),
2316
- resolveDecision: /* @__PURE__ */ __name(async (decisionId, status, reason, existingRationale, options) => {
2317
- const client2 = getClient();
2318
- const boot = getBootContext();
2319
- if (!client2 || !boot) {
2320
- throw new Error("Decision update unavailable: project context is not initialized.");
2321
- }
2322
- setSessionStatusLine(`Resolving decision as ${status}...`);
2323
- try {
2324
- await getService().resolveDecision(client2, boot.projectId, decisionId, status, reason, existingRationale);
2325
- appendSessionLog(`[decisions] ${decisionId} -> ${status}`);
2326
- if (options?.refresh !== false) {
2327
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KS4DPNDY.mjs");
2328
- await useSessionStore2.getState().refresh();
2329
- }
2330
- } catch (error) {
2331
- const message = error instanceof Error ? error.message : String(error);
2332
- appendSessionLog(`[error] decision resolution failed: ${message}`);
2333
- setSessionStatusLine("Decision resolution failed");
2334
- refreshOnAuthenticationError(message);
2335
- throw error;
2336
- }
2337
- }, "resolveDecision"),
2338
- deleteDecision: /* @__PURE__ */ __name(async (decisionId, mode = "archive", options) => {
2339
- const client2 = getClient();
2340
- const boot = getBootContext();
2341
- if (!client2 || !boot) {
2342
- throw new Error("Decision delete unavailable: project context is not initialized.");
2343
- }
2344
- setSessionStatusLine(mode === "delete" ? "Deleting decision permanently..." : "Archiving decision...");
2345
- try {
2346
- await getService().deleteDecision(client2, boot.projectId, decisionId, mode);
2347
- appendSessionLog(mode === "delete" ? `[decisions] ${decisionId} deleted permanently` : `[decisions] ${decisionId} archived`);
2348
- if (options?.refresh !== false) {
2349
- const { useSessionStore: useSessionStore2 } = await import("./use-session-store-KS4DPNDY.mjs");
2350
- await useSessionStore2.getState().refresh();
2351
- }
2352
- } catch (error) {
2353
- const message = error instanceof Error ? error.message : String(error);
2354
- appendSessionLog(`[error] decision ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2355
- setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2356
- refreshOnAuthenticationError(message);
2357
- throw error;
2358
- }
2359
- }, "deleteDecision")
2360
- })));
2361
-
2362
- // src/store/use-export-store.ts
2363
- import { create as create4 } from "zustand";
2364
- import { subscribeWithSelector as subscribeWithSelector4 } from "zustand/middleware";
2365
-
2366
- // src/utils/clipboard.ts
2367
- import { spawnSync } from "child_process";
2368
- function clipboardAttempts() {
2369
- if (process.platform === "darwin") {
2370
- return [
2371
- {
2372
- cmd: "pbcopy",
2373
- args: []
2374
- }
2375
- ];
2376
- }
2377
- if (process.platform === "win32") {
2378
- return [
2379
- {
2380
- cmd: "clip",
2381
- args: []
2382
- }
2383
- ];
2384
- }
2385
- return [
2386
- {
2387
- cmd: "wl-copy",
2388
- args: []
2389
- },
2390
- {
2391
- cmd: "xclip",
2392
- args: [
2393
- "-selection",
2394
- "clipboard"
2395
- ]
2396
- },
2397
- {
2398
- cmd: "xsel",
2399
- args: [
2400
- "--clipboard",
2401
- "--input"
2402
- ]
2403
- }
2404
- ];
2405
- }
2406
- __name(clipboardAttempts, "clipboardAttempts");
2407
- function copyTextToClipboard(text) {
2408
- const attempts = clipboardAttempts();
2409
- let lastError = "No clipboard command available.";
2410
- for (const attempt of attempts) {
2411
- const result = spawnSync(attempt.cmd, attempt.args, {
2412
- input: text,
2413
- encoding: "utf8",
2414
- stdio: [
2415
- "pipe",
2416
- "ignore",
2417
- "pipe"
2418
- ]
2419
- });
2420
- if (!result.error && result.status === 0) {
2421
- return {
2422
- ok: true
2423
- };
2424
- }
2425
- lastError = (result.error?.message ?? result.stderr?.trim()) || `${attempt.cmd} exited with status ${result.status}`;
2426
- }
2427
- return {
2428
- ok: false,
2429
- error: lastError
2430
- };
2431
- }
2432
- __name(copyTextToClipboard, "copyTextToClipboard");
2433
-
2434
- // src/store/use-export-store.ts
2435
- var EMPTY_EXPORT_JOB = {
2436
- action: null,
2437
- status: "idle"
2438
- };
2439
- async function runExport(action) {
2440
- const state = useExportStore.getState();
2441
- const boot = getBootContext();
2442
- if (!boot) return;
2443
- if (state.exportInFlight) {
2444
- appendSessionLog("[warn] Export already in progress");
2445
- return;
2446
- }
2447
- const format = state.exportFormat;
2448
- useExportStore.setState({
2449
- exportInFlight: true,
2450
- exportJob: {
2451
- action,
2452
- status: "running",
2453
- format
2454
- }
2455
- });
2456
- setSessionStatusLine(action === "preview" ? "Previewing export..." : "Generating export...");
2457
- const service2 = getService();
2458
- const client2 = getClient();
2459
- try {
2460
- if (action === "status") {
2461
- const status = await service2.exportStatus(boot.projectId, format, {
2462
- mode: state.exportMode,
2463
- scopePath: state.exportScopePath || void 0,
2464
- organizationId: boot.organizationId
2465
- });
2466
- useExportStore.setState({
2467
- exportStatus: status,
2468
- exportJob: {
2469
- action,
2470
- status: "success",
2471
- format
2472
- }
2473
- });
2474
- setSessionStatusLine(`Export status: ${status.overall}`);
2475
- appendSessionLog(`[export] Status ${format}: ${status.overall}`);
2476
- return;
2477
- }
2478
- if (action === "commit" || action === "pr") {
2479
- const delivery = action === "commit" ? "commit" : "pr";
2480
- const result = await service2.deliverExport(boot.projectId, format, delivery, {
2481
- mode: state.exportMode,
2482
- scopePath: state.exportScopePath || void 0,
2483
- organizationId: boot.organizationId
2484
- });
2485
- useExportStore.setState({
2486
- exportJob: {
2487
- action,
2488
- status: "success",
2489
- format
2490
- }
2491
- });
2492
- setSessionStatusLine(result.message);
2493
- appendSessionLog(`[export] ${result.message}`);
2494
- return;
2495
- }
2496
- const output = action === "preview" ? await service2.previewExport(client2, boot.projectId, format) : await service2.generateExport(client2, boot.projectId, format);
2497
- useExportStore.setState({
2498
- exportPreview: output,
2499
- exportJob: {
2500
- action,
2501
- status: "success",
2502
- format
2503
- }
2504
- });
2505
- setSessionStatusLine(action === "preview" ? "Export preview ready" : "Export generated");
2506
- const verb = action === "preview" ? "Previewed" : "Generated";
2507
- appendSessionLog(`[export] ${verb} ${format} (${output.anchorCount} anchors)`);
2508
- } catch (error) {
2509
- const message = error instanceof Error ? error.message : String(error);
2510
- useExportStore.setState({
2511
- exportJob: {
2512
- action,
2513
- status: "error",
2514
- format,
2515
- error: message
2516
- }
2517
- });
2518
- setSessionStatusLine(action === "preview" ? "Export preview failed" : "Export generation failed");
2519
- appendSessionLog(`[error] Export ${action} failed: ${message}`);
2520
- refreshOnAuthenticationError(message);
2521
- } finally {
2522
- useExportStore.setState({
2523
- exportInFlight: false
2524
- });
2525
- }
2526
- }
2527
- __name(runExport, "runExport");
2528
- var useExportStore = create4()(subscribeWithSelector4((set, get) => ({
2529
- exportFormat: "agents-md",
2530
- exportMode: "global",
2531
- exportScopePath: "",
2532
- exportDelivery: "download",
2533
- exportCapabilities: null,
2534
- exportPreview: null,
2535
- exportStatus: null,
2536
- exportValidation: {
2537
- open: false
2538
- },
2539
- exportJob: EMPTY_EXPORT_JOB,
2540
- exportInFlight: false,
2541
- setCapabilities: /* @__PURE__ */ __name((capabilities) => {
2542
- set((prev) => {
2543
- const discoveredFormats = capabilities?.formats?.map((f) => f.id) ?? [];
2544
- const discoveredModes = capabilities?.modes ?? [];
2545
- const resolvedFormat = discoveredFormats.length > 0 ? discoveredFormats.includes(prev.exportFormat) ? prev.exportFormat : discoveredFormats[0] : prev.exportFormat;
2546
- const resolvedMode = discoveredModes.length > 0 ? discoveredModes.includes(prev.exportMode) ? prev.exportMode : discoveredModes[0] : prev.exportMode;
2547
- return {
2548
- exportCapabilities: capabilities,
2549
- exportFormat: resolvedFormat,
2550
- exportMode: resolvedMode
2551
- };
2552
- });
2553
- }, "setCapabilities"),
2554
- setExportFormat: /* @__PURE__ */ __name((format) => {
2555
- set((prev) => {
2556
- const allowedFormats = prev.exportCapabilities?.formats.map((f) => f.id) ?? [];
2557
- if (allowedFormats.length > 0 && !allowedFormats.includes(format)) {
2558
- setSessionStatusLine(`Export format unavailable: ${format}`);
2559
- return prev;
2560
- }
2561
- if (prev.exportFormat === format) return prev;
2562
- setSessionStatusLine(`Export format set to ${format}`);
2563
- return {
2564
- exportFormat: format,
2565
- exportPreview: null,
2566
- exportStatus: null,
2567
- exportValidation: {
2568
- open: false
2569
- },
2570
- exportJob: EMPTY_EXPORT_JOB
2571
- };
2572
- });
2573
- }, "setExportFormat"),
2574
- setExportMode: /* @__PURE__ */ __name((mode) => {
2575
- set((prev) => {
2576
- const allowedModes = prev.exportCapabilities?.modes ?? [];
2577
- if (allowedModes.length > 0 && !allowedModes.includes(mode)) {
2578
- setSessionStatusLine(`Export mode unavailable: ${mode}`);
2579
- return prev;
2580
- }
2581
- setSessionStatusLine(`Export mode set to ${mode}`);
2582
- return {
2583
- exportMode: mode
2584
- };
2585
- });
2586
- }, "setExportMode"),
2587
- setExportScopePath: /* @__PURE__ */ __name((scopePath) => {
2588
- setSessionStatusLine("Updated export scope path");
2589
- set({
2590
- exportScopePath: scopePath
2591
- });
2592
- }, "setExportScopePath"),
2593
- setExportDelivery: /* @__PURE__ */ __name((delivery) => {
2594
- setSessionStatusLine(`Export delivery set to ${delivery}`);
2595
- set({
2596
- exportDelivery: delivery
2597
- });
2598
- }, "setExportDelivery"),
2599
- previewExport: /* @__PURE__ */ __name(async () => {
2600
- await runExport("preview");
2601
- }, "previewExport"),
2602
- generateExport: /* @__PURE__ */ __name(async () => {
2603
- setSessionStatusLine("Confirm export validation to write files to disk");
2604
- set({
2605
- exportValidation: {
2606
- open: true
2607
- }
2608
- });
2609
- }, "generateExport"),
2610
- validateAndWriteExport: /* @__PURE__ */ __name(async () => {
2611
- const state = get();
2612
- const boot = getBootContext();
2613
- if (!boot) return;
2614
- if (state.exportInFlight) {
2615
- appendSessionLog("[warn] Export already in progress");
2616
- return;
2617
- }
2618
- const format = state.exportFormat;
2619
- set({
2620
- exportInFlight: true,
2621
- exportValidation: {
2622
- open: false
2623
- },
2624
- exportJob: {
2625
- action: "generate",
2626
- status: "running",
2627
- format
2628
- }
2629
- });
2630
- setSessionStatusLine("Validating export and writing files...");
2631
- const service2 = getService();
2632
- try {
2633
- const result = await service2.deliverExport(boot.projectId, format, "download", {
2634
- mode: state.exportMode,
2635
- scopePath: state.exportScopePath || void 0,
2636
- organizationId: boot.organizationId
2637
- });
2638
- set((prev) => ({
2639
- exportStatus: result.localStatus ?? prev.exportStatus,
2640
- exportJob: {
2641
- action: "generate",
2642
- status: "success",
2643
- format
2644
- }
2645
- }));
2646
- setSessionStatusLine(result.message);
2647
- appendSessionLog(`[export] ${result.message}`);
2648
- } catch (error) {
2649
- const message = error instanceof Error ? error.message : String(error);
2650
- set({
2651
- exportJob: {
2652
- action: "generate",
2653
- status: "error",
2654
- format,
2655
- error: message
2656
- }
2657
- });
2658
- setSessionStatusLine("Export validation/write failed");
2659
- appendSessionLog(`[error] Export validate/write failed: ${message}`);
2660
- refreshOnAuthenticationError(message);
2661
- } finally {
2662
- set({
2663
- exportInFlight: false
2664
- });
2665
- }
2666
- }, "validateAndWriteExport"),
2667
- cancelExportValidation: /* @__PURE__ */ __name(() => {
2668
- setSessionStatusLine("Export validation cancelled");
2669
- set({
2670
- exportValidation: {
2671
- open: false
2672
- }
2673
- });
2674
- }, "cancelExportValidation"),
2675
- statusExport: /* @__PURE__ */ __name(async () => {
2676
- await runExport("status");
2677
- }, "statusExport"),
2678
- commitExport: /* @__PURE__ */ __name(async () => {
2679
- await runExport("commit");
2680
- }, "commitExport"),
2681
- createPrExport: /* @__PURE__ */ __name(async () => {
2682
- await runExport("pr");
2683
- }, "createPrExport"),
2684
- copyExportPreview: /* @__PURE__ */ __name(() => {
2685
- const { exportPreview, exportJob } = get();
2686
- const hasGeneratedPreview = exportJob.status === "success" && (exportJob.action === "preview" || exportJob.action === "generate");
2687
- if (!exportPreview?.content || !hasGeneratedPreview) {
2688
- setSessionStatusLine("No generated preview to copy. Run p or g first.");
2689
- appendSessionLog("[warn] export copy requested before preview/generate completed");
2690
- return;
2691
- }
2692
- const copied = copyTextToClipboard(exportPreview.content);
2693
- if (copied.ok) {
2694
- setSessionStatusLine("Copied preview to clipboard");
2695
- appendSessionLog("[export] copied preview to clipboard");
2696
- return;
2697
- }
2698
- setSessionStatusLine("Clipboard copy failed");
2699
- appendSessionLog(`[error] clipboard copy failed: ${copied.error}`);
2700
- }, "copyExportPreview")
2701
- })));
2702
-
2703
- // src/store/use-bridge-store.ts
2704
- import { create as create5 } from "zustand";
2705
- import { subscribeWithSelector as subscribeWithSelector5 } from "zustand/middleware";
2706
- var useBridgeStore = create5()(subscribeWithSelector5((set, get) => ({
2707
- bridge: null,
2708
- localBridge: null,
2709
- bridgeLogs: [],
2710
- bridgeLogsSince: 0,
2711
- startedByTui: false,
2712
- setBridgeData: /* @__PURE__ */ __name((bridge, localBridge) => set({
2713
- bridge,
2714
- localBridge
2715
- }), "setBridgeData"),
2716
- setLocalBridge: /* @__PURE__ */ __name((localBridge) => set({
2717
- localBridge
2718
- }), "setLocalBridge"),
2719
- setBridgeLogs: /* @__PURE__ */ __name((logs) => {
2720
- if (logs.length === 0) return;
2721
- const lastTimestamp = logs[logs.length - 1].timestamp;
2722
- set((prev) => ({
2723
- bridgeLogs: [
2724
- ...prev.bridgeLogs,
2725
- ...logs
2726
- ].slice(-200),
2727
- bridgeLogsSince: lastTimestamp
2728
- }));
2729
- }, "setBridgeLogs"),
2730
- clearBridgeLogs: /* @__PURE__ */ __name(() => set({
2731
- bridgeLogs: []
2732
- }), "clearBridgeLogs"),
2733
- bridgeStart: /* @__PURE__ */ __name(() => {
2734
- const service2 = getService();
2735
- service2.startLocalBridgeDetached();
2736
- set({
2737
- startedByTui: true
2738
- });
2739
- appendSessionLog("[bridge] Started local bridge process (detached)");
2740
- setSessionStatusLine("Bridge start triggered (detached)");
2741
- }, "bridgeStart"),
2742
- bridgeStop: /* @__PURE__ */ __name(async () => {
2743
- const service2 = getService();
2744
- const { localBridge } = get();
2745
- await service2.stopLocalBridge(localBridge?.port);
2746
- appendSessionLog("[bridge] Stop signal sent");
2747
- setSessionStatusLine("Bridge stop signal sent");
2748
- }, "bridgeStop")
2749
- })));
2750
-
2751
- // src/store/store-effects.ts
2752
- function dispatchRefreshComplete(data) {
2753
- useProjectDataStore.getState().setProjectData(data.specs, data.decisions, data.workflow, data.navPolicy);
2754
- useExportStore.getState().setCapabilities(data.exportCapabilities);
2755
- useBridgeStore.getState().setBridgeData(data.bridge, data.localBridge);
2756
- }
2757
- __name(dispatchRefreshComplete, "dispatchRefreshComplete");
2758
- function dispatchClearProjectData() {
2759
- useProjectDataStore.getState().clearProjectData();
2760
- }
2761
- __name(dispatchClearProjectData, "dispatchClearProjectData");
2762
- function refreshOnAuthenticationError(message) {
2763
- if (!isAuthenticationError(message)) return;
2764
- const { appendLog, refresh } = useSessionStore.getState();
2765
- useSessionStore.setState({
2766
- statusLine: "Authentication required. Refreshing context..."
2767
- });
2768
- appendLog("[auth] action requires authentication, refreshing context");
2769
- void refresh();
2770
- }
2771
- __name(refreshOnAuthenticationError, "refreshOnAuthenticationError");
2772
- async function withSessionFeedback(opts) {
2773
- const { appendLog, refresh } = useSessionStore.getState();
2774
- useSessionStore.setState({
2775
- statusLine: opts.statusLine
2776
- });
2777
- try {
2778
- const result = await opts.action();
2779
- appendLog(opts.successLog);
2780
- if (opts.refresh !== false) {
2781
- await refresh();
2782
- }
2783
- return result;
2784
- } catch (error) {
2785
- const message = error instanceof Error ? error.message : String(error);
2786
- appendLog(`${opts.failureLog}: ${message}`);
2787
- useSessionStore.setState({
2788
- statusLine: opts.failureStatusLine
2789
- });
2790
- refreshOnAuthenticationError(message);
2791
- throw error;
2792
- }
2793
- }
2794
- __name(withSessionFeedback, "withSessionFeedback");
2795
- function getBootContext() {
2796
- return useSessionStore.getState().boot;
2797
- }
2798
- __name(getBootContext, "getBootContext");
2799
- function setSessionStatusLine(line) {
2800
- useSessionStore.setState({
2801
- statusLine: line
2802
- });
2803
- }
2804
- __name(setSessionStatusLine, "setSessionStatusLine");
2805
- function appendSessionLog(entry) {
2806
- useSessionStore.getState().appendLog(entry);
2807
- }
2808
- __name(appendSessionLog, "appendSessionLog");
2809
-
2810
- // src/store/use-session-store.ts
2811
- var onboardingInteractionResolver = null;
2812
- function requestOnboardingInteraction(request) {
2813
- return new Promise((resolve) => {
2814
- onboardingInteractionResolver = resolve;
2815
- useSessionStore.setState((prev) => ({
2816
- onboarding: prev.onboarding ? {
2817
- ...prev.onboarding,
2818
- interaction: request
2819
- } : prev.onboarding
2820
- }));
2821
- });
2822
- }
2823
- __name(requestOnboardingInteraction, "requestOnboardingInteraction");
2824
- function refreshOnAuthenticationError2(message) {
2825
- if (!isAuthenticationError(message)) return;
2826
- const { appendLog, refresh } = useSessionStore.getState();
2827
- useSessionStore.setState({
2828
- statusLine: "Authentication required. Refreshing context..."
2829
- });
2830
- appendLog("[auth] action requires authentication, refreshing context");
2831
- void refresh();
2832
- }
2833
- __name(refreshOnAuthenticationError2, "refreshOnAuthenticationError");
2834
- async function buildOnboardingState(mode) {
2835
- const service2 = getService();
2836
- const boot = useSessionStore.getState().boot;
2837
- const organizations = await service2.listOrganizations();
2838
- if (organizations.length === 0) {
2839
- return {
2840
- mode,
2841
- step: "create-organization",
2842
- attachCurrentFolder: mode === "initial-setup",
2843
- organizations: [],
2844
- projects: [],
2845
- availableAgents: [],
2846
- canCreateProject: false,
2847
- error: void 0
2848
- };
2849
- }
2850
- const preferredOrganizationId = boot?.organizationId;
2851
- const selectedOrganization = organizations.find((org) => org.id === preferredOrganizationId) ?? organizations[0];
2852
- const projects = await service2.listProjects(selectedOrganization.id);
2853
- return {
2854
- mode,
2855
- step: organizations.length === 1 ? "project" : "organization",
2856
- attachCurrentFolder: mode === "initial-setup",
2857
- organizations,
2858
- projects,
2859
- availableAgents: [],
2860
- canCreateProject: service2.canCreateProject(selectedOrganization),
2861
- selectedOrganizationId: selectedOrganization.id,
2862
- interaction: void 0,
2863
- error: void 0
2864
- };
2865
- }
2866
- __name(buildOnboardingState, "buildOnboardingState");
2867
- var useSessionStore = create6()(subscribeWithSelector6((set, get) => ({
2868
- boot: null,
2869
- auth: null,
2870
- onboarding: null,
2871
- loading: true,
2872
- error: null,
2873
- statusLine: "Bootstrapping...",
2874
- logs: [],
2875
- appendLog: /* @__PURE__ */ __name((entry) => {
2876
- const screen = useTuiUiStore.getState().screen;
2877
- const level = entry.startsWith("[error]") ? "error" : entry.startsWith("[warn]") ? "warn" : "info";
2878
- appendGlobalStructuredLog({
2879
- source: "tui.event-log",
2880
- level,
2881
- message: entry,
2882
- details: {
2883
- screen
2884
- }
2885
- });
2886
- set((prev) => ({
2887
- logs: [
2888
- entry,
2889
- ...prev.logs
2890
- ].slice(0, 40)
2891
- }));
2892
- }, "appendLog"),
2893
- setStatusLine: /* @__PURE__ */ __name((line) => set({
2894
- statusLine: line
2895
- }), "setStatusLine"),
2896
- setLoading: /* @__PURE__ */ __name((loading) => set({
2897
- loading
2898
- }), "setLoading"),
2899
- setError: /* @__PURE__ */ __name((error) => set({
2900
- error
2901
- }), "setError"),
2902
- authenticate: /* @__PURE__ */ __name(async () => {
2903
- const { appendLog } = get();
2904
- const service2 = getService();
2905
- set({
2906
- loading: false,
2907
- auth: {
2908
- status: "authenticating"
2909
- },
2910
- statusLine: "Starting browser login flow..."
2911
- });
2912
- appendLog("[auth] starting login flow");
2913
- const ok = await service2.authenticateViaCli((line) => {
2914
- appendLog(`[auth] ${line}`);
2915
- });
2916
- if (!ok) {
2917
- set({
2918
- auth: {
2919
- status: "auth_failed",
2920
- error: "Authentication failed. Check logs and try again."
2921
- },
2922
- statusLine: "Authentication failed"
2923
- });
2924
- appendLog("[auth] login flow failed");
2925
- return;
2926
- }
2927
- appendLog("[auth] login flow completed");
2928
- await get().refresh();
2929
- }, "authenticate"),
2930
- refresh: /* @__PURE__ */ __name(async (projectId) => {
2931
- const service2 = getService();
2932
- set((prev) => ({
2933
- loading: prev.boot ? false : true,
2934
- statusLine: "Loading context..."
2935
- }));
2936
- try {
2937
- const token = await service2.checkAuthentication();
2938
- if (!token) {
2939
- set({
2940
- loading: false,
2941
- error: null,
2942
- auth: {
2943
- status: "unauthenticated",
2944
- error: "No valid credentials. Please run `spekn auth login` to authenticate."
2945
- },
2946
- statusLine: "Authentication required"
2947
- });
2948
- return;
2949
- }
2950
- set({
2951
- auth: {
2952
- status: "authenticated",
2953
- userEmail: service2.extractUserEmail(token),
2954
- tokenExpiresAt: service2.extractTokenExpiry(token)
2955
- }
2956
- });
2957
- if (!projectId && !service2.hasLocalProjectContext()) {
2958
- const onboarding = await buildOnboardingState("initial-setup");
2959
- set({
2960
- loading: false,
2961
- error: null,
2962
- onboarding,
2963
- statusLine: "Project setup required"
2964
- });
2965
- return;
2966
- }
2967
- let bootstrapResult;
2968
- try {
2969
- bootstrapResult = await service2.bootstrap(projectId);
2970
- } catch (bootstrapError) {
2971
- if (bootstrapError instanceof Error && bootstrapError.message === "ONBOARDING_REQUIRED") {
2972
- const onboarding = await buildOnboardingState("initial-setup");
2973
- set({
2974
- loading: false,
2975
- error: null,
2976
- onboarding,
2977
- statusLine: "Project setup required"
2978
- });
2979
- return;
2980
- }
2981
- throw bootstrapError;
2982
- }
2983
- const { boot, client: client2 } = bootstrapResult;
2984
- setClient(client2);
2985
- const [specs, decisions, workflow, bridge, localBridge, exportCapabilities] = await Promise.all([
2986
- service2.loadSpecs(client2, boot.projectId),
2987
- service2.loadDecisions(client2, boot.projectId),
2988
- service2.loadWorkflowSummary(client2, boot.projectId),
2989
- service2.loadBridgeSummary(client2),
2990
- service2.loadLocalBridgeSummary(),
2991
- service2.discoverExportCapabilities(boot.projectId, boot.organizationId).catch(() => null)
2992
- ]);
2993
- const capabilityContext = {
2994
- plan: boot.plan,
2995
- role: boot.role,
2996
- workflowPhase: workflow.currentPhase,
2997
- permissions: boot.permissions
2998
- };
2999
- const navPolicy = resolveNavPolicy(capabilityContext);
3000
- dispatchRefreshComplete({
3001
- specs,
3002
- decisions,
3003
- workflow,
3004
- navPolicy,
3005
- exportCapabilities,
3006
- bridge,
3007
- localBridge
3008
- });
3009
- set({
3010
- boot,
3011
- loading: false,
3012
- error: null,
3013
- onboarding: null,
3014
- statusLine: "Ready"
3015
- });
3016
- } catch (error) {
3017
- const message = error instanceof Error ? error.message : String(error);
3018
- let authStatus = null;
3019
- if (message.includes("credentials") || message.includes("auth") || message.includes("token")) {
3020
- authStatus = {
3021
- status: "auth_failed",
3022
- error: message
3023
- };
3024
- }
3025
- set((prev) => ({
3026
- loading: false,
3027
- error: message,
3028
- auth: authStatus || prev.auth,
3029
- statusLine: "Error"
3030
- }));
3031
- get().appendLog(`[error] ${message}`);
3032
- }
3033
- }, "refresh"),
3034
- switchContext: /* @__PURE__ */ __name(async () => {
3035
- const { appendLog } = get();
3036
- set({
3037
- loading: true,
3038
- error: null,
3039
- statusLine: "Loading organizations..."
3040
- });
3041
- try {
3042
- const onboarding = await buildOnboardingState("switch-context");
3043
- set({
3044
- loading: false,
3045
- onboarding,
3046
- statusLine: "Switch organization/project"
3047
- });
3048
- appendLog("[context] switch mode opened");
3049
- } catch (error) {
3050
- const message = error instanceof Error ? error.message : String(error);
3051
- set({
3052
- loading: false,
3053
- statusLine: "Context switch failed",
3054
- error: message
3055
- });
3056
- appendLog(`[error] context switch failed: ${message}`);
3057
- refreshOnAuthenticationError2(message);
3058
- }
3059
- }, "switchContext"),
3060
- detachRepoContext: /* @__PURE__ */ __name(async () => {
3061
- const { boot, appendLog, refresh } = get();
3062
- const service2 = getService();
3063
- const result = await service2.detachContextViaCli(boot?.projectId, process.cwd());
3064
- if (!result.success) {
3065
- appendLog(`[error] Failed to detach context: ${result.output}`);
3066
- set({
3067
- statusLine: "Context detach failed"
3068
- });
3069
- return;
3070
- }
3071
- if (result.output) {
3072
- appendLog(`[context] ${result.output}`);
3073
- }
3074
- appendLog("[context] Detached repository from local project context");
3075
- set({
3076
- boot: null,
3077
- statusLine: "Repository detached. Select a project to attach."
3078
- });
3079
- dispatchClearProjectData();
3080
- await refresh();
3081
- }, "detachRepoContext"),
3082
- syncRepository: /* @__PURE__ */ __name(async (options) => {
3083
- const { boot, appendLog, refresh } = get();
3084
- const service2 = getService();
3085
- if (!boot) {
3086
- appendLog("[error] repository sync unavailable: no active project context");
3087
- set({
3088
- statusLine: "Repository sync unavailable"
3089
- });
3090
- return false;
3091
- }
3092
- appendLog("[repo] running sync (metadata + drift analysis)");
3093
- set({
3094
- statusLine: "Syncing repository..."
3095
- });
3096
- const result = await service2.syncRepositoryViaCli(boot.organizationId, boot.projectId, boot.repoPath, {
3097
- analyze: options?.analyze ?? true,
3098
- importToProject: options?.importToProject,
3099
- maxFiles: options?.maxFiles,
3100
- analysisEngine: options?.analysisEngine,
3101
- agent: options?.agent,
3102
- requestInteraction: options?.requestInteraction,
3103
- onProgress: /* @__PURE__ */ __name((line) => {
3104
- appendLog(`[repo] ${line}`);
3105
- options?.onProgress?.(line);
3106
- }, "onProgress"),
3107
- onActivity: /* @__PURE__ */ __name((event) => {
3108
- if (event.event === "agent_chunk" && event.text) {
3109
- appendLog(`[agent] ${event.text}`);
3110
- options?.onProgress?.(event.text);
3111
- }
3112
- options?.onActivity?.(event);
3113
- }, "onActivity")
3114
- });
3115
- if (!result.success) {
3116
- appendLog(`[error] repository sync failed (exit ${result.exitCode})`);
3117
- set({
3118
- statusLine: "Repository sync failed"
3119
- });
3120
- refreshOnAuthenticationError2(result.output);
3121
- return false;
3122
- }
3123
- appendLog("[repo] sync completed");
3124
- set({
3125
- statusLine: "Repository sync completed"
3126
- });
3127
- await refresh();
3128
- return true;
3129
- }, "syncRepository"),
3130
- // Onboarding actions
3131
- selectOnboardingOrganization: /* @__PURE__ */ __name(async (index) => {
3132
- const { onboarding, appendLog } = get();
3133
- const service2 = getService();
3134
- if (!onboarding) return;
3135
- if (index < 0 || index >= onboarding.organizations.length) {
3136
- set((prev) => ({
3137
- onboarding: prev.onboarding ? {
3138
- ...prev.onboarding,
3139
- error: `Invalid organization index: ${index + 1}`
3140
- } : prev.onboarding
3141
- }));
3142
- return;
3143
- }
3144
- const selectedOrganization = onboarding.organizations[index];
3145
- set((prev) => ({
3146
- loading: true,
3147
- statusLine: "Loading projects...",
3148
- onboarding: prev.onboarding ? {
3149
- ...prev.onboarding,
3150
- selectedOrganizationId: selectedOrganization.id,
3151
- error: void 0
3152
- } : prev.onboarding
3153
- }));
3154
- try {
3155
- const projects = await service2.listProjects(selectedOrganization.id);
3156
- set((prev) => ({
3157
- loading: false,
3158
- statusLine: "Select a project",
3159
- onboarding: prev.onboarding ? {
3160
- ...prev.onboarding,
3161
- step: "project",
3162
- attachCurrentFolder: prev.onboarding.attachCurrentFolder,
3163
- projects,
3164
- availableAgents: prev.onboarding?.availableAgents ?? [],
3165
- canCreateProject: service2.canCreateProject(selectedOrganization),
3166
- selectedOrganizationId: selectedOrganization.id,
3167
- interaction: void 0,
3168
- error: projects.length === 0 ? "No projects found in selected organization." : void 0
3169
- } : prev.onboarding
3170
- }));
3171
- } catch (error) {
3172
- const message = error instanceof Error ? error.message : String(error);
3173
- set((prev) => ({
3174
- loading: false,
3175
- statusLine: "Setup error",
3176
- onboarding: prev.onboarding ? {
3177
- ...prev.onboarding,
3178
- error: message
3179
- } : prev.onboarding
3180
- }));
3181
- }
3182
- }, "selectOnboardingOrganization"),
3183
- registerOnboardingProject: /* @__PURE__ */ __name(async (index) => {
3184
- const { onboarding, appendLog, refresh } = get();
3185
- const service2 = getService();
3186
- if (!onboarding || !onboarding.selectedOrganizationId) return;
3187
- if (index < 0 || index >= onboarding.projects.length) {
3188
- set((prev) => ({
3189
- onboarding: prev.onboarding ? {
3190
- ...prev.onboarding,
3191
- error: `Invalid project index: ${index + 1}`
3192
- } : prev.onboarding
3193
- }));
3194
- return;
3195
- }
3196
- const selectedProject = onboarding.projects[index];
3197
- if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
3198
- set((prev) => ({
3199
- loading: true,
3200
- statusLine: "Switching context...",
3201
- onboarding: prev.onboarding ? {
3202
- ...prev.onboarding,
3203
- error: void 0
3204
- } : prev.onboarding
3205
- }));
3206
- try {
3207
- service2.persistContext(onboarding.selectedOrganizationId, selectedProject.id);
3208
- appendLog(`[context] switched to ${selectedProject.name}`);
3209
- await refresh();
3210
- } catch (error) {
3211
- const message = error instanceof Error ? error.message : String(error);
3212
- set((prev) => ({
3213
- loading: false,
3214
- statusLine: "Context switch failed",
3215
- onboarding: prev.onboarding ? {
3216
- ...prev.onboarding,
3217
- step: "project",
3218
- error: message
3219
- } : prev.onboarding
3220
- }));
3221
- }
3222
- return;
3223
- }
3224
- set((prev) => ({
3225
- loading: true,
3226
- statusLine: "Linking repository...",
3227
- onboarding: prev.onboarding ? {
3228
- ...prev.onboarding,
3229
- error: void 0
3230
- } : prev.onboarding
3231
- }));
3232
- try {
3233
- persistProjectContext(process.cwd(), {
3234
- projectId: selectedProject.id,
3235
- organizationId: onboarding.selectedOrganizationId
3236
- });
3237
- appendLog(`[context] linked to ${selectedProject.name}`);
3238
- await refresh();
3239
- } catch (error) {
3240
- const message = error instanceof Error ? error.message : String(error);
3241
- set((prev) => ({
3242
- loading: false,
3243
- statusLine: "Setup error",
3244
- onboarding: prev.onboarding ? {
3245
- ...prev.onboarding,
3246
- step: "project",
3247
- error: message
3248
- } : prev.onboarding
3249
- }));
3250
- }
3251
- }, "registerOnboardingProject"),
3252
- createOnboardingProject: /* @__PURE__ */ __name(async (name) => {
3253
- const { onboarding, appendLog, refresh } = get();
3254
- const service2 = getService();
3255
- if (!onboarding || !onboarding.selectedOrganizationId) return;
3256
- const trimmed = name.trim();
3257
- if (!onboarding.canCreateProject) {
3258
- set((prev) => ({
3259
- onboarding: prev.onboarding ? {
3260
- ...prev.onboarding,
3261
- error: "You are not authorized to create projects in this organization."
3262
- } : prev.onboarding
3263
- }));
3264
- return;
3265
- }
3266
- if (trimmed.length < 2) {
3267
- set((prev) => ({
3268
- onboarding: prev.onboarding ? {
3269
- ...prev.onboarding,
3270
- error: "Project name must be at least 2 characters."
3271
- } : prev.onboarding
3272
- }));
3273
- return;
3274
- }
3275
- set((prev) => ({
3276
- loading: true,
3277
- statusLine: "Creating project...",
3278
- onboarding: prev.onboarding ? {
3279
- ...prev.onboarding,
3280
- error: void 0
3281
- } : prev.onboarding
3282
- }));
3283
- try {
3284
- const created = await service2.createProject(onboarding.selectedOrganizationId, trimmed);
3285
- appendLog(`[setup] Created project "${created.name}"`);
3286
- if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
3287
- service2.persistContext(onboarding.selectedOrganizationId, created.id);
3288
- appendLog(`[context] switched to ${created.name}`);
3289
- await refresh();
3290
- return;
3291
- }
3292
- set((prev) => ({
3293
- loading: true,
3294
- statusLine: "Registering repository...",
3295
- onboarding: prev.onboarding ? {
3296
- ...prev.onboarding,
3297
- step: "registering",
3298
- availableAgents: prev.onboarding?.availableAgents ?? [],
3299
- selectedProjectId: created.id,
3300
- runLines: [],
3301
- runStatus: "running",
3302
- interaction: void 0,
3303
- error: void 0
3304
- } : prev.onboarding
3305
- }));
3306
- await attachRepositoryFromOnboardingZustand({
3307
- organizationId: onboarding.selectedOrganizationId,
3308
- projectId: created.id
3309
- });
3310
- await refresh();
3311
- } catch (error) {
3312
- const message = error instanceof Error ? error.message : String(error);
3313
- set((prev) => ({
3314
- loading: false,
3315
- statusLine: "Setup error",
3316
- onboarding: prev.onboarding ? {
3317
- ...prev.onboarding,
3318
- error: message
3319
- } : prev.onboarding
3320
- }));
3321
- }
3322
- }, "createOnboardingProject"),
3323
- resolveOnboardingInteraction: /* @__PURE__ */ __name((value) => {
3324
- const resolver = onboardingInteractionResolver;
3325
- onboardingInteractionResolver = null;
3326
- set((prev) => ({
3327
- onboarding: prev.onboarding ? {
3328
- ...prev.onboarding,
3329
- interaction: void 0
3330
- } : prev.onboarding
3331
- }));
3332
- if (resolver) resolver(value);
3333
- }, "resolveOnboardingInteraction"),
3334
- setOnboardingAttachCurrentFolder: /* @__PURE__ */ __name((attach) => {
3335
- set((prev) => ({
3336
- onboarding: prev.onboarding ? prev.onboarding.attachCurrentFolder === attach ? prev.onboarding : {
3337
- ...prev.onboarding,
3338
- attachCurrentFolder: attach
3339
- } : prev.onboarding
3340
- }));
3341
- }, "setOnboardingAttachCurrentFolder")
3342
- })));
3343
- async function attachRepositoryFromOnboardingZustand(input) {
3344
- const service2 = getService();
3345
- const { appendLog } = useSessionStore.getState();
3346
- const result = await service2.attachOrSyncCurrentRepository(input.organizationId, input.projectId, (line) => {
3347
- appendLog(`[setup] ${line}`);
3348
- useSessionStore.setState((prev) => ({
3349
- statusLine: line.slice(0, 100),
3350
- onboarding: prev.onboarding ? {
3351
- ...prev.onboarding,
3352
- runLines: [
3353
- ...prev.onboarding.runLines ?? [],
3354
- line
3355
- ].slice(-400)
3356
- } : prev.onboarding
3357
- }));
3358
- }, void 0, requestOnboardingInteraction, (event) => {
3359
- const { upsertToolCall, setActiveThought } = useOnboardingWindow.getState();
3360
- if (event.event === "tool_call" || event.event === "tool_call_update") {
3361
- upsertToolCall(event);
3362
- } else if (event.event === "agent_thought") {
3363
- setActiveThought(event.text);
3364
- } else if (event.event === "agent_chunk" && event.text) {
3365
- useSessionStore.setState((prev) => ({
3366
- onboarding: prev.onboarding ? {
3367
- ...prev.onboarding,
3368
- runLines: [
3369
- ...prev.onboarding.runLines ?? [],
3370
- event.text
3371
- ].slice(-400)
3372
- } : prev.onboarding
3373
- }));
3374
- }
3375
- });
3376
- useSessionStore.setState((prev) => ({
3377
- onboarding: prev.onboarding ? {
3378
- ...prev.onboarding,
3379
- runStatus: result.warning ? "error" : "success"
3380
- } : prev.onboarding
3381
- }));
3382
- logOnboardingAttachResult(appendLog, result);
3383
- }
3384
- __name(attachRepositoryFromOnboardingZustand, "attachRepositoryFromOnboardingZustand");
3385
-
3386
- export {
3387
- __name,
3388
- appendGlobalStructuredLog,
3389
- initServiceBridge,
3390
- getService,
3391
- getClient,
3392
- setInitialScreen,
3393
- useTuiUiStore,
3394
- resolveNavPolicy,
3395
- useOnboardingWindow,
3396
- buildOnboardingState,
3397
- useSessionStore,
3398
- useProjectDataStore,
3399
- useExportStore,
3400
- useBridgeStore
3401
- };