@galaxy-stack/blackhole-cli 2.0.0-alpha.18 → 2.0.0

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 session store maintenance
2
+ /**
3
+ * Session-store maintenance for the Galaxy overlay: enumerate the DSH session
4
+ * artifacts under \`DSH_HOME\`, delete one session durably, and sweep sessions
5
+ * that a live DSH process re-materialized after a delete.
6
+ *
7
+ * The DSH 0.1.5 persistence port exposes create/open/flush/stat/list only, so
8
+ * deletion has to happen on the artifact layout instead of a service call. The
9
+ * layout this module owns is:
10
+ *
11
+ * <home>/sessions/<cwd-slug>/<sessionId>/session.v<N>.jsonl.zstd
12
+ * <home>/sessions/<cwd-slug>/<sessionId>/session.lock
13
+ * <home>/storages/session_projcache/sessions/<sessionId>.json
14
+ *
15
+ * Every path is derived from a validated session id and re-checked against the
16
+ * sessions root, so a crafted id can never escape it.
17
+ */
18
+ import {
19
+ existsSync,
20
+ mkdirSync,
21
+ readFileSync,
22
+ readdirSync,
23
+ renameSync,
24
+ rmSync,
25
+ statSync,
26
+ writeFileSync,
27
+ } from "node:fs";
28
+ import { homedir } from "node:os";
29
+ import { isAbsolute, join, resolve, sep } from "node:path";
30
+
31
+ /** Tombstone ledger name; kept under \`<home>/storages\`. */
32
+ export const DELETED_INDEX_NAME = "galaxy-deleted-sessions.json";
33
+ /** Session ids accepted from the wire: no separators, no traversal. */
34
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
35
+
36
+ /**
37
+ * The DSH home the running runtime actually uses. \`blackhole web\` exports it as
38
+ * DSH_HOME for the child process, so that wins over the launcher-level GBH_HOME.
39
+ *
40
+ * @param {string | undefined} explicit - \`--home\` value, when a caller already resolved one.
41
+ */
42
+ export function resolveHome(explicit) {
43
+ if (typeof explicit === "string" && explicit.trim().length > 0) return resolve(explicit.trim());
44
+ for (const name of ["DSH_HOME", "GBH_HOME"]) {
45
+ const value = process.env[name];
46
+ if (typeof value === "string" && value.trim().length > 0) return resolve(value.trim());
47
+ }
48
+ return join(homedir(), ".galaxy", "gbh");
49
+ }
50
+
51
+ /** Root of the JSONL session artifacts. @param {string} home - resolved DSH home. */
52
+ export function sessionsRoot(home) {
53
+ return join(home, "sessions");
54
+ }
55
+
56
+ /** Per-session projection cache file. */
57
+ export function projectionCachePath(home, sessionId) {
58
+ return join(home, "storages", "session_projcache", "sessions", sessionId + ".json");
59
+ }
60
+
61
+ /** Delete ledger path. */
62
+ export function deletedIndexPath(home) {
63
+ return join(home, "storages", DELETED_INDEX_NAME);
64
+ }
65
+
66
+ /** Directory a deleted session is moved into (soft delete). */
67
+ export function trashRoot(home) {
68
+ return join(home, ".trash", "sessions");
69
+ }
70
+
71
+ /** @returns true when the value may be used as a session id on the filesystem. */
72
+ export function isSessionId(value) {
73
+ return typeof value === "string" && SESSION_ID_PATTERN.test(value);
74
+ }
75
+
76
+ /** Refuse any id that could select a path outside its root. */
77
+ function requireSessionId(sessionId) {
78
+ if (!isSessionId(sessionId)) throw new Error("invalid session id: " + String(sessionId));
79
+ return sessionId;
80
+ }
81
+
82
+ function isInside(root, candidate) {
83
+ const resolvedRoot = resolve(root);
84
+ const resolved = resolve(candidate);
85
+ return resolved === resolvedRoot || resolved.startsWith(resolvedRoot + sep);
86
+ }
87
+
88
+ /**
89
+ * Every directory holding artifacts for one session id.
90
+ * @param {string} home - resolved DSH home.
91
+ * @param {string} sessionId - validated session id.
92
+ * @returns {string[]} absolute session directories.
93
+ */
94
+ export function findSessionDirectories(home, sessionId) {
95
+ requireSessionId(sessionId);
96
+ const root = sessionsRoot(home);
97
+ if (!existsSync(root)) return [];
98
+ const found = [];
99
+ for (const slug of readdirSync(root)) {
100
+ const candidate = join(root, slug, sessionId);
101
+ if (!isInside(root, candidate)) continue;
102
+ try {
103
+ if (statSync(candidate).isDirectory()) found.push(candidate);
104
+ } catch {
105
+ /* a concurrent delete wins */
106
+ }
107
+ }
108
+ return found;
109
+ }
110
+
111
+ function artifactBytes(directory) {
112
+ let bytes = 0;
113
+ try {
114
+ for (const entry of readdirSync(directory)) {
115
+ try {
116
+ bytes += statSync(join(directory, entry)).size;
117
+ } catch {
118
+ /* lock files may vanish */
119
+ }
120
+ }
121
+ } catch {
122
+ /* an unreadable directory reports zero bytes */
123
+ }
124
+ return bytes;
125
+ }
126
+
127
+ /**
128
+ * Every session artifact on disk, newest first.
129
+ * @param {string} home - resolved DSH home.
130
+ * @returns {{ id: string, directory: string, bytes: number, updatedAt: number }[]} one row per session id.
131
+ */
132
+ export function listStoredSessions(home) {
133
+ const root = sessionsRoot(home);
134
+ if (!existsSync(root)) return [];
135
+ const rows = new Map();
136
+ for (const slug of readdirSync(root)) {
137
+ const slugDir = join(root, slug);
138
+ let ids;
139
+ try {
140
+ ids = readdirSync(slugDir);
141
+ } catch {
142
+ continue;
143
+ }
144
+ for (const id of ids) {
145
+ if (!isSessionId(id)) continue;
146
+ const directory = join(slugDir, id);
147
+ let stats;
148
+ try {
149
+ stats = statSync(directory);
150
+ } catch {
151
+ continue;
152
+ }
153
+ if (!stats.isDirectory()) continue;
154
+ const bytes = artifactBytes(directory);
155
+ const previous = rows.get(id);
156
+ if (previous === undefined || previous.updatedAt < stats.mtimeMs) {
157
+ rows.set(id, { id, directory, cwdSlug: slug, bytes, updatedAt: stats.mtimeMs });
158
+ }
159
+ }
160
+ }
161
+ return [...rows.values()].sort((left, right) => right.updatedAt - left.updatedAt);
162
+ }
163
+
164
+ /** @returns the tombstone ledger rows, oldest first; a corrupt file reads as empty. */
165
+ export function readTombstones(home) {
166
+ const path = deletedIndexPath(home);
167
+ if (!existsSync(path)) return [];
168
+ try {
169
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
170
+ const rows = parsed && Array.isArray(parsed.sessions) ? parsed.sessions : [];
171
+ return rows
172
+ .filter(row => row && isSessionId(row.id) && typeof row.deletedAt === "string")
173
+ .map(row => ({ id: row.id, deletedAt: row.deletedAt }));
174
+ } catch {
175
+ return [];
176
+ }
177
+ }
178
+
179
+ function writeTombstones(home, rows) {
180
+ const path = deletedIndexPath(home);
181
+ mkdirSync(join(home, "storages"), { recursive: true });
182
+ const body = { unit: "galaxy-deleted-sessions", version: 1, sessions: rows };
183
+ writeFileSync(path, JSON.stringify(body, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
184
+ }
185
+
186
+ /** Record one deleted id so a later sweep removes a re-materialized artifact. */
187
+ export function recordTombstone(home, sessionId, deletedAt = new Date().toISOString()) {
188
+ requireSessionId(sessionId);
189
+ const rows = readTombstones(home).filter(row => row.id !== sessionId);
190
+ rows.push({ id: sessionId, deletedAt });
191
+ writeTombstones(home, rows);
192
+ return rows.length;
193
+ }
194
+
195
+ /**
196
+ * Delete one stored session.
197
+ *
198
+ * @param {string} home - resolved DSH home.
199
+ * @param {string} sessionId - session to delete.
200
+ * @param {{ trash?: boolean, now?: Date }} [options] - \`trash\` moves the artifacts into \`<home>/.trash/sessions\` instead of unlinking them.
201
+ * @returns {{ id: string, bytes: number, directories: string[], projectionCache: boolean, trashedTo?: string }} what was removed.
202
+ */
203
+ export function deleteSession(home, sessionId, options = {}) {
204
+ requireSessionId(sessionId);
205
+ const trash = options.trash !== false;
206
+ const now = options.now instanceof Date ? options.now : new Date();
207
+ const directories = findSessionDirectories(home, sessionId);
208
+ let projectionCache = false;
209
+ const cachePath = projectionCachePath(home, sessionId);
210
+ if (isInside(home, cachePath) && existsSync(cachePath)) {
211
+ rmSync(cachePath, { force: true });
212
+ projectionCache = true;
213
+ }
214
+ if (directories.length === 0) {
215
+ /* Nothing on disk: keep the id tombstoned so a later re-materialization is swept. */
216
+ recordTombstone(home, sessionId, now.toISOString());
217
+ return { id: sessionId, bytes: 0, directories: [], projectionCache };
218
+ }
219
+ let bytes = 0;
220
+ for (const directory of directories) bytes += artifactBytes(directory);
221
+ if (!trash) {
222
+ for (const directory of directories) rmSync(directory, { recursive: true, force: true });
223
+ recordTombstone(home, sessionId, now.toISOString());
224
+ return { id: sessionId, bytes, directories, projectionCache };
225
+ }
226
+ const stamp = now.toISOString().replace(/[:.]/g, "-");
227
+ const target = join(trashRoot(home), sessionId + "." + stamp);
228
+ if (!isInside(join(home, ".trash"), target)) throw new Error("refusing to trash outside the trash root");
229
+ mkdirSync(join(trashRoot(home)), { recursive: true });
230
+ for (const directory of directories) {
231
+ const destination = directories.length === 1 ? target : target + "-" + directories.indexOf(directory);
232
+ try {
233
+ renameSync(directory, destination);
234
+ } catch (error) {
235
+ throw new Error("could not move " + directory + " to the trash: " + (error instanceof Error ? error.message : String(error)));
236
+ }
237
+ }
238
+ recordTombstone(home, sessionId, now.toISOString());
239
+ return { id: sessionId, bytes, directories, projectionCache, trashedTo: target };
240
+ }
241
+
242
+ /**
243
+ * Remove artifacts a still-running DSH process re-materialized for an id the
244
+ * user already deleted, and prune expired tombstones.
245
+ *
246
+ * @param {string} home - resolved DSH home.
247
+ * @param {{ maxAgeDays?: number, now?: Date }} [options] - tombstone retention window.
248
+ * @returns {{ resurrected: string[], pruned: string[], kept: number }} sweep report.
249
+ */
250
+ export function sweepTombstones(home, options = {}) {
251
+ const maxAgeDays = Number.isFinite(options.maxAgeDays) && options.maxAgeDays > 0 ? options.maxAgeDays : 30;
252
+ const now = options.now instanceof Date ? options.now : new Date();
253
+ const rows = readTombstones(home);
254
+ const resurrected = [];
255
+ const pruned = [];
256
+ const kept = [];
257
+ for (const row of rows) {
258
+ const age = now.getTime() - Date.parse(row.deletedAt);
259
+ if (Number.isFinite(age) && age > maxAgeDays * 24 * 60 * 60 * 1000) {
260
+ pruned.push(row.id);
261
+ continue;
262
+ }
263
+ const directories = findSessionDirectories(home, row.id);
264
+ if (directories.length > 0) {
265
+ for (const directory of directories) rmSync(directory, { recursive: true, force: true });
266
+ const cachePath = projectionCachePath(home, row.id);
267
+ if (existsSync(cachePath)) rmSync(cachePath, { force: true });
268
+ resurrected.push(row.id);
269
+ }
270
+ kept.push(row);
271
+ }
272
+ if (resurrected.length > 0 || pruned.length > 0) writeTombstones(home, kept);
273
+ return { resurrected, pruned, kept: kept.length };
274
+ }
275
+
276
+ /** @returns a human-readable byte count. */
277
+ export function formatBytes(bytes) {
278
+ if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
279
+ const units = ["B", "KB", "MB", "GB"];
280
+ let value = bytes;
281
+ let unit = 0;
282
+ while (value >= 1024 && unit < units.length - 1) {
283
+ value /= 1024;
284
+ unit += 1;
285
+ }
286
+ return (unit === 0 ? String(value) : value.toFixed(1)) + " " + units[unit];
287
+ }
288
+ //#endregion
@@ -84,7 +84,8 @@
84
84
  "connection.connecting": "Đang kết nối lại",
85
85
  "connection.connected": "Đã kết nối",
86
86
  "connection.reconnect": "Mất kết nối, kết nối lại ngay",
87
- "connection.restart": "Đang kết nối lại, kết nối lại ngay"
87
+ "connection.restart": "Đang kết nối lại, kết nối lại ngay",
88
+ "connection.retry": "Kết nối lại ngay"
88
89
  },
89
90
  "command": {
90
91
  "section.add": "Thêm",
@@ -133,6 +134,7 @@
133
134
  "menu.effort": "Mức suy luận",
134
135
  "effort.providerDefault": "Mặc định",
135
136
  "status.loading": "Đang làm mới danh sách model…",
137
+ "blocked.composer": "Model này không khả dụng — hãy chọn một model để tiếp tục",
136
138
  "error.action": "Thao tác model thất bại: {message}",
137
139
  "error.sessionInUse": "Phiên này đang được dùng, có thể bởi DSH khác (dsh web hoặc desktop). Hãy thoát các DSH khác rồi thử lại.",
138
140
  "action.reload": "Tải lại",
@@ -141,7 +143,11 @@
141
143
  "empty.efforts": "Model này không cung cấp mức suy luận nào."
142
144
  },
143
145
  "approval": {
144
- "detail.aria": "Chi tiết phê duyệt"
146
+ "detail.aria": "Chi tiết phê duyệt",
147
+ "waiting": "Đang chờ phê duyệt",
148
+ "escalation": "Công cụ {toolName} yêu cầu quyền thực thi đặc biệt",
149
+ "reject": "Từ chối",
150
+ "allowOnce": "Cho phép một lần"
145
151
  },
146
152
  "conversation": {
147
153
  "access.preset.readOnly": "Chỉ đọc",
@@ -594,6 +600,8 @@
594
600
  "advancedHint": "Các trường khác nằm trong cordis.patch.yml; hãy sửa trực tiếp mục đó.",
595
601
  "modelCapacityInvalid": "Dung lượng phải là số, có thể có hậu tố K hoặc M.",
596
602
  "modelDuplicate": "Mỗi ID model chỉ được xuất hiện một lần.",
603
+ "modelContextWindow": "Cửa sổ ngữ cảnh",
604
+ "modelMaxTokens": "Token đầu ra tối đa",
597
605
  "fetchModels": "Tải model khả dụng",
598
606
  "fetching": "Đang hỏi nhà cung cấp…",
599
607
  "fetchNeedsBaseUrl": "Nhập base URL trước, rồi tải.",
@@ -605,6 +613,8 @@
605
613
  "fetchSelectAll": "Chọn tất cả",
606
614
  "fetchDeselectAll": "Bỏ chọn tất cả",
607
615
  "fetchAdopt": "Thêm mục đã chọn",
616
+ "customAdd": "Thêm nhà cung cấp tuỳ chỉnh",
617
+ "customTitle": "Nhà cung cấp tuỳ chỉnh",
608
618
  "customTag": "Tuỳ chỉnh",
609
619
  "customRoute": "ID nhà cung cấp",
610
620
  "customRouteHint": "Định danh chữ thường, bắt đầu bằng chữ cái, đặt tên duy nhất cho nhà cung cấp này trong yêu cầu và làm tên thông tin xác thực.",
@@ -716,6 +726,7 @@
716
726
  "search.pending": "Đang tìm trong lịch sử phiên…",
717
727
  "search.noMatches": "Không có phiên khớp",
718
728
  "search.hasMore": "Đang hiện {n} kết quả đầu. Hãy thu hẹp tìm kiếm.",
729
+ "search.unavailable": "Tìm kiếm nội dung tạm thời không khả dụng. Đang hiển thị kết quả theo tên.",
719
730
  "menu.addWorkspace": "Thêm workspace…",
720
731
  "picker.loading": "Đang tải workspace…",
721
732
  "conflict.named": "Đã tồn tại workspace tên “{name}”.",
@@ -781,6 +792,7 @@
781
792
  "status.compact.planReview": "Duyệt kế hoạch",
782
793
  "status.compact.answer": "Trả lời",
783
794
  "status.completed": "Hoàn thành",
795
+ "schedule.active": "Có nhắc hẹn theo lịch đang hoạt động",
784
796
  "hover.created": "Tạo lúc {time}",
785
797
  "hover.copied": "Đã sao chép",
786
798
  "date.ymd": "{y}-{m}-{d}",
@@ -985,5 +997,19 @@
985
997
  "message.turnTime.duration": "Tổng thời gian chạy",
986
998
  "message.turnTime.speed": "Token mỗi giây (TPS)",
987
999
  "message.turnTime.ttft": "Thời gian tới token đầu (TTFT)"
1000
+ },
1001
+ "gbh.sessions": {
1002
+ "action.delete": "Xoá phiên",
1003
+ "dialog.title": "Xoá phiên này?",
1004
+ "dialog.body": "Log của phiên và cache projection sẽ bị xoá khỏi DSH home. Không thể hoàn tác.",
1005
+ "dialog.trash": "Tệp được chuyển vào .trash/sessions trước, nên vẫn có thể khôi phục thủ công.",
1006
+ "dialog.cascade": "Phiên này có {count} phiên con. Xoá nó sẽ xoá luôn chúng.",
1007
+ "dialog.running": "Phiên đang chạy. Hãy dừng phiên trước khi xoá.",
1008
+ "dialog.cancel": "Huỷ",
1009
+ "dialog.confirm": "Xoá phiên",
1010
+ "dialog.confirmCascade": "Xoá {count} phiên",
1011
+ "dialog.busy": "Đang xoá…",
1012
+ "dialog.failed": "Không xoá được phiên.",
1013
+ "dialog.done": "Đã xoá phiên. Đang tải lại…"
988
1014
  }
989
1015
  }