@spekn/cli 1.0.0 → 1.0.2

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