@galaxy-stack/blackhole-cli 3.0.21 → 3.0.22

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.
@@ -0,0 +1,288 @@
1
+ //#region gbh journey host: routes, agent tools, chat command
2
+ /**
3
+ * Host side of the Galaxy delivery journey: the browser route the panel drives,
4
+ * the agent tools that edit and run the same blueprint, and the human /journey
5
+ * command. All three share one engine, one validator, and one revision rule, so
6
+ * a human edit and an agent edit are the same kind of write.
7
+ */
8
+ import { join } from "node:path";
9
+ import { blueprintPathFor, readBlueprint, validateBlueprint, writeBlueprint } from "./journey-store.js";
10
+ import { advanceRun, cancelRun, createRun, decideRun, listRuns, readRun, summarizeRun, writeRun } from "./journey-run.js";
11
+ import { resolveHome } from "./session-store.js";
12
+
13
+ /** The tool result text block. */
14
+ function toolText(value) {
15
+ return [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }];
16
+ }
17
+
18
+ /** One run id that stays unique across restarts. */
19
+ function newRunId() {
20
+ return "run-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
21
+ }
22
+
23
+ /** In-process workspace root of an agent session; never taken from a request body. */
24
+ export function rootOfSession(session) {
25
+ const cwd = session?.header?.cwd;
26
+ return typeof cwd === "string" && cwd.length > 0 ? cwd : undefined;
27
+ }
28
+
29
+ /** Load the blueprint a run works against, or an error body. */
30
+ function loadBlueprint(sessionWorkspaceRoot, ctx, sessionId) {
31
+ return sessionWorkspaceRoot(ctx, sessionId).then(root => {
32
+ if (root === undefined) {
33
+ return { error: { status: 409, body: { ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." } } };
34
+ }
35
+ const blueprint = readBlueprint(root);
36
+ if (blueprint.document === undefined) {
37
+ return { error: { status: 422, body: { ok: false, code: "journey/unparsable", message: "journey.json is not valid JSON." } } };
38
+ }
39
+ return { root: root, blueprint: blueprint };
40
+ });
41
+ }
42
+
43
+ /** Start a run for the blueprint as it exists right now. */
44
+ export async function startJourneyRun(host, sessionId, feature) {
45
+ const home = resolveHome();
46
+ const context = await loadBlueprint(host.sessionWorkspaceRoot, host.ctx, sessionId);
47
+ if (context.error !== undefined) return context.error;
48
+ const document = context.blueprint.document;
49
+ const issues = validateBlueprint(document);
50
+ if (issues.length > 0) return { status: 422, body: { ok: false, code: "journey/invalid", issues: issues } };
51
+ const run = createRun({
52
+ runId: newRunId(),
53
+ sessionId: sessionId,
54
+ blueprintPath: context.blueprint.path,
55
+ workspaceRoot: context.root,
56
+ document: document,
57
+ feature: typeof feature === "string" && feature.length > 0 ? feature : undefined,
58
+ });
59
+ const advanced = await advanceRun(run, document, { cwd: context.root });
60
+ writeRun(home, advanced.run);
61
+ return { status: 200, body: { ok: true, run: summarizeRun(advanced.run), executed: advanced.executed } };
62
+ }
63
+
64
+ /** Advance, decide, cancel, list, or read a run. */
65
+ export async function continueJourneyRun(host, sessionId, payload) {
66
+ const home = resolveHome();
67
+ const op = typeof payload?.op === "string" ? payload.op : "advance";
68
+ if (op === "list") {
69
+ return { status: 200, body: { ok: true, runs: listRuns(home, sessionId).map(run => summarizeRun(run)) } };
70
+ }
71
+ const runId = typeof payload?.runId === "string" ? payload.runId : "";
72
+ if (runId.length === 0) {
73
+ return { status: 400, body: { ok: false, code: "invalid-request", message: "runId is required." } };
74
+ }
75
+ const run = readRun(home, runId);
76
+ if (run === undefined || run.sessionId !== sessionId) {
77
+ return { status: 404, body: { ok: false, code: "journey/unknown-run", message: "Run " + runId + " is not part of this session." } };
78
+ }
79
+ if (op === "status") return { status: 200, body: { ok: true, run: summarizeRun(run) } };
80
+ if (op === "cancel") {
81
+ cancelRun(run, { text: typeof payload?.note === "string" ? payload.note : undefined });
82
+ writeRun(home, run);
83
+ return { status: 200, body: { ok: true, run: summarizeRun(run) } };
84
+ }
85
+ if (op === "decide") {
86
+ const decision = typeof payload?.decision === "string" ? payload.decision : "";
87
+ const decided = decideRun(run, String(payload?.nodeId ?? ""), decision, {
88
+ text: typeof payload?.note === "string" ? payload.note : undefined,
89
+ by: payload?.updatedBy === "agent" ? "agent" : "human",
90
+ });
91
+ if (decided.ok !== true) return { status: 409, body: { ok: false, code: decided.code, message: decided.message } };
92
+ }
93
+ const context = await loadBlueprint(host.sessionWorkspaceRoot, host.ctx, sessionId);
94
+ if (context.error !== undefined) return context.error;
95
+ /* decideRun mutated the in-memory record; the file write below persists it. */
96
+ const advanced = await advanceRun(run, context.blueprint.document, { cwd: context.root });
97
+ writeRun(home, advanced.run);
98
+ return { status: 200, body: { ok: true, run: summarizeRun(advanced.run), executed: advanced.executed } };
99
+ }
100
+
101
+ /** Register the run route the panel drives. */
102
+ export function registerJourneyRunRoutes(host, connectionCtx) {
103
+ const ctx = host.ctx;
104
+ connectionCtx.connection.fetch.register({
105
+ path: "/api/galaxy/journey.run",
106
+ methods: ["GET", "HEAD", "POST"],
107
+ requestBody: "buffered",
108
+ fetch: async request => {
109
+ if (request.method !== "POST") {
110
+ const url = new URL(request.url);
111
+ const sessionId = url.searchParams.get("sessionId") ?? "";
112
+ const runId = url.searchParams.get("runId");
113
+ const home = resolveHome();
114
+ const body = runId === null
115
+ ? { ok: true, runs: listRuns(home, sessionId).map(run => summarizeRun(run)) }
116
+ : (() => {
117
+ const run = readRun(home, runId);
118
+ if (run === undefined || run.sessionId !== sessionId) {
119
+ return { ok: false, code: "journey/unknown-run", message: "Run " + runId + " is not part of this session." };
120
+ }
121
+ return { ok: true, run: summarizeRun(run) };
122
+ })();
123
+ const response = host.jsonResponse(body, body.ok === true ? 200 : 404);
124
+ if (request.method === "GET") return response;
125
+ await response.body?.cancel();
126
+ return new Response(null, { status: response.status, headers: response.headers });
127
+ }
128
+ let payload;
129
+ try {
130
+ payload = await request.json();
131
+ } catch {
132
+ return host.jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
133
+ }
134
+ const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
135
+ const op = typeof payload?.op === "string" ? payload.op : "advance";
136
+ const result = op === "start" ? await startJourneyRun(host, sessionId, payload?.feature) : await continueJourneyRun(host, sessionId, payload);
137
+ if (result.status === 200 && result.body.run !== undefined) {
138
+ host.appendJourneyAudit({
139
+ at: new Date().toISOString(),
140
+ sessionId: sessionId,
141
+ runId: result.body.run.id,
142
+ event: "run/" + op,
143
+ by: payload?.updatedBy === "agent" ? "agent" : "human",
144
+ });
145
+ }
146
+ return host.jsonResponse(result.body, result.status);
147
+ },
148
+ });
149
+ }
150
+
151
+ /** Agent-facing journey tools: read, write under CAS, and drive the run. */
152
+ function journeyToolDefinitions(host) {
153
+ const objectSchema = (properties, required) => ({ type: "object", additionalProperties: false, properties: properties, required: required });
154
+ const textOutput = { schema: { type: "object", additionalProperties: true }, render: (args, value) => toolText(value) };
155
+ const workspaceRootOf = async sessionId => host.sessionWorkspaceRoot(host.ctx, sessionId);
156
+ return [
157
+ {
158
+ name: "journey_get",
159
+ description: "Read the workspace delivery-journey blueprint (journey.json): nodes, edges, revision, validation issues, and missingDescriptions — the nodes that still lack the description the run hands you for their step. Read it before journey_set so the revision you send is current.",
160
+ parameters: objectSchema({ sessionId: { type: "string", description: "Session whose workspace holds the blueprint." } }, ["sessionId"]),
161
+ output: textOutput,
162
+ execute: async args => {
163
+ const root = await workspaceRootOf(String(args.sessionId ?? ""));
164
+ if (root === undefined) return { ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." };
165
+ const blueprint = readBlueprint(root);
166
+ const nodes = Array.isArray(blueprint.document?.nodes) ? blueprint.document.nodes : [];
167
+ return {
168
+ ok: blueprint.parseError === undefined,
169
+ path: blueprint.path,
170
+ exists: blueprint.exists,
171
+ revision: typeof blueprint.document?.revision === "number" ? blueprint.document.revision : 0,
172
+ document: blueprint.document,
173
+ issues: blueprint.document === undefined ? [] : validateBlueprint(blueprint.document),
174
+ /* A description is how the author tells the agent what a step means; naming the
175
+ gaps lets the agent fill them with journey_set instead of guessing. */
176
+ missingDescriptions: nodes
177
+ .filter(node => typeof node?.description !== "string" || node.description.trim().length === 0)
178
+ .map(node => node.id),
179
+ };
180
+ },
181
+ },
182
+ {
183
+ name: "journey_set",
184
+ description: "Replace the workspace journey blueprint after validating it. Send the revision returned by journey_get as expectedRevision; on a race the call fails with journey/conflict plus the current document instead of overwriting it.",
185
+ parameters: objectSchema({
186
+ sessionId: { type: "string", description: "Session whose workspace holds the blueprint." },
187
+ document: { type: "object", description: "Full blueprint document with nodes[] and edges[]." },
188
+ expectedRevision: { type: "number", description: "Revision last read with journey_get." },
189
+ }, ["sessionId", "document", "expectedRevision"]),
190
+ output: textOutput,
191
+ execute: async args => {
192
+ const root = await workspaceRootOf(String(args.sessionId ?? ""));
193
+ if (root === undefined) return { ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." };
194
+ const result = writeBlueprint(root, args.document, { expectedRevision: Number(args.expectedRevision ?? 0), updatedBy: "agent" });
195
+ if (result.ok === true) {
196
+ host.appendJourneyAudit({ at: new Date().toISOString(), sessionId: String(args.sessionId ?? ""), path: result.path, revision: result.revision, hash: result.hash, updatedBy: "agent" });
197
+ }
198
+ return result;
199
+ },
200
+ },
201
+ {
202
+ name: "journey_run",
203
+ description: "Drive the delivery run of this workspace: op=start begins a run for a feature, op=advance executes the next runnable nodes, op=status and op=list read progress, op=decide approves, rejects, or retries a waiting node, op=cancel stops the run. Command actions execute in the workspace root. Every node row reports the kind, label, and description frozen from the blueprint, so read them before deciding a step.",
204
+ parameters: objectSchema({
205
+ sessionId: { type: "string", description: "Session whose workspace holds the blueprint." },
206
+ op: { type: "string", description: "start | advance | status | list | decide | cancel" },
207
+ runId: { type: "string", description: "Run to act on; required for every op except start and list." },
208
+ feature: { type: "string", description: "Feature label for op=start." },
209
+ nodeId: { type: "string", description: "Node to decide, for op=decide." },
210
+ decision: { type: "string", description: "approve | reject | retry, for op=decide." },
211
+ note: { type: "string", description: "Free-text note recorded with the decision." },
212
+ }, ["sessionId", "op"]),
213
+ output: textOutput,
214
+ execute: async args => {
215
+ const sessionId = String(args.sessionId ?? "");
216
+ const op = String(args.op ?? "");
217
+ const payload = {
218
+ op: op,
219
+ runId: typeof args.runId === "string" ? args.runId : "",
220
+ nodeId: typeof args.nodeId === "string" ? args.nodeId : "",
221
+ decision: typeof args.decision === "string" ? args.decision : "",
222
+ note: typeof args.note === "string" ? args.note : "",
223
+ updatedBy: "agent",
224
+ };
225
+ const result = op === "start"
226
+ ? await startJourneyRun(host, sessionId, typeof args.feature === "string" ? args.feature : undefined)
227
+ : await continueJourneyRun(host, sessionId, payload);
228
+ return result.body;
229
+ },
230
+ },
231
+ ];
232
+ }
233
+
234
+ /** Register the agent tools once the tool registry is available. */
235
+ export function registerJourneyTools(host) {
236
+ host.ctx.inject(["tools"], scope => {
237
+ for (const definition of journeyToolDefinitions(host)) {
238
+ try {
239
+ scope.tools.register(definition);
240
+ } catch (error) {
241
+ console.warn("gbh: journey tool " + definition.name + " was not registered: " + (error instanceof Error ? error.message : String(error)));
242
+ }
243
+ }
244
+ });
245
+ }
246
+
247
+ /** Register the human /journey command: print the blueprint and run state in chat. */
248
+ export function registerJourneyCommand(host) {
249
+ host.ctx.inject(["commands"], scope => {
250
+ scope.commands.register({
251
+ name: "journey",
252
+ description: "show the delivery journey blueprint and the current run",
253
+ input: { hint: "[status]" },
254
+ recordInput: false,
255
+ handler: async invocation => {
256
+ const session = invocation?.agent?.session;
257
+ const root = rootOfSession(session);
258
+ if (root === undefined) return { kind: "error", text: "Phiên này chưa có workspace." };
259
+ const blueprint = readBlueprint(root);
260
+ const issues = blueprint.document === undefined ? [] : validateBlueprint(blueprint.document);
261
+ const runs = listRuns(resolveHome(), session.id);
262
+ const active = runs.find(run => run.status !== "completed" && run.status !== "cancelled");
263
+ const lines = [
264
+ "Hành trình: " + blueprint.path + " (rev " + String(blueprint.document?.revision ?? 0) + (blueprint.exists ? "" : ", chưa ghi ra file") + ")",
265
+ "Node: " + String((blueprint.document?.nodes ?? []).length) + " · Edge: " + String((blueprint.document?.edges ?? []).length) + (issues.length > 0 ? " · " + String(issues.length) + " lỗi validate" : ""),
266
+ ];
267
+ if (active !== undefined) {
268
+ const summary = summarizeRun(active);
269
+ lines.push("Run " + summary.id + " (" + summary.status + ") — " + Object.entries(summary.counts).map(entry => entry[0] + " " + String(entry[1])).join(", "));
270
+ for (const node of summary.nodes.filter(item => item.state === "awaiting_approval" || item.state === "blocked")) {
271
+ lines.push(" • " + node.nodeId + ": " + node.state + " — " + String(node.last?.note ?? ""));
272
+ }
273
+ } else {
274
+ lines.push("Chưa có run nào đang chạy. Mở tab Hành trình để chạy.");
275
+ }
276
+ return { kind: "success", text: lines.join("\n") };
277
+ },
278
+ });
279
+ });
280
+ }
281
+
282
+ /** Wire every journey surface a host plugin needs. */
283
+ export function registerJourneyHost(host) {
284
+ host.ctx.inject(["connection"], connectionCtx => registerJourneyRunRoutes(host, connectionCtx));
285
+ registerJourneyTools(host);
286
+ registerJourneyCommand(host);
287
+ }
288
+ //#endregion
@@ -0,0 +1,70 @@
1
+ /** Types for the gbh journey run engine (see journey-run.js). */
2
+
3
+ export interface JourneyRunNodeState {
4
+ state: string;
5
+ attempts: number;
6
+ /** Node kind, label, and description frozen from the blueprint the run started from. */
7
+ kind?: string;
8
+ label?: string;
9
+ description?: string;
10
+ evidence: Record<string, unknown>[];
11
+ }
12
+
13
+ export interface JourneyRun {
14
+ id: string;
15
+ sessionId: string;
16
+ blueprintPath: string;
17
+ blueprintRevision: number;
18
+ workspaceRoot: string;
19
+ feature: string;
20
+ status: string;
21
+ createdAt: string;
22
+ updatedAt: string;
23
+ nodes: Record<string, JourneyRunNodeState>;
24
+ log: Record<string, unknown>[];
25
+ }
26
+
27
+ export declare const JOURNEY_RUN_STATES: readonly string[];
28
+ export declare const JOURNEY_RUN_STATUSES: readonly string[];
29
+ export declare function runsDirectory(home: string): string;
30
+ export declare function runPath(home: string, runId: string): string;
31
+ export declare function edgeIsActive(edge: { when?: string }, sourceState: string): boolean;
32
+ export declare function eligibleNodes(document: unknown, run: JourneyRun): Record<string, unknown>[];
33
+ export declare function runCommand(
34
+ command: string,
35
+ options?: { cwd?: string; timeoutMs?: number; signal?: AbortSignal; env?: Record<string, string> },
36
+ ): Promise<{ exitCode: number | null; stdout: string; stderr: string; error?: string }>;
37
+ export declare function createRun(input: {
38
+ runId: string;
39
+ sessionId: string;
40
+ blueprintPath: string;
41
+ workspaceRoot: string;
42
+ document: { nodes?: Record<string, unknown>[]; revision?: number };
43
+ feature?: string;
44
+ now?: Date;
45
+ }): JourneyRun;
46
+ export declare function writeRun(home: string, run: JourneyRun): string;
47
+ export declare function readRun(home: string, runId: string): JourneyRun | undefined;
48
+ export declare function listRuns(home: string, sessionId?: string): JourneyRun[];
49
+ export declare function refreshRunStatus(run: JourneyRun): string;
50
+ export declare function advanceRun(
51
+ run: JourneyRun,
52
+ document: unknown,
53
+ options?: { cwd?: string; now?: Date; signal?: AbortSignal },
54
+ ): Promise<{ run: JourneyRun; executed: { nodeId: string; status: string }[] }>;
55
+ export declare function decideRun(
56
+ run: JourneyRun,
57
+ nodeId: string,
58
+ decision: "approve" | "reject" | "retry",
59
+ note?: { text?: string; by?: string },
60
+ now?: Date,
61
+ ): { ok: true; run: JourneyRun } | { ok: false; code: string; message: string };
62
+ export declare function cancelRun(run: JourneyRun, note?: { text?: string }, now?: Date): JourneyRun;
63
+ export declare function summarizeRun(run: JourneyRun): {
64
+ id: string;
65
+ feature: string;
66
+ status: string;
67
+ blueprintRevision: number;
68
+ counts: Record<string, number>;
69
+ nodes: { nodeId: string; state: string; attempts: number; kind?: string; label?: string; description?: string; last: Record<string, unknown> | null }[];
70
+ };