@galaxy-stack/blackhole-cli 3.0.13 → 3.0.14

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 (69) hide show
  1. package/CHANGELOG.md +971 -0
  2. package/README.md +12 -11
  3. package/dist/harness/install-command.js +2 -2
  4. package/dist/harness/install-command.js.map +1 -1
  5. package/dist/harness/install.d.ts +1 -1
  6. package/dist/harness/install.js +1 -1
  7. package/dist/harness/locate.d.ts +9 -3
  8. package/dist/harness/locate.d.ts.map +1 -1
  9. package/dist/harness/locate.js +39 -7
  10. package/dist/harness/locate.js.map +1 -1
  11. package/dist/harness/node-runtime.d.ts +37 -3
  12. package/dist/harness/node-runtime.d.ts.map +1 -1
  13. package/dist/harness/node-runtime.js +60 -14
  14. package/dist/harness/node-runtime.js.map +1 -1
  15. package/dist/harness/process.d.ts +1 -1
  16. package/dist/harness/process.d.ts.map +1 -1
  17. package/dist/harness/process.js +14 -5
  18. package/dist/harness/process.js.map +1 -1
  19. package/dist/migrate.d.ts +20 -12
  20. package/dist/migrate.d.ts.map +1 -1
  21. package/dist/migrate.js +39 -67
  22. package/dist/migrate.js.map +1 -1
  23. package/dist/options.d.ts +1 -1
  24. package/dist/options.d.ts.map +1 -1
  25. package/dist/options.js +1 -1
  26. package/dist/web/command.d.ts +1 -1
  27. package/dist/web/command.js +3 -3
  28. package/dist/web/command.js.map +1 -1
  29. package/dist/web/doctor.js +5 -5
  30. package/dist/web/doctor.js.map +1 -1
  31. package/dist/web/options.js +2 -2
  32. package/dist/web/options.js.map +1 -1
  33. package/dist/web/web.d.ts +6 -4
  34. package/dist/web/web.d.ts.map +1 -1
  35. package/dist/web/web.js +10 -8
  36. package/dist/web/web.js.map +1 -1
  37. package/package.json +4 -6
  38. package/dist/web/dsh.d.ts +0 -51
  39. package/dist/web/dsh.d.ts.map +0 -1
  40. package/dist/web/dsh.js +0 -149
  41. package/dist/web/dsh.js.map +0 -1
  42. package/web/brand/app-icon-192.png +0 -0
  43. package/web/brand/app-icon-512.png +0 -0
  44. package/web/brand/client.template.js +0 -1259
  45. package/web/brand/dsh-locale-keys.json +0 -8659
  46. package/web/brand/favicon.png +0 -0
  47. package/web/brand/favicon.svg +0 -12
  48. package/web/brand/lib/app-icons.js +0 -3
  49. package/web/brand/lib/client.js +0 -5161
  50. package/web/brand/lib/favicon.js +0 -1
  51. package/web/brand/lib/index.d.ts +0 -3
  52. package/web/brand/lib/index.js +0 -1068
  53. package/web/brand/lib/journey-host.js +0 -288
  54. package/web/brand/lib/journey-run.d.ts +0 -70
  55. package/web/brand/lib/journey-run.js +0 -344
  56. package/web/brand/lib/journey-store.d.ts +0 -61
  57. package/web/brand/lib/journey-store.js +0 -183
  58. package/web/brand/lib/session-store.d.ts +0 -54
  59. package/web/brand/lib/session-store.js +0 -288
  60. package/web/brand/logo.png +0 -0
  61. package/web/brand/logo.svg +0 -20
  62. package/web/brand/package.json +0 -35
  63. package/web/brand/panel/journey-panel.js +0 -1037
  64. package/web/brand/vi-same-by-design.json +0 -112
  65. package/web/brand/vi.locales.json +0 -2867
  66. package/web/brand/zalo.jpg +0 -0
  67. package/web/patches/gbh-brand.patch.yml +0 -13
  68. package/web/patches/gbh-ui.patch.yml +0 -7
  69. package/web/patches/gbh-web.patch.yml +0 -124
@@ -1,1068 +0,0 @@
1
- //#region node half
2
- import { readFileSync } from "node:fs";
3
- import { FAVICON_DATA_URI } from "./favicon.js";
4
- import { APP_ICON_192_DATA_URI, APP_ICON_512_DATA_URI } from "./app-icons.js";
5
- import {
6
- deleteSession,
7
- findSessionDirectories,
8
- formatBytes,
9
- isSessionId,
10
- listStoredSessions,
11
- projectionCachePath,
12
- readTombstones,
13
- resolveHome,
14
- sweepTombstones,
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, existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
21
- import { join } from "node:path";
22
-
23
- /**
24
- * Host half of the gbh brand plugin: rewords the fixed harness:identity
25
- * system-prompt section, replaces the page favicon, hides the built-in
26
- * provider's edit/remove actions, and registers the Galaxy web-search provider.
27
- */
28
-
29
- const IDENTITY_SECTION = "harness:identity";
30
- const IDENTITY_TEXT = "You are an AI agent powered by Galaxy Blackhole.";
31
- const PERSONA_SECTION = "deployment:persona-prefix";
32
- const PERSONA_TEXT = "You are a coding agent powered by Galaxy Blackhole.";
33
-
34
- const FAVICON_SCRIPT = [
35
- "(function(){",
36
- "var href=" + JSON.stringify(FAVICON_DATA_URI) + ";",
37
- 'function apply(){var links=document.querySelectorAll("link[rel*=icon]");for(var i=0;i<links.length;i++){links[i].parentNode.removeChild(links[i]);}var link=document.createElement("link");link.rel="icon";link.type="image/png";link.href=href;document.head.appendChild(link);}',
38
- 'if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",apply);}else{apply();}',
39
- "})();",
40
- ].join("");
41
-
42
- /**
43
- * Hide two things the stock UI still shows:
44
- * - the built-in provider's edit/remove actions on the Models page (buttons
45
- * labelled "Edit/Remove provider {provider}"), keeping later providers editable;
46
- * - the built-in Chinese language option, leaving English and Vietnamese.
47
- */
48
- const HIDE_UI_SCRIPT = [
49
- "(function(){",
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;}",
54
- "function hide(){",
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';}",
65
- "}",
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});}",
71
- "})();",
72
- ].join("");
73
-
74
-
75
- /** Late text replacements the locale layer cannot reach on 0.1.5. */
76
- const TEXT_FIX_SCRIPT = [
77
- "(function(){",
78
- "var exact={",
79
- "\"HARNESS\":\"GALAXY BLACKHOLE\",",
80
- "\"Read Only\":\"Chỉ đọc\",",
81
- "\"Workspace Write\":\"Ghi trong workspace\",",
82
- "\"Full access\":\"Toàn quyền\",",
83
- "\"Loading plugins…\":\"Đang tải...\"",
84
- "};",
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 ');}}",
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);}}",
87
- "walk(document.body);",
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});}",
93
- "})();"
94
- ].join("");
95
-
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
- */
104
- const TITLE_SCRIPT = [
105
- "(function(){",
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;}}',
108
- "enforce();",
109
- "if(typeof MutationObserver==='function'){new MutationObserver(enforce).observe(document.head,{childList:true,subtree:true,characterData:true});}",
110
- "})();",
111
- ].join("");
112
-
113
- /* A real provider id. "auto" is the seam's policy (pick the only usable provider), not an id:
114
- registering under it made the seam report the provider as configured but unavailable. */
115
- const GALAXY_SEARCH_ID = "galaxy";
116
- const GALAXY_SEARCH_URL = "https://ollama.com/api/web_search";
117
- const GALAXY_REF = "GBH_GALAXY_API_KEY";
118
-
119
- /** A quoted scalar ends at its closing quote — a comment may follow it on the same line. */
120
- function unquoteValue(raw) {
121
- const value = raw.trim();
122
- const quote = value.charAt(0);
123
- if ((quote === '"' || quote === "'") && value.length >= 2) {
124
- const end = value.indexOf(quote, 1);
125
- if (end !== -1) return dequote(value.slice(0, end + 1));
126
- }
127
- const comment = value.search(/\s#/);
128
- return (comment === -1 ? value : value.slice(0, comment)).trim();
129
- }
130
-
131
- function dequote(value) {
132
- if (value.charAt(0) === '"') {
133
- try { return JSON.parse(value); } catch (error) { return value.slice(1, -1); }
134
- }
135
- return value.slice(1, -1);
136
- }
137
-
138
- /**
139
- * The key the first-run journey wrote, from the environment or the shared credential document
140
- * (~/.galaxy/credentials.yaml, refs: GBH_GALAXY_API_KEY).
141
- *
142
- * Reading only the environment is why web_search reported "registered but unavailable" for every
143
- * user who configured the key through setup instead of an env var.
144
- */
145
- function galaxyKey() {
146
- const fromEnv = process.env[GALAXY_REF];
147
- if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim();
148
- return readGalaxyKeyFromDocument();
149
- }
150
-
151
- function readGalaxyKeyFromDocument() {
152
- try {
153
- const home = process.env.HOME ?? process.env.USERPROFILE;
154
- if (typeof home !== "string" || home.length === 0) return undefined;
155
- const lines = readFileSync(join(home, ".galaxy", "credentials.yaml"), "utf8").split(/\r?\n/);
156
- let inRefs = false;
157
- for (const line of lines) {
158
- if (!inRefs) { inRefs = /^refs:\s*(#.*)?$/.test(line); continue; }
159
- if (line.trim().length === 0 || line.trimStart().startsWith("#")) continue;
160
- const match = /^\s+([^\s#][^:]*):\s*(.*)$/.exec(line);
161
- if (match === null) break;
162
- if (unquoteValue(match[1] ?? "") !== GALAXY_REF) continue;
163
- const value = unquoteValue(match[2] ?? "");
164
- return value.length === 0 ? undefined : value;
165
- }
166
- return undefined;
167
- } catch (error) {
168
- return undefined;
169
- }
170
- }
171
-
172
- /** A ctx.web search provider over the Galaxy web search endpoint. */
173
- function createGalaxySearchProvider() {
174
- return {
175
- id: GALAXY_SEARCH_ID,
176
- available() {
177
- return galaxyKey() !== undefined;
178
- },
179
- async search(request, signal) {
180
- const key = galaxyKey();
181
- if (key === undefined) throw new Error("galaxy web_search requires GBH_GALAXY_API_KEY");
182
- const body = { query: request?.query ?? "" };
183
- if (typeof request?.maxResults === "number") body.max_results = request.maxResults;
184
- const response = await fetch(GALAXY_SEARCH_URL, {
185
- method: "POST",
186
- headers: { "Content-Type": "application/json", Authorization: "Bearer " + key },
187
- body: JSON.stringify(body),
188
- ...(signal === undefined ? {} : { signal }),
189
- });
190
- if (!response.ok) throw new Error("galaxy web_search HTTP " + response.status);
191
- const payload = await response.json();
192
- const rows = Array.isArray(payload?.results) ? payload.results : [];
193
- const sources = [];
194
- for (const row of rows) {
195
- const url = typeof row?.url === "string" ? row.url : "";
196
- if (url.length === 0) continue;
197
- const source = { url };
198
- if (typeof row?.title === "string") source.title = row.title;
199
- if (typeof row?.content === "string") source.snippet = row.content;
200
- sources.push(source);
201
- }
202
- return { sources, truncated: false };
203
- },
204
- };
205
- }
206
-
207
- //#region session maintenance
208
- /** Browser routes owned by the Galaxy session tools. */
209
- const SESSIONS_PATH = "/api/galaxy/sessions";
210
- const SESSION_DELETE_PATH = "/api/galaxy/session.delete";
211
-
212
- function jsonResponse(body, status = 200) {
213
- return new Response(JSON.stringify(body), {
214
- status,
215
- headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
216
- });
217
- }
218
-
219
- /** Read the durable title the sidebar projects for one session, when it exists. */
220
- function sessionTitleFromCache(home, sessionId) {
221
- try {
222
- const raw = readFileSync(projectionCachePath(home, sessionId), "utf8");
223
- const parsed = JSON.parse(raw);
224
- const title = parsed?.record?.rows?.title?.val;
225
- return typeof title === "string" && title.length > 0 ? title : undefined;
226
- } catch {
227
- return undefined;
228
- }
229
- }
230
-
231
- /** The Host's own running predicate, shared with the Session list projection. */
232
- function sessionIsRunning(ctx, sessionId) {
233
- try {
234
- const agents = ctx.get("agents");
235
- return agents?.get?.(sessionId)?.status === "running";
236
- } catch {
237
- return false;
238
- }
239
- }
240
-
241
- /** Whether this DSH process currently holds the Session attached. */
242
- function sessionIsAttached(ctx, sessionId) {
243
- try {
244
- const sessions = ctx.get("sessions");
245
- return sessions?.get?.(sessionId) !== undefined;
246
- } catch {
247
- return false;
248
- }
249
- }
250
-
251
- /** @returns true when the tombstone ledger already records this id as deleted. */
252
- function isTombstoned(home, sessionId) {
253
- try {
254
- return readTombstones(home).some(row => row.id === sessionId);
255
- } catch {
256
- return false;
257
- }
258
- }
259
-
260
- function describeError(error) {
261
- return error instanceof Error ? error.message : String(error);
262
- }
263
-
264
- /** Resolve an optional Host service without letting a provider fault break the route. */
265
- function optionalService(ctx, name) {
266
- try {
267
- return ctx.get(name);
268
- } catch {
269
- return undefined;
270
- }
271
- }
272
-
273
- /**
274
- * Hide one Session whose artifacts are being deleted.
275
- *
276
- * DSH 0.1.5 exposes no Session-delete service, so removing the artifacts leaves a
277
- * Session this process still holds attached inside `session.list`: the sidebar row and
278
- * the transcript survive the delete. The registry-global archive set is the Host's own
279
- * "hide from every list" primitive (the stock row menu calls it "Archive"), it is
280
- * durable in `<home>/storages/workspace.json`, and the Workspace controller publishes
281
- * an `archived` frame the browser applies immediately.
282
- *
283
- * @param ctx - plugin context; the registry resolves lazily per delete.
284
- * @param sessionId - validated session id.
285
- * @returns true when the id is archived (an already archived id counts as true).
286
- */
287
- async function hideDeletedSession(ctx, sessionId) {
288
- const registry = optionalService(ctx, "workspaceRegistry");
289
- if (registry === undefined) return false;
290
- try {
291
- await registry.archiveSession(sessionId);
292
- return true;
293
- } catch (error) {
294
- /* Best effort: the artifacts still go, and a later delete finishes the job. */
295
- console.warn("gbh: could not archive session " + sessionId + ": " + describeError(error));
296
- return false;
297
- }
298
- }
299
-
300
- /**
301
- * Drop one deleted id from every Workspace's accounting.
302
- *
303
- * The Workspace registry holds the durable `sessionIds` list the sidebar groups by;
304
- * nothing prunes it on delete, so a deleted id lingers in `workspace.json` forever.
305
- *
306
- * @param ctx - plugin context; the registry resolves lazily per delete.
307
- * @param sessionId - validated session id.
308
- * @returns true when at least one Workspace dropped the id.
309
- */
310
- async function detachDeletedSession(ctx, sessionId) {
311
- const registry = optionalService(ctx, "workspaceRegistry");
312
- if (registry === undefined) return false;
313
- try {
314
- const workspaces = registry.list();
315
- let detached = false;
316
- for (const workspace of Array.isArray(workspaces) ? workspaces : []) {
317
- let sessionIds;
318
- try {
319
- sessionIds = workspace?.sessionIds;
320
- } catch {
321
- sessionIds = undefined;
322
- }
323
- if (!Array.isArray(sessionIds) || !sessionIds.includes(sessionId)) continue;
324
- await workspace.detachSession(sessionId);
325
- detached = true;
326
- }
327
- return detached;
328
- } catch (error) {
329
- console.warn("gbh: could not detach session " + sessionId + " from its workspace: " + describeError(error));
330
- return false;
331
- }
332
- }
333
-
334
- /** Cached persistence listing; a provider fault degrades to an empty listing. */
335
- async function storedSnapshots(ctx) {
336
- try {
337
- const persistence = ctx.get("sessionPersistence");
338
- if (persistence === undefined) return [];
339
- const snapshots = await persistence.list();
340
- return Array.isArray(snapshots) ? snapshots : [];
341
- } catch {
342
- return [];
343
- }
344
- }
345
-
346
- function headerOf(snapshot) {
347
- return snapshot && typeof snapshot === "object" ? snapshot.header : undefined;
348
- }
349
-
350
- /** Join the artifact inventory with the Host's session facts. */
351
- async function sessionInventory(ctx, home) {
352
- const snapshots = await storedSnapshots(ctx);
353
- const known = new Map();
354
- for (const snapshot of snapshots) {
355
- const header = headerOf(snapshot);
356
- if (header === undefined || typeof header.id !== "string") continue;
357
- known.set(header.id, {
358
- cwd: typeof header.cwd === "string" ? header.cwd : undefined,
359
- parentId: typeof header.parentSession === "string" ? header.parentSession : undefined,
360
- });
361
- }
362
- const rows = [];
363
- for (const stored of listStoredSessions(home)) {
364
- const facts = known.get(stored.id);
365
- rows.push({
366
- id: stored.id,
367
- bytes: stored.bytes,
368
- size: formatBytes(stored.bytes),
369
- updatedAt: stored.updatedAt,
370
- title: sessionTitleFromCache(home, stored.id),
371
- cwd: facts?.cwd,
372
- parentId: facts?.parentId,
373
- running: sessionIsRunning(ctx, stored.id),
374
- attached: sessionIsAttached(ctx, stored.id),
375
- });
376
- }
377
- return { home, sessions: rows };
378
- }
379
-
380
- /** Delete one stored session after the guards the UI relies on. */
381
- async function removeStoredSession(ctx, home, sessionId, options = {}) {
382
- if (!isSessionId(sessionId)) {
383
- return { status: 400, body: { ok: false, code: "invalid-request", message: "Invalid session id." } };
384
- }
385
- const snapshots = await storedSnapshots(ctx);
386
- const known = new Set();
387
- const children = [];
388
- for (const snapshot of snapshots) {
389
- const header = headerOf(snapshot);
390
- if (header === undefined || typeof header.id !== "string") continue;
391
- known.add(header.id);
392
- if (header.parentSession === sessionId) children.push(header.id);
393
- }
394
- const directories = findSessionDirectories(home, sessionId);
395
- if (!known.has(sessionId) && directories.length === 0) {
396
- /* Nothing is stored under this home, yet the id can still reach this route: the
397
- runtime may hold the Session attached, the Workspace registry may still account for
398
- it, or an earlier delete already tombstoned it. Clean every one of those and answer
399
- success — the caller's intent ("make this session gone") is already satisfiable, and
400
- "does not exist" is a dead end the UI cannot act on. */
401
- const wasRecorded = isTombstoned(home, sessionId);
402
- const hidden = sessionIsAttached(ctx, sessionId) && (await hideDeletedSession(ctx, sessionId)) ? [sessionId] : [];
403
- const detached = (await detachDeletedSession(ctx, sessionId)) ? [sessionId] : [];
404
- let projectionCache = false;
405
- try {
406
- /* Also records the tombstone, so a live runtime that flushes this id later is swept. */
407
- projectionCache = deleteSession(home, sessionId, { trash: options.trash !== false }).projectionCache;
408
- } catch (error) {
409
- return { status: 500, body: { ok: false, code: "session/delete-failed", message: describeError(error) } };
410
- }
411
- return {
412
- status: 200,
413
- body: {
414
- ok: true,
415
- alreadyDeleted: wasRecorded,
416
- /* False only when this id left no trace here at all: no artifact, no tombstone,
417
- nothing attached, no Workspace accounting. */
418
- found: wasRecorded || hidden.length > 0 || detached.length > 0,
419
- deleted: [],
420
- cascaded: [],
421
- hidden,
422
- detached,
423
- projectionCache,
424
- },
425
- };
426
- }
427
- if (sessionIsRunning(ctx, sessionId)) {
428
- return {
429
- status: 409,
430
- body: { ok: false, code: "session/running", message: "Session " + sessionId + " is running; stop it before deleting." },
431
- };
432
- }
433
- if (children.length > 0 && options.cascade !== true) {
434
- return {
435
- status: 409,
436
- body: {
437
- ok: false,
438
- code: "session/has-children",
439
- message: "Session " + sessionId + " has " + children.length + " descendant session(s).",
440
- children,
441
- },
442
- };
443
- }
444
- const targets = options.cascade === true && children.length > 0 ? [...children, sessionId] : [sessionId];
445
- /* Hide every target this process still holds attached before unlinking it: such a
446
- Session keeps its row in every list (and its transcript readable) without files. */
447
- const hidden = [];
448
- for (const target of targets) {
449
- if (!sessionIsAttached(ctx, target)) continue;
450
- if (await hideDeletedSession(ctx, target)) hidden.push(target);
451
- }
452
- const removed = [];
453
- try {
454
- for (const target of targets) {
455
- const result = deleteSession(home, target, { trash: options.trash !== false });
456
- removed.push({ id: target, bytes: result.bytes, trashedTo: result.trashedTo, projectionCache: result.projectionCache });
457
- }
458
- } catch (error) {
459
- return {
460
- status: 500,
461
- body: { ok: false, code: "session/delete-failed", message: describeError(error) },
462
- };
463
- }
464
- /* The artifact is gone; drop the id from the durable Workspace accounting so
465
- `workspace.json` stops listing a Session that no longer exists. */
466
- const detached = [];
467
- for (const target of targets) {
468
- if (await detachDeletedSession(ctx, target)) detached.push(target);
469
- }
470
- return {
471
- status: 200,
472
- body: {
473
- ok: true,
474
- alreadyDeleted: false,
475
- found: true,
476
- deleted: removed,
477
- cascaded: options.cascade === true ? children : [],
478
- hidden,
479
- detached,
480
- },
481
- };
482
- }
483
-
484
- /**
485
- * Register the Galaxy session routes on the Host connection carrier.
486
- *
487
- * @param ctx - plugin context, used to reach the Session services lazily per request.
488
- * @param connectionCtx - the injected connection scope that owns route registration.
489
- */
490
- /*
491
- * The optional features a profile can add. Both ship with this DSH but stay out of the composition until the
492
- * owner asks for them, and the only place DSH records that is `dsh.profile.bundles` in a profile's package.json.
493
- */
494
- const FEATURES_PATH = "/api/galaxy/features";
495
- const GBH_FEATURE_BUNDLES = [
496
- { id: "agentTeams", name: "@deepseek-ai/dsh-experimental-agent-team-profile" },
497
- { id: "automationTasks", name: "@deepseek-ai/dsh-experimental-schedule-bundle" },
498
- ];
499
-
500
- /** Every profile this home holds. Normally one, the `web` profile this GUI is served from. */
501
- function profileFiles(home) {
502
- const root = join(home, "profiles");
503
- if (!existsSync(root)) return [];
504
- return readdirSync(root).map(name => join(root, name, "package.json")).filter(existsSync);
505
- }
506
-
507
- /** Which optional features the profiles have turned on. Absent means off, which is the shipped default. */
508
- function readFeatureState(home) {
509
- const state = {};
510
- for (const feature of GBH_FEATURE_BUNDLES) state[feature.id] = false;
511
- for (const file of profileFiles(home)) {
512
- let parsed;
513
- try { parsed = JSON.parse(readFileSync(file, "utf8")); } catch { continue; }
514
- const bundles = parsed?.dsh?.profile?.bundles;
515
- if (!Array.isArray(bundles)) continue;
516
- for (const feature of GBH_FEATURE_BUNDLES) if (bundles.includes(feature.name)) state[feature.id] = true;
517
- }
518
- return state;
519
- }
520
-
521
- /** Turn the requested features on or off, and report how many profiles changed. */
522
- function writeFeatureState(home, wanted) {
523
- let touched = 0;
524
- for (const file of profileFiles(home)) {
525
- let parsed;
526
- try { parsed = JSON.parse(readFileSync(file, "utf8")); } catch { continue; }
527
- const profile = parsed?.dsh?.profile;
528
- if (profile === undefined || !Array.isArray(profile.bundles)) continue;
529
- let changed = false;
530
- for (const feature of GBH_FEATURE_BUNDLES) {
531
- const want = wanted?.[feature.id];
532
- if (typeof want !== "boolean" || want === profile.bundles.includes(feature.name)) continue;
533
- profile.bundles = want
534
- ? [...profile.bundles, feature.name]
535
- : profile.bundles.filter(name => name !== feature.name);
536
- changed = true;
537
- }
538
- if (!changed) continue;
539
- writeFileSync(file, JSON.stringify(parsed, null, 2) + "\n", "utf8");
540
- touched += 1;
541
- }
542
- return touched;
543
- }
544
-
545
- function registerFeatureRoutes(ctx, connectionCtx) {
546
- const home = resolveHome();
547
- connectionCtx.connection.fetch.register({
548
- path: FEATURES_PATH,
549
- methods: ["GET", "POST"],
550
- requestBody: "buffered",
551
- fetch: async (request) => {
552
- if (request.method !== "POST") return jsonResponse({ features: readFeatureState(home) });
553
- let body = {};
554
- try { body = JSON.parse(await request.text()); } catch { body = {}; }
555
- const touched = writeFeatureState(home, body?.features);
556
- return jsonResponse({ features: readFeatureState(home), profiles: touched });
557
- },
558
- });
559
- }
560
-
561
- function registerSessionRoutes(ctx, connectionCtx) {
562
- const home = resolveHome();
563
- try {
564
- const swept = sweepTombstones(home);
565
- if (swept.resurrected.length > 0) {
566
- console.log("gbh: removed " + swept.resurrected.length + " session artifact(s) a live runtime re-created: " + swept.resurrected.join(", "));
567
- }
568
- } catch (error) {
569
- console.warn("gbh: session tombstone sweep failed: " + (error instanceof Error ? error.message : String(error)));
570
- }
571
- connectionCtx.connection.fetch.register({
572
- path: SESSIONS_PATH,
573
- methods: ["GET", "HEAD"],
574
- requestBody: "buffered",
575
- fetch: async (request) => {
576
- const inventory = await sessionInventory(ctx, home);
577
- const response = jsonResponse(inventory);
578
- if (request.method === "GET") return response;
579
- await response.body?.cancel();
580
- return new Response(null, { status: response.status, headers: response.headers });
581
- },
582
- });
583
- connectionCtx.connection.fetch.register({
584
- path: SESSION_DELETE_PATH,
585
- methods: ["POST"],
586
- requestBody: "buffered",
587
- fetch: async (request) => {
588
- let payload;
589
- try {
590
- payload = await request.json();
591
- } catch {
592
- return jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
593
- }
594
- const sessionId = payload && typeof payload.sessionId === "string" ? payload.sessionId : "";
595
- const result = await removeStoredSession(ctx, home, sessionId, {
596
- cascade: payload?.cascade === true,
597
- trash: payload?.trash !== false,
598
- });
599
- return jsonResponse(result.body, result.status);
600
- },
601
- });
602
- }
603
- //#endregion
604
-
605
- //#region update routes
606
- /** Browser routes that report versions and run the CLI's own npm upgrade. */
607
- const UPDATE_VERSION_PATH = "/api/galaxy/version";
608
- const UPDATE_RUN_PATH = "/api/galaxy/update";
609
- const UPDATE_PROGRESS_PATH = "/api/galaxy/update.progress";
610
- const UPDATE_PACKAGE = "@galaxy-stack/blackhole-cli";
611
- let updateVersionCache = { at: 0, latest: undefined };
612
- let updateRunState;
613
-
614
- /** True when `candidate` is strictly newer than `current` (x.y.z, pre-releases ignored). */
615
- function updateIsNewer(candidate, current) {
616
- const parse = (value) => String(value).trim().replace(/^v/, "").split("-")[0].split(".").map((part) => Number.parseInt(part, 10) || 0);
617
- const left = parse(candidate);
618
- const right = parse(current);
619
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
620
- const a = left[index] ?? 0;
621
- const b = right[index] ?? 0;
622
- if (a !== b) return a > b;
623
- }
624
- return false;
625
- }
626
-
627
- /** Newest published version, cached for six hours; an offline machine simply reports none. */
628
- async function updateLatestVersion() {
629
- if (updateVersionCache.latest !== undefined && Date.now() - updateVersionCache.at < 6 * 3600_000) return updateVersionCache.latest;
630
- const output = await new Promise((resolve) => {
631
- let text = "";
632
- try {
633
- const child = spawn("npm", ["view", UPDATE_PACKAGE, "version"], { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
634
- const timer = setTimeout(() => child.kill("SIGTERM"), 8000);
635
- child.stdout.on("data", (chunk) => { text += String(chunk); });
636
- child.stderr.on("data", (chunk) => { text += String(chunk); });
637
- child.once("close", () => { clearTimeout(timer); resolve(text); });
638
- child.once("error", () => { clearTimeout(timer); resolve(""); });
639
- } catch {
640
- resolve("");
641
- }
642
- });
643
- const latest = output.trim().split("\n").pop().trim();
644
- updateVersionCache = { at: Date.now(), latest: /^\d+\.\d+\.\d+/.test(latest) ? latest : undefined };
645
- return updateVersionCache.latest;
646
- }
647
-
648
- /** Start `npm install -g` once and follow it; the browser polls the percentage. */
649
- function updateStart() {
650
- if (updateRunState !== undefined && updateRunState.done !== true) return updateRunState;
651
- const state = { pct: 5, line: "đang bắt đầu", done: false, ok: false, startedAt: Date.now() };
652
- updateRunState = state;
653
- const absorb = (chunk) => {
654
- for (const raw of String(chunk).split("\n")) {
655
- const line = raw.trim();
656
- if (line.length === 0) continue;
657
- state.line = line.slice(0, 140);
658
- if (/reify|idealTree|audit/i.test(line)) state.pct = Math.max(state.pct, 55);
659
- if (/added \d+ package|changed \d+ package|up to date/i.test(line)) state.pct = Math.max(state.pct, 95);
660
- }
661
- };
662
- try {
663
- const child = spawn("npm", ["install", "-g", UPDATE_PACKAGE + "@latest"], { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
664
- child.stdout.on("data", absorb);
665
- child.stderr.on("data", absorb);
666
- const ticker = setInterval(() => {
667
- state.pct = Math.min(90, Math.max(state.pct, 5 + Math.round(((Date.now() - state.startedAt) / 30_000) * 60)));
668
- }, 500);
669
- ticker.unref?.();
670
- child.once("close", (code) => {
671
- clearInterval(ticker);
672
- state.pct = 100;
673
- state.ok = code === 0;
674
- state.done = true;
675
- if (!state.ok) state.line = "npm thoát với mã " + String(code);
676
- });
677
- child.once("error", (error) => {
678
- clearInterval(ticker);
679
- state.pct = 100;
680
- state.ok = false;
681
- state.done = true;
682
- state.line = String(error instanceof Error ? error.message : error).slice(0, 140);
683
- });
684
- } catch (error) {
685
- state.pct = 100;
686
- state.ok = false;
687
- state.done = true;
688
- state.line = String(error instanceof Error ? error.message : error).slice(0, 140);
689
- }
690
- return state;
691
- }
692
-
693
- function registerUpdateRoutes(ctx, connectionCtx) {
694
- connectionCtx.connection.fetch.register({
695
- path: UPDATE_VERSION_PATH,
696
- methods: ["GET"],
697
- requestBody: "buffered",
698
- fetch: async (request) => {
699
- const current = new URL(request.url).searchParams.get("current") ?? "";
700
- const latest = await updateLatestVersion();
701
- return jsonResponse({
702
- current,
703
- latest: latest ?? null,
704
- hasUpdate: latest !== undefined && current.length > 0 && updateIsNewer(latest, current),
705
- });
706
- },
707
- });
708
- connectionCtx.connection.fetch.register({
709
- path: UPDATE_RUN_PATH,
710
- methods: ["POST"],
711
- requestBody: "buffered",
712
- fetch: async () => {
713
- const state = updateStart();
714
- return jsonResponse({ ok: true, pct: state.pct, line: state.line });
715
- },
716
- });
717
- connectionCtx.connection.fetch.register({
718
- path: UPDATE_PROGRESS_PATH,
719
- methods: ["GET"],
720
- requestBody: "buffered",
721
- fetch: async () => updateRunState === undefined
722
- ? jsonResponse({ pct: 0, line: "", done: false, ok: false })
723
- : jsonResponse({ pct: updateRunState.pct, line: updateRunState.line, done: updateRunState.done, ok: updateRunState.ok }),
724
- });
725
- }
726
- //#endregion
727
-
728
- //#region journey blueprint routes
729
- /** Browser routes owned by the Galaxy journey panel. */
730
- const JOURNEY_PATH = "/api/galaxy/journey";
731
-
732
- /** Workspace root of one session, resolved from the trusted persistence record. */
733
- async function sessionWorkspaceRoot(ctx, sessionId) {
734
- try {
735
- const persistence = ctx.get("sessionPersistence");
736
- if (persistence === undefined) return undefined;
737
- const snapshot = await persistence.stat(sessionId);
738
- const cwd = snapshot?.header?.cwd;
739
- if (typeof cwd === "string" && cwd.length > 0) return cwd;
740
- const snapshots = await persistence.list();
741
- for (const row of Array.isArray(snapshots) ? snapshots : []) {
742
- if (row?.header?.id === sessionId && typeof row.header.cwd === "string") return row.header.cwd;
743
- }
744
- return undefined;
745
- } catch {
746
- return undefined;
747
- }
748
- }
749
-
750
- /** Append one journey mutation to the local audit ledger; never fails the request. */
751
- function appendJourneyAudit(entry) {
752
- try {
753
- const directory = join(resolveHome(), "journey");
754
- mkdirSync(directory, { recursive: true });
755
- appendFileSync(join(directory, "history.jsonl"), JSON.stringify(entry) + "\n", { encoding: "utf8", mode: 0o600 });
756
- } catch {
757
- /* the audit ledger is best effort */
758
- }
759
- }
760
-
761
- /** Register the Galaxy journey routes on the Host connection carrier. */
762
- function registerJourneyRoutes(ctx, connectionCtx) {
763
- /* One registration per path: the Host registry refuses a second one for the same path. */
764
- connectionCtx.connection.fetch.register({
765
- path: JOURNEY_PATH,
766
- methods: ["GET", "HEAD", "POST"],
767
- requestBody: "buffered",
768
- fetch: async (request) => {
769
- if (request.method === "POST") return handleJourneyWrite(ctx, request);
770
- const url = new URL(request.url);
771
- const sessionId = url.searchParams.get("sessionId") ?? "";
772
- const root = await sessionWorkspaceRoot(ctx, sessionId);
773
- if (root === undefined) {
774
- return jsonResponse({ ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." }, 409);
775
- }
776
- let path;
777
- try {
778
- path = blueprintPathFor(root);
779
- } catch (error) {
780
- return jsonResponse({ ok: false, code: "journey/no-workspace", message: error instanceof Error ? error.message : String(error) }, 409);
781
- }
782
- const blueprint = readBlueprint(root);
783
- if (blueprint.parseError !== undefined) {
784
- return jsonResponse({ ok: false, code: "journey/unparsable", path, message: "journey.json is not valid JSON: " + blueprint.parseError }, 422);
785
- }
786
- const body = {
787
- ok: true,
788
- path,
789
- workspaceRoot: root,
790
- exists: blueprint.exists,
791
- revision: typeof blueprint.document?.revision === "number" ? blueprint.document.revision : 0,
792
- hash: blueprint.hash,
793
- document: blueprint.document,
794
- issues: validateBlueprint(blueprint.document),
795
- };
796
- const response = jsonResponse(body);
797
- if (request.method === "GET") return response;
798
- await response.body?.cancel();
799
- return new Response(null, { status: response.status, headers: response.headers });
800
- },
801
- });
802
- }
803
-
804
- /** Append one feedback remark to the session log, audited locally. */
805
- async function handleFeedbackWrite(ctx, request) {
806
- let payload;
807
- try {
808
- payload = await request.json();
809
- } catch {
810
- return jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
811
- }
812
- const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
813
- const text = typeof payload?.text === "string" ? payload.text.trim() : "";
814
- const category = typeof payload?.category === "string" ? payload.category : "";
815
- if (text.length === 0) {
816
- return jsonResponse({ ok: false, code: "invalid-request", message: "Feedback text is required." }, 400);
817
- }
818
- let session;
819
- try {
820
- const sessions = ctx.get("sessions");
821
- session = sessions?.get?.(sessionId);
822
- } catch {
823
- session = undefined;
824
- }
825
- if (session === undefined || typeof session.append !== "function") {
826
- return jsonResponse({ ok: false, code: "feedback/no-session", message: "This session is not live in this runtime." }, 409);
827
- }
828
- try {
829
- session.append("feedback/record", {
830
- text,
831
- ...(category.length === 0 ? {} : { category }),
832
- });
833
- } catch (error) {
834
- return jsonResponse({ ok: false, code: "feedback/append-failed", message: error instanceof Error ? error.message : String(error) }, 500);
835
- }
836
- try {
837
- const directory = join(resolveHome(), "feedback");
838
- mkdirSync(directory, { recursive: true });
839
- appendFileSync(join(directory, "history.jsonl"), JSON.stringify({ at: new Date().toISOString(), sessionId, category, text }) + "\n", { encoding: "utf8", mode: 0o600 });
840
- } catch {
841
- /* the audit ledger is best effort */
842
- }
843
- return jsonResponse({ ok: true, sessionId, category });
844
- }
845
-
846
- /** One blueprint write: validate, compare-and-swap, audit. */
847
- async function handleJourneyWrite(ctx, request) {
848
- let payload;
849
- try {
850
- payload = await request.json();
851
- } catch {
852
- return jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
853
- }
854
- const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
855
- const root = await sessionWorkspaceRoot(ctx, sessionId);
856
- if (root === undefined) {
857
- return jsonResponse({ ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." }, 409);
858
- }
859
- const document = payload?.document;
860
- if (document === null || typeof document !== "object") {
861
- return jsonResponse({ ok: false, code: "invalid-request", message: "document is required." }, 400);
862
- }
863
- const expectedRevision = typeof payload?.expectedRevision === "number" ? payload.expectedRevision : undefined;
864
- const updatedBy = payload?.updatedBy === "agent" ? "agent" : "human";
865
- const result = writeBlueprint(root, document, {
866
- ...(expectedRevision === undefined ? {} : { expectedRevision }),
867
- updatedBy,
868
- });
869
- if (result.ok !== true) {
870
- return jsonResponse(result, result.code === "journey/conflict" ? 409 : 422);
871
- }
872
- appendJourneyAudit({ at: new Date().toISOString(), sessionId, path: result.path, revision: result.revision, hash: result.hash, updatedBy });
873
- return jsonResponse({ ok: true, revision: result.revision, hash: result.hash, path: result.path });
874
- }
875
- //#endregion
876
-
877
- //#region installed-app identity
878
- /**
879
- * The shipped web-app manifest names the product "DeepSeek Harness" and draws its icon
880
- * from the DSH favicon, so Chrome's install offer and the installed app window wear the
881
- * upstream identity — the overlay rebrands the page but not that file. Serving our own
882
- * manifest and icons on the same paths keeps the installable app while making the name,
883
- * the window title and the dock icon say Galaxy Blackhole.
884
- */
885
- const MANIFEST_PATH = "/manifest.webmanifest";
886
- const APP_ICON_192_PATH = "/gbh-app-icon-192.png";
887
- const APP_ICON_512_PATH = "/gbh-app-icon-512.png";
888
- const APP_MANIFEST = {
889
- id: "/",
890
- name: "Galaxy Blackhole",
891
- /* Chrome shows `name` in the app window/title and `short_name` where space is tight. */
892
- short_name: "Galaxy Blackhole",
893
- description: "Galaxy Blackhole — the Galaxy AI coding stack in the browser.",
894
- start_url: "/",
895
- scope: "/",
896
- display: "standalone",
897
- background_color: "#0b0a14",
898
- theme_color: "#0b0a14",
899
- icons: [
900
- { src: APP_ICON_192_PATH, sizes: "192x192", type: "image/png", purpose: "any" },
901
- { src: APP_ICON_512_PATH, sizes: "512x512", type: "image/png", purpose: "any" },
902
- ],
903
- };
904
- /** The manifest icons the build script baked into the plugin. */
905
- const APP_ICONS = [
906
- [APP_ICON_192_PATH, APP_ICON_192_DATA_URI],
907
- [APP_ICON_512_PATH, APP_ICON_512_DATA_URI],
908
- ];
909
-
910
- /** Decode one generated `data:…;base64,…` asset into the bytes a route returns. */
911
- function dataUriBytes(dataUri) {
912
- const comma = dataUri.indexOf(",");
913
- return Buffer.from(comma === -1 ? "" : dataUri.slice(comma + 1), "base64");
914
- }
915
-
916
- /** Answer one whole-response route with a fixed body and its own caching policy. */
917
- function sendBody(request, response, contentType, body, cacheControl) {
918
- if (request.method !== "GET" && request.method !== "HEAD") {
919
- response.writeHead(405, { allow: "GET, HEAD" });
920
- response.end();
921
- return;
922
- }
923
- response.writeHead(200, {
924
- "content-type": contentType,
925
- "content-length": body.length,
926
- "cache-control": cacheControl,
927
- });
928
- if (request.method === "HEAD") {
929
- response.end();
930
- return;
931
- }
932
- response.end(body);
933
- }
934
-
935
- /**
936
- * Serve the Galaxy app identity on the paths the shipped index already links.
937
- *
938
- * @param hostCtx - the injected webServer scope owning route registration.
939
- */
940
- function registerAppIdentity(hostCtx) {
941
- const manifest = Buffer.from(JSON.stringify(APP_MANIFEST, null, 2) + "\n", "utf8");
942
- hostCtx.effect(
943
- () => hostCtx.webServer.register({
944
- kind: "exact",
945
- path: MANIFEST_PATH,
946
- handler: (request, response) => sendBody(request, response, "application/manifest+json; charset=utf-8", manifest, "no-cache"),
947
- }),
948
- "gbh-brand: app manifest",
949
- );
950
- for (const [path, dataUri] of APP_ICONS) {
951
- const body = dataUriBytes(dataUri);
952
- hostCtx.effect(
953
- () => hostCtx.webServer.register({
954
- kind: "exact",
955
- path,
956
- handler: (request, response) => sendBody(request, response, "image/png", body, "public, max-age=86400"),
957
- }),
958
- "gbh-brand: app icon " + path,
959
- );
960
- }
961
- }
962
- //#endregion
963
-
964
- //#region galaxy feedback route
965
- /** Browser route owned by the Galaxy feedback settings section. */
966
- const FEEDBACK_PATH = "/api/galaxy/feedback";
967
- /** The taxonomy the stock feedback surface defined; kept as durable log vocabulary. */
968
- const FEEDBACK_CATEGORIES = [
969
- "task-result",
970
- "instruction-following",
971
- "product-interaction",
972
- "service-stability",
973
- "resource-cost",
974
- "security-privacy-permission",
975
- "other",
976
- ];
977
-
978
- /**
979
- * Record one remark as the session's own \`feedback/record\` event.
980
- *
981
- * The stock command and dialog are disabled in this profile, so the Galaxy settings
982
- * section is the only producer; appending through the live Session keeps the event
983
- * type, the log placement, and the audit trail identical to the stock behaviour.
984
- */
985
- function registerFeedbackRoute(ctx, connectionCtx) {
986
- connectionCtx.connection.fetch.register({
987
- path: FEEDBACK_PATH,
988
- methods: ["POST"],
989
- requestBody: "buffered",
990
- fetch: async request => {
991
- let payload;
992
- try {
993
- payload = await request.json();
994
- } catch {
995
- return jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
996
- }
997
- const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
998
- const text = typeof payload?.text === "string" ? payload.text.trim().slice(0, 4000) : "";
999
- const category = typeof payload?.category === "string" ? payload.category : undefined;
1000
- if (text.length === 0) return jsonResponse({ ok: false, code: "feedback/empty", message: "Feedback text is required." }, 400);
1001
- if (category !== undefined && !FEEDBACK_CATEGORIES.includes(category)) {
1002
- return jsonResponse({ ok: false, code: "feedback/category", message: "Unknown feedback category." }, 400);
1003
- }
1004
- let session;
1005
- try {
1006
- session = ctx.get("sessions")?.get?.(sessionId);
1007
- } catch {
1008
- session = undefined;
1009
- }
1010
- if (session === undefined) {
1011
- return jsonResponse({ ok: false, code: "feedback/no-session", message: "This session is not attached to the runtime." }, 409);
1012
- }
1013
- try {
1014
- session.append("feedback/record", { text, ...(category === undefined ? {} : { category }) });
1015
- } catch (error) {
1016
- return jsonResponse({ ok: false, code: "feedback/append-failed", message: error instanceof Error ? error.message : String(error) }, 500);
1017
- }
1018
- return jsonResponse({ ok: true, recorded: true });
1019
- },
1020
- });
1021
- }
1022
- //#endregion
1023
-
1024
- /** The system-prompt registry owns the section this plugin rewrites. */
1025
- export const inject = ["systemPrompt"];
1026
-
1027
- function apply(ctx) {
1028
- ctx.on("system-prompt/assemble", async (assembly, _context, next) => {
1029
- const sections = assembly?.sections;
1030
- if (Array.isArray(sections)) {
1031
- for (const section of sections) {
1032
- if (section?.name === IDENTITY_SECTION) section.text = IDENTITY_TEXT;
1033
- if (section?.name === PERSONA_SECTION) section.text = PERSONA_TEXT;
1034
- }
1035
- }
1036
- return next();
1037
- });
1038
- ctx.inject(["web"], (webCtx) => webCtx.web.registerSearchProvider(createGalaxySearchProvider()));
1039
- ctx.inject(["connection"], (connectionCtx) => registerSessionRoutes(ctx, connectionCtx));
1040
- ctx.inject(["connection"], (connectionCtx) => registerFeatureRoutes(ctx, connectionCtx));
1041
- ctx.inject(["connection"], (connectionCtx) => registerJourneyRoutes(ctx, connectionCtx));
1042
- ctx.inject(["connection"], (connectionCtx) => registerUpdateRoutes(ctx, connectionCtx));
1043
- ctx.inject(["connection"], (connectionCtx) => {
1044
- connectionCtx.connection.fetch.register({
1045
- path: "/api/galaxy/feedback",
1046
- methods: ["POST"],
1047
- requestBody: "buffered",
1048
- fetch: request => handleFeedbackWrite(ctx, request),
1049
- });
1050
- });
1051
- ctx.inject(["connection"], (connectionCtx) => registerFeedbackRoute(ctx, connectionCtx));
1052
- /* Run route, agent tools, and the /journey command all share this host's helpers. */
1053
- registerJourneyHost({ ctx, jsonResponse, sessionWorkspaceRoot, appendJourneyAudit });
1054
- ctx.inject(["webServer"], (hostCtx) => {
1055
- hostCtx.on("webserver/index-inject", (table) => {
1056
- table.push({ kind: "script", placement: "body", text: FAVICON_SCRIPT });
1057
- table.push({ kind: "script", placement: "body", text: HIDE_UI_SCRIPT });
1058
- table.push({ kind: "script", placement: "body", text: TITLE_SCRIPT });
1059
- table.push({ kind: "script", placement: "body", text: TEXT_FIX_SCRIPT });
1060
- table.push({ kind: "global", name: "__GBH_HAS_KEY__", value: (process.env.GBH_GALAXY_API_KEY ?? "").length > 0 });
1061
- });
1062
- /* The install stays available, wearing the Galaxy name and icon instead of the
1063
- shipped "DeepSeek Harness" manifest. */
1064
- registerAppIdentity(hostCtx);
1065
- });
1066
- }
1067
- //#endregion
1068
- export { apply };