@galaxy-stack/blackhole-cli 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/cli.js +24 -0
  2. package/dist/cli.js.map +1 -1
  3. package/dist/commands.d.ts.map +1 -1
  4. package/dist/commands.js +2 -0
  5. package/dist/commands.js.map +1 -1
  6. package/dist/config-command.d.ts +35 -0
  7. package/dist/config-command.d.ts.map +1 -0
  8. package/dist/config-command.js +273 -0
  9. package/dist/config-command.js.map +1 -0
  10. package/dist/info.d.ts +21 -0
  11. package/dist/info.d.ts.map +1 -0
  12. package/dist/info.js +33 -0
  13. package/dist/info.js.map +1 -0
  14. package/dist/logs.d.ts.map +1 -1
  15. package/dist/logs.js +10 -2
  16. package/dist/logs.js.map +1 -1
  17. package/dist/manual-config.d.ts +17 -0
  18. package/dist/manual-config.d.ts.map +1 -1
  19. package/dist/manual-config.js +35 -0
  20. package/dist/manual-config.js.map +1 -1
  21. package/dist/options.d.ts +2 -2
  22. package/dist/options.d.ts.map +1 -1
  23. package/dist/options.js +5 -1
  24. package/dist/options.js.map +1 -1
  25. package/dist/tui.d.ts.map +1 -1
  26. package/dist/tui.js +39 -1
  27. package/dist/tui.js.map +1 -1
  28. package/dist/update.d.ts +45 -0
  29. package/dist/update.d.ts.map +1 -0
  30. package/dist/update.js +158 -0
  31. package/dist/update.js.map +1 -0
  32. package/dist/web/web.d.ts.map +1 -1
  33. package/dist/web/web.js +16 -5
  34. package/dist/web/web.js.map +1 -1
  35. package/package.json +4 -3
  36. package/skills/galaxy-ui/SKILL.md +18 -0
  37. package/skills/orbit-framework/SKILL.md +18 -0
  38. package/web/brand/app-icon-192.png +0 -0
  39. package/web/brand/app-icon-512.png +0 -0
  40. package/web/brand/client.template.js +581 -79
  41. package/web/brand/dsh-locale-keys.json +2020 -0
  42. package/web/brand/favicon.png +0 -0
  43. package/web/brand/favicon.svg +12 -0
  44. package/web/brand/lib/app-icons.js +3 -0
  45. package/web/brand/lib/client.js +2303 -88
  46. package/web/brand/lib/favicon.js +1 -1
  47. package/web/brand/lib/index.js +618 -18
  48. package/web/brand/lib/journey-host.js +282 -0
  49. package/web/brand/lib/journey-run.d.ts +66 -0
  50. package/web/brand/lib/journey-run.js +315 -0
  51. package/web/brand/lib/journey-store.d.ts +61 -0
  52. package/web/brand/lib/journey-store.js +177 -0
  53. package/web/brand/logo.png +0 -0
  54. package/web/brand/logo.svg +20 -0
  55. package/web/brand/panel/journey-panel.js +884 -0
  56. package/web/brand/vi.locales.json +838 -8
  57. package/web/brand/zalo.jpg +0 -0
  58. package/web/patches/gbh-web.patch.yml +51 -2
@@ -1,6 +1,7 @@
1
1
  //#region node half
2
2
  import { readFileSync } from "node:fs";
3
3
  import { FAVICON_DATA_URI } from "./favicon.js";
4
+ import { APP_ICON_192_DATA_URI, APP_ICON_512_DATA_URI } from "./app-icons.js";
4
5
  import {
5
6
  deleteSession,
6
7
  findSessionDirectories,
@@ -8,9 +9,16 @@ import {
8
9
  isSessionId,
9
10
  listStoredSessions,
10
11
  projectionCachePath,
12
+ readTombstones,
11
13
  resolveHome,
12
14
  sweepTombstones,
13
15
  } from "./session-store.js";
16
+ import { blueprintPathFor, readBlueprint, validateBlueprint, writeBlueprint } from "./journey-store.js";
17
+ import { registerJourneyHost } from "./journey-host.js";
18
+ import { advanceRun, cancelRun, createRun, decideRun, listRuns, readRun, runPath, summarizeRun, writeRun } from "./journey-run.js";
19
+ import { spawn } from "node:child_process";
20
+ import { appendFileSync, mkdirSync } from "node:fs";
21
+ import { join } from "node:path";
14
22
 
15
23
  /**
16
24
  * Host half of the gbh brand plugin: rewords the fixed harness:identity
@@ -40,18 +48,26 @@ const FAVICON_SCRIPT = [
40
48
  const HIDE_UI_SCRIPT = [
41
49
  "(function(){",
42
50
  "var name=" + JSON.stringify("Galaxy Blackhole") + ";",
51
+ "var scheduled=false;",
52
+ /* The dialog is the only place the API-key state is shown, and reading it there is bounded. */
53
+ "function keyMissing(){var dialog=document.querySelector('[role=dialog]');if(!dialog)return false;var text=(dialog.innerText||'').slice(0,4000);return text.indexOf('API key missing')!==-1||text.indexOf('Thiếu API key')!==-1;}",
43
54
  "function hide(){",
44
- "var body=document.body?document.body.textContent||'':'';",
45
- "var keyMissing=body.indexOf('API key missing')!==-1||body.indexOf('Thiếu API key')!==-1;",
46
- "var btns=document.querySelectorAll('button[aria-label]');",
47
- "for(var i=0;i<btns.length;i++){var a=btns[i].getAttribute('aria-label')||'';if(a.indexOf(name)!==-1&&(a.indexOf('Edit')!==-1||a.indexOf('Remove')!==-1||a.indexOf('Delete')!==-1)){btns[i].style.display=keyMissing?'':'none';}}",
48
- "var items=document.querySelectorAll('[role=menuitem],[role=option],li,button');",
49
- "for(var j=0;j<items.length;j++){var el=items[j];if((el.textContent||'').trim()==='中文'){el.style.display='none';}}",
50
- "var details=document.querySelectorAll('details');",
51
- "for(var k=0;k<details.length;k++){var d=details[k];var sm=d.querySelector('summary');var lbl=sm?(sm.textContent||'').trim():'';if(lbl!=='Cài đặt tuỳ chỉnh'&&lbl!=='Customized settings')continue;var p=d.parentElement;var hit=false;for(var m=0;m<6&&p;m++){if((p.textContent||'').indexOf(name)!==-1){hit=true;break;}p=p.parentElement;}if(hit)d.style.display='none';}",
55
+ /* Everything this script hides lives in the settings dialog or an open menu; anywhere
56
+ else the pass is a no-op, so a streaming transcript costs two cheap queries. */
57
+ "if(!document.querySelector('[role=dialog]')&&!document.querySelector('[role=menu]'))return;",
58
+ "var missing=keyMissing();",
59
+ "var btns=document.querySelectorAll('button[aria-label]');var btnLimit=Math.min(btns.length,600);",
60
+ "for(var i=0;i<btnLimit;i++){var a=btns[i].getAttribute('aria-label')||'';if(a.indexOf(name)!==-1&&(a.indexOf('Edit')!==-1||a.indexOf('Remove')!==-1||a.indexOf('Delete')!==-1)){btns[i].style.display=missing?'':'none';}}",
61
+ "var items=document.querySelectorAll('[role=menuitem],[role=option],[role=treeitem]');var itemLimit=Math.min(items.length,400);",
62
+ "for(var j=0;j<itemLimit;j++){var el=items[j];if((el.textContent||'').trim()==='中文'){el.style.display='none';}}",
63
+ "var details=document.querySelectorAll('details');var detailLimit=Math.min(details.length,60);",
64
+ "for(var k=0;k<detailLimit;k++){var d=details[k];var sm=d.querySelector('summary');var lbl=sm?(sm.textContent||'').trim():'';if(lbl!=='Cài đặt tuỳ chỉnh'&&lbl!=='Customized settings')continue;var p=d.parentElement;var hit=false;for(var m=0;m<6&&p;m++){if((p.textContent||'').indexOf(name)!==-1){hit=true;break;}p=p.parentElement;}if(hit)d.style.display='none';}",
52
65
  "}",
53
- "hide();",
54
- "if(typeof MutationObserver==='function'){new MutationObserver(hide).observe(document.documentElement,{childList:true,subtree:true});}",
66
+ /* One pass per mutation burst instead of one per record: a session switch fires
67
+ hundreds of records, and an unthrottled full-document pass froze the renderer. */
68
+ "function schedule(){if(scheduled)return;scheduled=true;setTimeout(function(){scheduled=false;hide();},250);}",
69
+ "schedule();",
70
+ "if(typeof MutationObserver==='function'){new MutationObserver(schedule).observe(document.documentElement,{childList:true,subtree:true});}",
55
71
  "})();",
56
72
  ].join("");
57
73
 
@@ -69,14 +85,26 @@ const TEXT_FIX_SCRIPT = [
69
85
  "function fixText(t){if(!t)return t;var s=t.nodeValue;if(s===null)return;var v=s.trim();if(exact[v]!==undefined){t.nodeValue=s.replace(v,exact[v]);return;}if(v.indexOf('Ran for ')===0){t.nodeValue=s.replace('Ran for ','Chạy trong ');}}",
70
86
  "function walk(root){if(!root)return;if(root.nodeType===3){fixText(root);return;}var it=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,null);var n;while((n=it.nextNode())){fixText(n);}}",
71
87
  "walk(document.body);",
72
- "if(typeof MutationObserver==='function'){new MutationObserver(function(ms){for(var i=0;i<ms.length;i++){var m=ms[i];if(m.type==='characterData'){fixText(m.target);}else{for(var j=0;j<m.addedNodes.length;j++){walk(m.addedNodes[j]);}}}}).observe(document.documentElement,{childList:true,subtree:true,characterData:true});}",
88
+ /* The same burst problem: collect mutated nodes and walk them once. */
89
+ "var pending=[];var pendingScheduled=false;",
90
+ "function flush(){pendingScheduled=false;for(var i=0;i<pending.length;i++){var node=pending[i];if(node.nodeType===3)fixText(node);else walk(node);}pending.length=0;}",
91
+ "function queue(node){if(node)pending.push(node);if(pending.length>400)pending.shift();if(pendingScheduled)return;pendingScheduled=true;setTimeout(flush,200);}",
92
+ "if(typeof MutationObserver==='function'){new MutationObserver(function(ms){for(var i=0;i<ms.length;i++){var m=ms[i];if(m.type==='characterData'){queue(m.target);}else{for(var j=0;j<m.addedNodes.length;j++){queue(m.addedNodes[j]);}}}}).observe(document.documentElement,{childList:true,subtree:true,characterData:true});}",
73
93
  "})();"
74
94
  ].join("");
75
95
 
76
- /** Keep the browser tab title on the product name, even after in-app updates. */
96
+ /**
97
+ * Keep the browser tab title on the product name, even after in-app updates.
98
+ *
99
+ * An installed app window already prints the manifest name ("Galaxy Blackhole") followed
100
+ * by the page title, so repeating it there would render "Galaxy Blackhole - Galaxy
101
+ * Blackhole"; the app window therefore keeps the page title empty and lets the app name
102
+ * stand alone, while a normal tab still shows the product name.
103
+ */
77
104
  const TITLE_SCRIPT = [
78
105
  "(function(){",
79
- 'function enforce(){var want="Galaxy Blackhole";if(document.title!==want){document.title=want;}}',
106
+ "function appWindow(){try{return !!(globalThis.matchMedia&&globalThis.matchMedia('(display-mode: standalone)').matches);}catch(error){return false;}}",
107
+ 'function enforce(){var want=appWindow()?"":"Galaxy Blackhole";if(document.title!==want){document.title=want;}}',
80
108
  "enforce();",
81
109
  "if(typeof MutationObserver==='function'){new MutationObserver(enforce).observe(document.head,{childList:true,subtree:true,characterData:true});}",
82
110
  "})();",
@@ -169,6 +197,89 @@ function sessionIsAttached(ctx, sessionId) {
169
197
  }
170
198
  }
171
199
 
200
+ /** @returns true when the tombstone ledger already records this id as deleted. */
201
+ function isTombstoned(home, sessionId) {
202
+ try {
203
+ return readTombstones(home).some(row => row.id === sessionId);
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+
209
+ function describeError(error) {
210
+ return error instanceof Error ? error.message : String(error);
211
+ }
212
+
213
+ /** Resolve an optional Host service without letting a provider fault break the route. */
214
+ function optionalService(ctx, name) {
215
+ try {
216
+ return ctx.get(name);
217
+ } catch {
218
+ return undefined;
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Hide one Session whose artifacts are being deleted.
224
+ *
225
+ * DSH 0.1.5 exposes no Session-delete service, so removing the artifacts leaves a
226
+ * Session this process still holds attached inside `session.list`: the sidebar row and
227
+ * the transcript survive the delete. The registry-global archive set is the Host's own
228
+ * "hide from every list" primitive (the stock row menu calls it "Archive"), it is
229
+ * durable in `<home>/storages/workspace.json`, and the Workspace controller publishes
230
+ * an `archived` frame the browser applies immediately.
231
+ *
232
+ * @param ctx - plugin context; the registry resolves lazily per delete.
233
+ * @param sessionId - validated session id.
234
+ * @returns true when the id is archived (an already archived id counts as true).
235
+ */
236
+ async function hideDeletedSession(ctx, sessionId) {
237
+ const registry = optionalService(ctx, "workspaceRegistry");
238
+ if (registry === undefined) return false;
239
+ try {
240
+ await registry.archiveSession(sessionId);
241
+ return true;
242
+ } catch (error) {
243
+ /* Best effort: the artifacts still go, and a later delete finishes the job. */
244
+ console.warn("gbh: could not archive session " + sessionId + ": " + describeError(error));
245
+ return false;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Drop one deleted id from every Workspace's accounting.
251
+ *
252
+ * The Workspace registry holds the durable `sessionIds` list the sidebar groups by;
253
+ * nothing prunes it on delete, so a deleted id lingers in `workspace.json` forever.
254
+ *
255
+ * @param ctx - plugin context; the registry resolves lazily per delete.
256
+ * @param sessionId - validated session id.
257
+ * @returns true when at least one Workspace dropped the id.
258
+ */
259
+ async function detachDeletedSession(ctx, sessionId) {
260
+ const registry = optionalService(ctx, "workspaceRegistry");
261
+ if (registry === undefined) return false;
262
+ try {
263
+ const workspaces = registry.list();
264
+ let detached = false;
265
+ for (const workspace of Array.isArray(workspaces) ? workspaces : []) {
266
+ let sessionIds;
267
+ try {
268
+ sessionIds = workspace?.sessionIds;
269
+ } catch {
270
+ sessionIds = undefined;
271
+ }
272
+ if (!Array.isArray(sessionIds) || !sessionIds.includes(sessionId)) continue;
273
+ await workspace.detachSession(sessionId);
274
+ detached = true;
275
+ }
276
+ return detached;
277
+ } catch (error) {
278
+ console.warn("gbh: could not detach session " + sessionId + " from its workspace: " + describeError(error));
279
+ return false;
280
+ }
281
+ }
282
+
172
283
  /** Cached persistence listing; a provider fault degrades to an empty listing. */
173
284
  async function storedSnapshots(ctx) {
174
285
  try {
@@ -229,8 +340,38 @@ async function removeStoredSession(ctx, home, sessionId, options = {}) {
229
340
  known.add(header.id);
230
341
  if (header.parentSession === sessionId) children.push(header.id);
231
342
  }
232
- if (!known.has(sessionId) && findSessionDirectories(home, sessionId).length === 0) {
233
- return { status: 404, body: { ok: false, code: "session/not-found", message: "Session " + sessionId + " does not exist." } };
343
+ const directories = findSessionDirectories(home, sessionId);
344
+ if (!known.has(sessionId) && directories.length === 0) {
345
+ /* Nothing is stored under this home, yet the id can still reach this route: the
346
+ runtime may hold the Session attached, the Workspace registry may still account for
347
+ it, or an earlier delete already tombstoned it. Clean every one of those and answer
348
+ success — the caller's intent ("make this session gone") is already satisfiable, and
349
+ "does not exist" is a dead end the UI cannot act on. */
350
+ const wasRecorded = isTombstoned(home, sessionId);
351
+ const hidden = sessionIsAttached(ctx, sessionId) && (await hideDeletedSession(ctx, sessionId)) ? [sessionId] : [];
352
+ const detached = (await detachDeletedSession(ctx, sessionId)) ? [sessionId] : [];
353
+ let projectionCache = false;
354
+ try {
355
+ /* Also records the tombstone, so a live runtime that flushes this id later is swept. */
356
+ projectionCache = deleteSession(home, sessionId, { trash: options.trash !== false }).projectionCache;
357
+ } catch (error) {
358
+ return { status: 500, body: { ok: false, code: "session/delete-failed", message: describeError(error) } };
359
+ }
360
+ return {
361
+ status: 200,
362
+ body: {
363
+ ok: true,
364
+ alreadyDeleted: wasRecorded,
365
+ /* False only when this id left no trace here at all: no artifact, no tombstone,
366
+ nothing attached, no Workspace accounting. */
367
+ found: wasRecorded || hidden.length > 0 || detached.length > 0,
368
+ deleted: [],
369
+ cascaded: [],
370
+ hidden,
371
+ detached,
372
+ projectionCache,
373
+ },
374
+ };
234
375
  }
235
376
  if (sessionIsRunning(ctx, sessionId)) {
236
377
  return {
@@ -249,9 +390,16 @@ async function removeStoredSession(ctx, home, sessionId, options = {}) {
249
390
  },
250
391
  };
251
392
  }
393
+ const targets = options.cascade === true && children.length > 0 ? [...children, sessionId] : [sessionId];
394
+ /* Hide every target this process still holds attached before unlinking it: such a
395
+ Session keeps its row in every list (and its transcript readable) without files. */
396
+ const hidden = [];
397
+ for (const target of targets) {
398
+ if (!sessionIsAttached(ctx, target)) continue;
399
+ if (await hideDeletedSession(ctx, target)) hidden.push(target);
400
+ }
252
401
  const removed = [];
253
402
  try {
254
- const targets = options.cascade === true && children.length > 0 ? [...children, sessionId] : [sessionId];
255
403
  for (const target of targets) {
256
404
  const result = deleteSession(home, target, { trash: options.trash !== false });
257
405
  removed.push({ id: target, bytes: result.bytes, trashedTo: result.trashedTo, projectionCache: result.projectionCache });
@@ -259,10 +407,27 @@ async function removeStoredSession(ctx, home, sessionId, options = {}) {
259
407
  } catch (error) {
260
408
  return {
261
409
  status: 500,
262
- body: { ok: false, code: "session/delete-failed", message: error instanceof Error ? error.message : String(error) },
410
+ body: { ok: false, code: "session/delete-failed", message: describeError(error) },
263
411
  };
264
412
  }
265
- return { status: 200, body: { ok: true, deleted: removed, cascaded: options.cascade === true ? children : [] } };
413
+ /* The artifact is gone; drop the id from the durable Workspace accounting so
414
+ `workspace.json` stops listing a Session that no longer exists. */
415
+ const detached = [];
416
+ for (const target of targets) {
417
+ if (await detachDeletedSession(ctx, target)) detached.push(target);
418
+ }
419
+ return {
420
+ status: 200,
421
+ body: {
422
+ ok: true,
423
+ alreadyDeleted: false,
424
+ found: true,
425
+ deleted: removed,
426
+ cascaded: options.cascade === true ? children : [],
427
+ hidden,
428
+ detached,
429
+ },
430
+ };
266
431
  }
267
432
 
268
433
  /**
@@ -315,6 +480,425 @@ function registerSessionRoutes(ctx, connectionCtx) {
315
480
  }
316
481
  //#endregion
317
482
 
483
+ //#region update routes
484
+ /** Browser routes that report versions and run the CLI's own npm upgrade. */
485
+ const UPDATE_VERSION_PATH = "/api/galaxy/version";
486
+ const UPDATE_RUN_PATH = "/api/galaxy/update";
487
+ const UPDATE_PROGRESS_PATH = "/api/galaxy/update.progress";
488
+ const UPDATE_PACKAGE = "@galaxy-stack/blackhole-cli";
489
+ let updateVersionCache = { at: 0, latest: undefined };
490
+ let updateRunState;
491
+
492
+ /** True when `candidate` is strictly newer than `current` (x.y.z, pre-releases ignored). */
493
+ function updateIsNewer(candidate, current) {
494
+ const parse = (value) => String(value).trim().replace(/^v/, "").split("-")[0].split(".").map((part) => Number.parseInt(part, 10) || 0);
495
+ const left = parse(candidate);
496
+ const right = parse(current);
497
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
498
+ const a = left[index] ?? 0;
499
+ const b = right[index] ?? 0;
500
+ if (a !== b) return a > b;
501
+ }
502
+ return false;
503
+ }
504
+
505
+ /** Newest published version, cached for six hours; an offline machine simply reports none. */
506
+ async function updateLatestVersion() {
507
+ if (updateVersionCache.latest !== undefined && Date.now() - updateVersionCache.at < 6 * 3600_000) return updateVersionCache.latest;
508
+ const output = await new Promise((resolve) => {
509
+ let text = "";
510
+ try {
511
+ const child = spawn("npm", ["view", UPDATE_PACKAGE, "version"], { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
512
+ const timer = setTimeout(() => child.kill("SIGTERM"), 8000);
513
+ child.stdout.on("data", (chunk) => { text += String(chunk); });
514
+ child.stderr.on("data", (chunk) => { text += String(chunk); });
515
+ child.once("close", () => { clearTimeout(timer); resolve(text); });
516
+ child.once("error", () => { clearTimeout(timer); resolve(""); });
517
+ } catch {
518
+ resolve("");
519
+ }
520
+ });
521
+ const latest = output.trim().split("\n").pop().trim();
522
+ updateVersionCache = { at: Date.now(), latest: /^\d+\.\d+\.\d+/.test(latest) ? latest : undefined };
523
+ return updateVersionCache.latest;
524
+ }
525
+
526
+ /** Start `npm install -g` once and follow it; the browser polls the percentage. */
527
+ function updateStart() {
528
+ if (updateRunState !== undefined && updateRunState.done !== true) return updateRunState;
529
+ const state = { pct: 5, line: "đang bắt đầu", done: false, ok: false, startedAt: Date.now() };
530
+ updateRunState = state;
531
+ const absorb = (chunk) => {
532
+ for (const raw of String(chunk).split("\n")) {
533
+ const line = raw.trim();
534
+ if (line.length === 0) continue;
535
+ state.line = line.slice(0, 140);
536
+ if (/reify|idealTree|audit/i.test(line)) state.pct = Math.max(state.pct, 55);
537
+ if (/added \d+ package|changed \d+ package|up to date/i.test(line)) state.pct = Math.max(state.pct, 95);
538
+ }
539
+ };
540
+ try {
541
+ const child = spawn("npm", ["install", "-g", UPDATE_PACKAGE + "@latest"], { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
542
+ child.stdout.on("data", absorb);
543
+ child.stderr.on("data", absorb);
544
+ const ticker = setInterval(() => {
545
+ state.pct = Math.min(90, Math.max(state.pct, 5 + Math.round(((Date.now() - state.startedAt) / 30_000) * 60)));
546
+ }, 500);
547
+ ticker.unref?.();
548
+ child.once("close", (code) => {
549
+ clearInterval(ticker);
550
+ state.pct = 100;
551
+ state.ok = code === 0;
552
+ state.done = true;
553
+ if (!state.ok) state.line = "npm thoát với mã " + String(code);
554
+ });
555
+ child.once("error", (error) => {
556
+ clearInterval(ticker);
557
+ state.pct = 100;
558
+ state.ok = false;
559
+ state.done = true;
560
+ state.line = String(error instanceof Error ? error.message : error).slice(0, 140);
561
+ });
562
+ } catch (error) {
563
+ state.pct = 100;
564
+ state.ok = false;
565
+ state.done = true;
566
+ state.line = String(error instanceof Error ? error.message : error).slice(0, 140);
567
+ }
568
+ return state;
569
+ }
570
+
571
+ function registerUpdateRoutes(ctx, connectionCtx) {
572
+ connectionCtx.connection.fetch.register({
573
+ path: UPDATE_VERSION_PATH,
574
+ methods: ["GET"],
575
+ requestBody: "buffered",
576
+ fetch: async (request) => {
577
+ const current = new URL(request.url).searchParams.get("current") ?? "";
578
+ const latest = await updateLatestVersion();
579
+ return jsonResponse({
580
+ current,
581
+ latest: latest ?? null,
582
+ hasUpdate: latest !== undefined && current.length > 0 && updateIsNewer(latest, current),
583
+ });
584
+ },
585
+ });
586
+ connectionCtx.connection.fetch.register({
587
+ path: UPDATE_RUN_PATH,
588
+ methods: ["POST"],
589
+ requestBody: "buffered",
590
+ fetch: async () => {
591
+ const state = updateStart();
592
+ return jsonResponse({ ok: true, pct: state.pct, line: state.line });
593
+ },
594
+ });
595
+ connectionCtx.connection.fetch.register({
596
+ path: UPDATE_PROGRESS_PATH,
597
+ methods: ["GET"],
598
+ requestBody: "buffered",
599
+ fetch: async () => updateRunState === undefined
600
+ ? jsonResponse({ pct: 0, line: "", done: false, ok: false })
601
+ : jsonResponse({ pct: updateRunState.pct, line: updateRunState.line, done: updateRunState.done, ok: updateRunState.ok }),
602
+ });
603
+ }
604
+ //#endregion
605
+
606
+ //#region journey blueprint routes
607
+ /** Browser routes owned by the Galaxy journey panel. */
608
+ const JOURNEY_PATH = "/api/galaxy/journey";
609
+
610
+ /** Workspace root of one session, resolved from the trusted persistence record. */
611
+ async function sessionWorkspaceRoot(ctx, sessionId) {
612
+ try {
613
+ const persistence = ctx.get("sessionPersistence");
614
+ if (persistence === undefined) return undefined;
615
+ const snapshot = await persistence.stat(sessionId);
616
+ const cwd = snapshot?.header?.cwd;
617
+ if (typeof cwd === "string" && cwd.length > 0) return cwd;
618
+ const snapshots = await persistence.list();
619
+ for (const row of Array.isArray(snapshots) ? snapshots : []) {
620
+ if (row?.header?.id === sessionId && typeof row.header.cwd === "string") return row.header.cwd;
621
+ }
622
+ return undefined;
623
+ } catch {
624
+ return undefined;
625
+ }
626
+ }
627
+
628
+ /** Append one journey mutation to the local audit ledger; never fails the request. */
629
+ function appendJourneyAudit(entry) {
630
+ try {
631
+ const directory = join(resolveHome(), "journey");
632
+ mkdirSync(directory, { recursive: true });
633
+ appendFileSync(join(directory, "history.jsonl"), JSON.stringify(entry) + "\n", { encoding: "utf8", mode: 0o600 });
634
+ } catch {
635
+ /* the audit ledger is best effort */
636
+ }
637
+ }
638
+
639
+ /** Register the Galaxy journey routes on the Host connection carrier. */
640
+ function registerJourneyRoutes(ctx, connectionCtx) {
641
+ /* One registration per path: the Host registry refuses a second one for the same path. */
642
+ connectionCtx.connection.fetch.register({
643
+ path: JOURNEY_PATH,
644
+ methods: ["GET", "HEAD", "POST"],
645
+ requestBody: "buffered",
646
+ fetch: async (request) => {
647
+ if (request.method === "POST") return handleJourneyWrite(ctx, request);
648
+ const url = new URL(request.url);
649
+ const sessionId = url.searchParams.get("sessionId") ?? "";
650
+ const root = await sessionWorkspaceRoot(ctx, sessionId);
651
+ if (root === undefined) {
652
+ return jsonResponse({ ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." }, 409);
653
+ }
654
+ let path;
655
+ try {
656
+ path = blueprintPathFor(root);
657
+ } catch (error) {
658
+ return jsonResponse({ ok: false, code: "journey/no-workspace", message: error instanceof Error ? error.message : String(error) }, 409);
659
+ }
660
+ const blueprint = readBlueprint(root);
661
+ if (blueprint.parseError !== undefined) {
662
+ return jsonResponse({ ok: false, code: "journey/unparsable", path, message: "journey.json is not valid JSON: " + blueprint.parseError }, 422);
663
+ }
664
+ const body = {
665
+ ok: true,
666
+ path,
667
+ workspaceRoot: root,
668
+ exists: blueprint.exists,
669
+ revision: typeof blueprint.document?.revision === "number" ? blueprint.document.revision : 0,
670
+ hash: blueprint.hash,
671
+ document: blueprint.document,
672
+ issues: validateBlueprint(blueprint.document),
673
+ };
674
+ const response = jsonResponse(body);
675
+ if (request.method === "GET") return response;
676
+ await response.body?.cancel();
677
+ return new Response(null, { status: response.status, headers: response.headers });
678
+ },
679
+ });
680
+ }
681
+
682
+ /** Append one feedback remark to the session log, audited locally. */
683
+ async function handleFeedbackWrite(ctx, request) {
684
+ let payload;
685
+ try {
686
+ payload = await request.json();
687
+ } catch {
688
+ return jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
689
+ }
690
+ const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
691
+ const text = typeof payload?.text === "string" ? payload.text.trim() : "";
692
+ const category = typeof payload?.category === "string" ? payload.category : "";
693
+ if (text.length === 0) {
694
+ return jsonResponse({ ok: false, code: "invalid-request", message: "Feedback text is required." }, 400);
695
+ }
696
+ let session;
697
+ try {
698
+ const sessions = ctx.get("sessions");
699
+ session = sessions?.get?.(sessionId);
700
+ } catch {
701
+ session = undefined;
702
+ }
703
+ if (session === undefined || typeof session.append !== "function") {
704
+ return jsonResponse({ ok: false, code: "feedback/no-session", message: "This session is not live in this runtime." }, 409);
705
+ }
706
+ try {
707
+ session.append("feedback/record", {
708
+ text,
709
+ ...(category.length === 0 ? {} : { category }),
710
+ });
711
+ } catch (error) {
712
+ return jsonResponse({ ok: false, code: "feedback/append-failed", message: error instanceof Error ? error.message : String(error) }, 500);
713
+ }
714
+ try {
715
+ const directory = join(resolveHome(), "feedback");
716
+ mkdirSync(directory, { recursive: true });
717
+ appendFileSync(join(directory, "history.jsonl"), JSON.stringify({ at: new Date().toISOString(), sessionId, category, text }) + "\n", { encoding: "utf8", mode: 0o600 });
718
+ } catch {
719
+ /* the audit ledger is best effort */
720
+ }
721
+ return jsonResponse({ ok: true, sessionId, category });
722
+ }
723
+
724
+ /** One blueprint write: validate, compare-and-swap, audit. */
725
+ async function handleJourneyWrite(ctx, request) {
726
+ let payload;
727
+ try {
728
+ payload = await request.json();
729
+ } catch {
730
+ return jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
731
+ }
732
+ const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
733
+ const root = await sessionWorkspaceRoot(ctx, sessionId);
734
+ if (root === undefined) {
735
+ return jsonResponse({ ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." }, 409);
736
+ }
737
+ const document = payload?.document;
738
+ if (document === null || typeof document !== "object") {
739
+ return jsonResponse({ ok: false, code: "invalid-request", message: "document is required." }, 400);
740
+ }
741
+ const expectedRevision = typeof payload?.expectedRevision === "number" ? payload.expectedRevision : undefined;
742
+ const updatedBy = payload?.updatedBy === "agent" ? "agent" : "human";
743
+ const result = writeBlueprint(root, document, {
744
+ ...(expectedRevision === undefined ? {} : { expectedRevision }),
745
+ updatedBy,
746
+ });
747
+ if (result.ok !== true) {
748
+ return jsonResponse(result, result.code === "journey/conflict" ? 409 : 422);
749
+ }
750
+ appendJourneyAudit({ at: new Date().toISOString(), sessionId, path: result.path, revision: result.revision, hash: result.hash, updatedBy });
751
+ return jsonResponse({ ok: true, revision: result.revision, hash: result.hash, path: result.path });
752
+ }
753
+ //#endregion
754
+
755
+ //#region installed-app identity
756
+ /**
757
+ * The shipped web-app manifest names the product "DeepSeek Harness" and draws its icon
758
+ * from the DSH favicon, so Chrome's install offer and the installed app window wear the
759
+ * upstream identity — the overlay rebrands the page but not that file. Serving our own
760
+ * manifest and icons on the same paths keeps the installable app while making the name,
761
+ * the window title and the dock icon say Galaxy Blackhole.
762
+ */
763
+ const MANIFEST_PATH = "/manifest.webmanifest";
764
+ const APP_ICON_192_PATH = "/gbh-app-icon-192.png";
765
+ const APP_ICON_512_PATH = "/gbh-app-icon-512.png";
766
+ const APP_MANIFEST = {
767
+ id: "/",
768
+ name: "Galaxy Blackhole",
769
+ /* Chrome shows `name` in the app window/title and `short_name` where space is tight. */
770
+ short_name: "Galaxy Blackhole",
771
+ description: "Galaxy Blackhole — the Galaxy AI coding stack in the browser.",
772
+ start_url: "/",
773
+ scope: "/",
774
+ display: "standalone",
775
+ background_color: "#0b0a14",
776
+ theme_color: "#0b0a14",
777
+ icons: [
778
+ { src: APP_ICON_192_PATH, sizes: "192x192", type: "image/png", purpose: "any" },
779
+ { src: APP_ICON_512_PATH, sizes: "512x512", type: "image/png", purpose: "any" },
780
+ ],
781
+ };
782
+ /** The manifest icons the build script baked into the plugin. */
783
+ const APP_ICONS = [
784
+ [APP_ICON_192_PATH, APP_ICON_192_DATA_URI],
785
+ [APP_ICON_512_PATH, APP_ICON_512_DATA_URI],
786
+ ];
787
+
788
+ /** Decode one generated `data:…;base64,…` asset into the bytes a route returns. */
789
+ function dataUriBytes(dataUri) {
790
+ const comma = dataUri.indexOf(",");
791
+ return Buffer.from(comma === -1 ? "" : dataUri.slice(comma + 1), "base64");
792
+ }
793
+
794
+ /** Answer one whole-response route with a fixed body and its own caching policy. */
795
+ function sendBody(request, response, contentType, body, cacheControl) {
796
+ if (request.method !== "GET" && request.method !== "HEAD") {
797
+ response.writeHead(405, { allow: "GET, HEAD" });
798
+ response.end();
799
+ return;
800
+ }
801
+ response.writeHead(200, {
802
+ "content-type": contentType,
803
+ "content-length": body.length,
804
+ "cache-control": cacheControl,
805
+ });
806
+ if (request.method === "HEAD") {
807
+ response.end();
808
+ return;
809
+ }
810
+ response.end(body);
811
+ }
812
+
813
+ /**
814
+ * Serve the Galaxy app identity on the paths the shipped index already links.
815
+ *
816
+ * @param hostCtx - the injected webServer scope owning route registration.
817
+ */
818
+ function registerAppIdentity(hostCtx) {
819
+ const manifest = Buffer.from(JSON.stringify(APP_MANIFEST, null, 2) + "\n", "utf8");
820
+ hostCtx.effect(
821
+ () => hostCtx.webServer.register({
822
+ kind: "exact",
823
+ path: MANIFEST_PATH,
824
+ handler: (request, response) => sendBody(request, response, "application/manifest+json; charset=utf-8", manifest, "no-cache"),
825
+ }),
826
+ "gbh-brand: app manifest",
827
+ );
828
+ for (const [path, dataUri] of APP_ICONS) {
829
+ const body = dataUriBytes(dataUri);
830
+ hostCtx.effect(
831
+ () => hostCtx.webServer.register({
832
+ kind: "exact",
833
+ path,
834
+ handler: (request, response) => sendBody(request, response, "image/png", body, "public, max-age=86400"),
835
+ }),
836
+ "gbh-brand: app icon " + path,
837
+ );
838
+ }
839
+ }
840
+ //#endregion
841
+
842
+ //#region galaxy feedback route
843
+ /** Browser route owned by the Galaxy feedback settings section. */
844
+ const FEEDBACK_PATH = "/api/galaxy/feedback";
845
+ /** The taxonomy the stock feedback surface defined; kept as durable log vocabulary. */
846
+ const FEEDBACK_CATEGORIES = [
847
+ "task-result",
848
+ "instruction-following",
849
+ "product-interaction",
850
+ "service-stability",
851
+ "resource-cost",
852
+ "security-privacy-permission",
853
+ "other",
854
+ ];
855
+
856
+ /**
857
+ * Record one remark as the session's own \`feedback/record\` event.
858
+ *
859
+ * The stock command and dialog are disabled in this profile, so the Galaxy settings
860
+ * section is the only producer; appending through the live Session keeps the event
861
+ * type, the log placement, and the audit trail identical to the stock behaviour.
862
+ */
863
+ function registerFeedbackRoute(ctx, connectionCtx) {
864
+ connectionCtx.connection.fetch.register({
865
+ path: FEEDBACK_PATH,
866
+ methods: ["POST"],
867
+ requestBody: "buffered",
868
+ fetch: async request => {
869
+ let payload;
870
+ try {
871
+ payload = await request.json();
872
+ } catch {
873
+ return jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
874
+ }
875
+ const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
876
+ const text = typeof payload?.text === "string" ? payload.text.trim().slice(0, 4000) : "";
877
+ const category = typeof payload?.category === "string" ? payload.category : undefined;
878
+ if (text.length === 0) return jsonResponse({ ok: false, code: "feedback/empty", message: "Feedback text is required." }, 400);
879
+ if (category !== undefined && !FEEDBACK_CATEGORIES.includes(category)) {
880
+ return jsonResponse({ ok: false, code: "feedback/category", message: "Unknown feedback category." }, 400);
881
+ }
882
+ let session;
883
+ try {
884
+ session = ctx.get("sessions")?.get?.(sessionId);
885
+ } catch {
886
+ session = undefined;
887
+ }
888
+ if (session === undefined) {
889
+ return jsonResponse({ ok: false, code: "feedback/no-session", message: "This session is not attached to the runtime." }, 409);
890
+ }
891
+ try {
892
+ session.append("feedback/record", { text, ...(category === undefined ? {} : { category }) });
893
+ } catch (error) {
894
+ return jsonResponse({ ok: false, code: "feedback/append-failed", message: error instanceof Error ? error.message : String(error) }, 500);
895
+ }
896
+ return jsonResponse({ ok: true, recorded: true });
897
+ },
898
+ });
899
+ }
900
+ //#endregion
901
+
318
902
  /** The system-prompt registry owns the section this plugin rewrites. */
319
903
  export const inject = ["systemPrompt"];
320
904
 
@@ -331,6 +915,19 @@ function apply(ctx) {
331
915
  });
332
916
  ctx.inject(["web"], (webCtx) => webCtx.web.registerSearchProvider(createGalaxySearchProvider()));
333
917
  ctx.inject(["connection"], (connectionCtx) => registerSessionRoutes(ctx, connectionCtx));
918
+ ctx.inject(["connection"], (connectionCtx) => registerJourneyRoutes(ctx, connectionCtx));
919
+ ctx.inject(["connection"], (connectionCtx) => registerUpdateRoutes(ctx, connectionCtx));
920
+ ctx.inject(["connection"], (connectionCtx) => {
921
+ connectionCtx.connection.fetch.register({
922
+ path: "/api/galaxy/feedback",
923
+ methods: ["POST"],
924
+ requestBody: "buffered",
925
+ fetch: request => handleFeedbackWrite(ctx, request),
926
+ });
927
+ });
928
+ ctx.inject(["connection"], (connectionCtx) => registerFeedbackRoute(ctx, connectionCtx));
929
+ /* Run route, agent tools, and the /journey command all share this host's helpers. */
930
+ registerJourneyHost({ ctx, jsonResponse, sessionWorkspaceRoot, appendJourneyAudit });
334
931
  ctx.inject(["webServer"], (hostCtx) => {
335
932
  hostCtx.on("webserver/index-inject", (table) => {
336
933
  table.push({ kind: "script", placement: "body", text: FAVICON_SCRIPT });
@@ -339,6 +936,9 @@ function apply(ctx) {
339
936
  table.push({ kind: "script", placement: "body", text: TEXT_FIX_SCRIPT });
340
937
  table.push({ kind: "global", name: "__GBH_HAS_KEY__", value: (process.env.GBH_GALAXY_API_KEY ?? "").length > 0 });
341
938
  });
939
+ /* The install stays available, wearing the Galaxy name and icon instead of the
940
+ shipped "DeepSeek Harness" manifest. */
941
+ registerAppIdentity(hostCtx);
342
942
  });
343
943
  }
344
944
  //#endregion