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