dsh-desktop-kit 2.7.7 → 2.7.9

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,143 @@
1
+ /**
2
+ * Safe git worktrees for project agents.
3
+ *
4
+ * One task = one branch + one working directory under `.dsh/worktrees/`.
5
+ * `.dsh/worktrees/` is excluded through `.git/info/exclude` (never the user's
6
+ * tracked .gitignore), so the main worktree stays clean.
7
+ */
8
+ import { execFileSync } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+
12
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,40}$/u;
13
+
14
+ function run(cwd, args, options = {}) {
15
+ return execFileSync("git", args, {
16
+ cwd,
17
+ encoding: "utf8",
18
+ stdio: options.allowFailure ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "pipe"],
19
+ timeout: options.timeout ?? 30_000,
20
+ windowsHide: true,
21
+ }).trim();
22
+ }
23
+
24
+ function tryRun(cwd, args) {
25
+ try { return run(cwd, args); } catch { return null; }
26
+ }
27
+
28
+ export function gitRoot(cwd) {
29
+ if (!cwd) throw new Error("worktree: cwd is required");
30
+ const root = tryRun(cwd, ["rev-parse", "--show-toplevel"]);
31
+ if (!root) throw new Error(`worktree: not a git repository (${cwd})`);
32
+ return root;
33
+ }
34
+
35
+ export function validateSlug(value) {
36
+ const slug = String(value ?? "").trim();
37
+ if (!SLUG.test(slug)) throw new Error("worktree: slug must be 1–41 chars, lowercase letters/digits/hyphen");
38
+ return slug;
39
+ }
40
+
41
+ export function worktreesRoot(repo) {
42
+ return path.join(repo, ".dsh", "worktrees");
43
+ }
44
+
45
+ function ensureExcluded(repo) {
46
+ const exclude = path.join(repo, ".git", "info", "exclude");
47
+ try {
48
+ fs.mkdirSync(path.dirname(exclude), { recursive: true });
49
+ const current = fs.existsSync(exclude) ? fs.readFileSync(exclude, "utf8") : "";
50
+ if (!/^\.dsh\/worktrees\/?$/mu.test(current)) {
51
+ fs.appendFileSync(exclude, `${current.endsWith("\n") || current.length === 0 ? "" : "\n"}.dsh/worktrees/\n`, "utf8");
52
+ }
53
+ } catch {
54
+ /* best effort: a worktree inside .dsh is still usable */
55
+ }
56
+ }
57
+
58
+ export function listWorktrees({ cwd }) {
59
+ const repo = gitRoot(cwd);
60
+ const output = run(repo, ["worktree", "list", "--porcelain"]);
61
+ const records = [];
62
+ let current = {};
63
+ for (const line of output.split(/\r?\n/u)) {
64
+ if (line === "") {
65
+ if (current.path) records.push(current);
66
+ current = {};
67
+ continue;
68
+ }
69
+ const [key, ...rest] = line.split(" ");
70
+ if (key === "worktree") current.path = rest.join(" ");
71
+ else if (key === "HEAD") current.head = rest.join(" ");
72
+ else if (key === "branch") current.branch = rest.join(" ").replace(/^refs\/heads\//u, "");
73
+ else if (key === "detached") current.detached = true;
74
+ else if (key === "locked") current.locked = true;
75
+ else if (key === "prunable") current.prunable = true;
76
+ }
77
+ if (current.path) records.push(current);
78
+ const root = worktreesRoot(repo);
79
+ return records
80
+ .filter((record) => record.path === repo || record.path.startsWith(`${root}${path.sep}`) || record.branch?.startsWith("dsh/"))
81
+ .map((record) => {
82
+ const isMain = path.resolve(record.path) === path.resolve(repo);
83
+ const dirty = isMain ? null : (tryRun(record.path, ["status", "--porcelain"]) ?? "").length > 0;
84
+ return {
85
+ id: path.basename(record.path),
86
+ path: record.path,
87
+ branch: record.branch ?? null,
88
+ head: record.head ?? null,
89
+ detached: record.detached === true,
90
+ locked: record.locked === true,
91
+ prunable: record.prunable === true,
92
+ main: isMain,
93
+ dirty,
94
+ exists: fs.existsSync(record.path),
95
+ };
96
+ });
97
+ }
98
+
99
+ export function createWorktree({ cwd, slug, base }) {
100
+ const repo = gitRoot(cwd);
101
+ const name = validateSlug(slug);
102
+ ensureExcluded(repo);
103
+ const target = path.join(worktreesRoot(repo), name);
104
+ if (fs.existsSync(target)) throw new Error(`worktree: path already exists: ${target}`);
105
+ const baseRef = String(base ?? "HEAD").trim() || "HEAD";
106
+ if (!tryRun(repo, ["rev-parse", "--verify", `${baseRef}^{commit}`])) throw new Error(`worktree: base ref not found: ${baseRef}`);
107
+ const branch = `dsh/${name}`;
108
+ const branchExists = tryRun(repo, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]) !== null;
109
+ fs.mkdirSync(path.dirname(target), { recursive: true });
110
+ if (branchExists) run(repo, ["worktree", "add", target, branch]);
111
+ else run(repo, ["worktree", "add", "-b", branch, target, baseRef]);
112
+ return {
113
+ id: name,
114
+ path: target,
115
+ branch,
116
+ base: baseRef,
117
+ repo,
118
+ createdAt: new Date().toISOString(),
119
+ };
120
+ }
121
+
122
+ export function removeWorktree({ cwd, id, force = false }) {
123
+ const repo = gitRoot(cwd);
124
+ const name = validateSlug(id);
125
+ const target = path.join(worktreesRoot(repo), name);
126
+ const record = listWorktrees({ cwd: repo }).find((item) => path.resolve(item.path) === path.resolve(target));
127
+ if (!record) throw new Error(`worktree not found: ${name}`);
128
+ if (record.dirty && !force) throw new Error(`worktree is dirty: ${name}; commit/stash or pass force=true`);
129
+ if (record.locked && !force) throw new Error(`worktree is locked: ${name}`);
130
+ if (fs.existsSync(target)) run(repo, ["worktree", "remove", ...(force ? ["--force"] : []), target]);
131
+ run(repo, ["worktree", "prune"]);
132
+ return { id: name, path: target, removed: true, branchKept: record.branch };
133
+ }
134
+
135
+ export function worktreeSummary({ cwd }) {
136
+ const list = listWorktrees({ cwd });
137
+ return {
138
+ repo: gitRoot(cwd),
139
+ root: worktreesRoot(gitRoot(cwd)),
140
+ worktrees: list.filter((item) => !item.main),
141
+ main: list.find((item) => item.main) ?? null,
142
+ };
143
+ }
@@ -19,6 +19,19 @@ bundled plugins. The kit passes no services to it beyond `tools`; the
19
19
  `fs/*` hooks are event-only, which is why no `fs` injection is declared
20
20
  (the shipped `dsh-fs-observation-policy` also injects nothing).
21
21
 
22
+ ## Permissions UI
23
+
24
+ Настройки → **Права** — read-only срез эффективных разрешений:
25
+
26
+ - текущий preset DSH (`current(session)`), sandbox и approval;
27
+ - каталог всех пресетов с пометкой текущего;
28
+ - жёсткие правила kit и защищённые пути;
29
+ - явное предупреждение: смена режима — только штатным picker DSH, страница ничего не переключает и не хранит approvals.
30
+
31
+ ![Права](screenshots/permissions-1440.png)
32
+
33
+ ![Права на 390px](screenshots/permissions-390.png)
34
+
22
35
  ## Tool `guardrails`
23
36
 
24
37
  Read-only. The canonical value is lossless JSON; the rendered text is a
@@ -0,0 +1,220 @@
1
+ /**
2
+ * dsh-guardrails — Permissions settings page (read-only).
3
+ *
4
+ * The DSH permission picker remains the only way to change the mode. This page
5
+ * explains the effective preset and shows the kit's independent hard rules.
6
+ */
7
+ window.__ModuleLoader__.load({
8
+ id: "dsh-guardrails",
9
+ factory: (require) => {
10
+ var module = { exports: {} };
11
+ var exports = module.exports;
12
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
13
+ const React = require("react");
14
+ const h = React.createElement;
15
+ const useEffect = React.useEffect;
16
+ const useState = React.useState;
17
+
18
+ const CSS = `
19
+ .pr-root{--pr-line:var(--dsw-alias-border-l1,rgba(20,40,36,.13));--pr-soft:var(--dsw-alias-bg-layer-1,#f4f7f5);--pr-panel:var(--dsw-alias-bg-layer-2,#fff);--pr-text:var(--dsw-alias-label-primary,#17231f);--pr-muted:var(--dsw-alias-label-secondary,#61706b);--pr-accent:var(--dsw-alias-brand-primary,#0f766e);display:flex;flex-direction:column;gap:20px;max-width:1040px;min-width:0;color:var(--pr-text)}
20
+ .pr-head{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;flex-wrap:wrap}
21
+ .pr-eyebrow{margin:0 0 6px;font-size:11px;font-weight:700;letter-spacing:.14em;text-transform:uppercase;color:var(--pr-accent)}
22
+ .pr-title{margin:0;font-size:clamp(24px,2.6vw,32px);line-height:1.1;letter-spacing:-.025em;font-weight:680}
23
+ .pr-sub{margin:8px 0 0;max-width:68ch;color:var(--pr-muted);font-size:14px;line-height:1.5}
24
+ .pr-mode{padding:20px;border:1px solid var(--pr-line);border-radius:18px;background:linear-gradient(145deg,var(--pr-panel),var(--pr-soft));min-width:0}
25
+ .pr-mode-top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap}
26
+ .pr-mode h3{margin:0;font-size:24px;line-height:1.1;letter-spacing:-.03em}
27
+ .pr-chips{display:flex;gap:6px;flex-wrap:wrap}
28
+ .pr-chip{padding:3px 8px;border:1px solid var(--pr-line);border-radius:999px;background:var(--pr-panel);font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--pr-muted);white-space:nowrap}
29
+ .pr-chip.sandbox{color:#0f766e;border-color:rgba(15,118,110,.25);background:rgba(15,118,110,.07)}
30
+ .pr-chip.approval{color:#9a3412;border-color:rgba(154,52,18,.22);background:rgba(154,52,18,.06)}
31
+ .pr-mode p{margin:8px 0 0;color:var(--pr-muted);font-size:13px;line-height:1.5;max-width:70ch}
32
+ .pr-note{display:flex;gap:8px;align-items:flex-start;margin-top:14px;padding:10px 12px;border:1px solid rgba(15,118,110,.16);border-radius:10px;background:rgba(15,118,110,.05);color:var(--pr-muted);font-size:12px;line-height:1.45}
33
+ .pr-note b{color:var(--pr-text);font-weight:650}
34
+ .pr-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
35
+ .pr-stat{padding:14px 16px;border:1px solid var(--pr-line);border-radius:14px;background:var(--pr-panel);min-width:0}
36
+ .pr-stat b{display:block;font-size:24px;line-height:1.1;letter-spacing:-.03em;font-variant-numeric:tabular-nums}
37
+ .pr-stat span{display:block;margin-top:5px;color:var(--pr-muted);font-size:11px;font-weight:650;letter-spacing:.07em;text-transform:uppercase}
38
+ .pr-section{display:flex;flex-direction:column;gap:10px;min-width:0}
39
+ .pr-section h3{margin:0;font-size:15px;letter-spacing:-.01em}
40
+ .pr-section .pr-hint{margin:0;color:var(--pr-muted);font-size:12px;line-height:1.45}
41
+ .pr-presets{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
42
+ .pr-preset{padding:12px;border:1px solid var(--pr-line);border-radius:12px;background:var(--pr-panel);min-width:0}
43
+ .pr-preset.active{border-color:rgba(15,118,110,.35);background:rgba(15,118,110,.06)}
44
+ .pr-preset b{display:flex;justify-content:space-between;gap:8px;font-size:13px;align-items:center}
45
+ .pr-preset span{display:block;margin-top:4px;color:var(--pr-muted);font-size:11.5px;line-height:1.4}
46
+ .pr-preset em{font-style:normal;color:var(--pr-accent);font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase}
47
+ .pr-list{display:flex;flex-direction:column;border:1px solid var(--pr-line);border-radius:14px;overflow:hidden;background:var(--pr-panel)}
48
+ .pr-row{display:flex;gap:10px;align-items:baseline;padding:9px 12px;border-top:1px solid var(--pr-line);font-size:12px;line-height:1.4;min-width:0}
49
+ .pr-row:first-child{border-top:0}
50
+ .pr-sev{flex:none;width:46px;font-size:9.5px;font-weight:750;letter-spacing:.08em;text-transform:uppercase}
51
+ .pr-sev.deny{color:#9f1239}.pr-sev.ask{color:#9a3412}
52
+ .pr-row code{flex:none;color:var(--pr-text);font:inherit;font-weight:650;white-space:nowrap}
53
+ .pr-row span{color:var(--pr-muted);overflow:hidden;text-overflow:ellipsis;min-width:0}
54
+ .pr-path{padding:9px 12px;border-top:1px solid var(--pr-line);font-size:12px;line-height:1.45;min-width:0}
55
+ .pr-path:first-child{border-top:0}
56
+ .pr-path b{display:block;font-size:12px}
57
+ .pr-path code{display:block;margin-top:3px;color:var(--pr-muted);font:11.5px/1.4 ui-monospace,SFMono-Regular,Consolas,monospace;overflow-wrap:anywhere}
58
+ .pr-error{padding:8px 10px;border:1px solid rgba(159,18,57,.16);border-radius:9px;background:rgba(159,18,57,.06);color:#9f1239;font-size:12px;line-height:1.4}
59
+ .pr-loading{color:var(--pr-muted);font-size:13px;padding:18px 0}
60
+ .pr-empty{padding:18px;border:1px dashed var(--pr-line);border-radius:14px;color:var(--pr-muted);font-size:12.5px;line-height:1.5;background:linear-gradient(160deg,var(--pr-soft),transparent 75%)}
61
+ .pr-foot{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;color:var(--pr-muted);font-size:11px;line-height:1.4}
62
+ @media(max-width:860px){.pr-presets{grid-template-columns:1fr 1fr}.pr-stats{grid-template-columns:1fr 1fr}}
63
+ @media(max-width:520px){.pr-presets{grid-template-columns:1fr}.pr-stats{grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}.pr-stat{padding:10px 12px}.pr-stat b{font-size:20px}.pr-stat span{font-size:9px;letter-spacing:.04em}.pr-root{gap:16px}.pr-mode{padding:16px}.pr-note{flex-direction:column;gap:4px}.pr-row{display:flex;flex-wrap:wrap;gap:4px 8px}.pr-row code{white-space:normal;overflow-wrap:anywhere}.pr-row span{flex-basis:100%;padding-left:0}}
64
+ `;
65
+
66
+ const SEVERITY_ORDER = { deny: 0, ask: 1 };
67
+
68
+ function currentSessionSelector(state) {
69
+ try {
70
+ const sessions = Object.values(state.byId || {});
71
+ const main = sessions.find((session) => session && session.retainedBy && (session.retainedBy.mainView || 0) > 0);
72
+ if (main) return main.id;
73
+ const ids = Array.isArray(state.ids) ? state.ids : [];
74
+ return ids.length > 0 ? ids[ids.length - 1] : undefined;
75
+ } catch { return undefined; }
76
+ }
77
+
78
+ async function call(ctx, operation, payload) {
79
+ let signal;
80
+ try { signal = AbortSignal.timeout(30000); } catch { signal = undefined; }
81
+ const result = await ctx.connection.rpc.call("/api", `dsh-guardrails/${operation}`, payload ?? {}, signal);
82
+ if (!result || result.ok !== true) throw new Error(result?.error?.message || "Ошибка RPC");
83
+ return result.value;
84
+ }
85
+
86
+ function errorOf(value) { return value instanceof Error ? value.message : String(value); }
87
+
88
+ function SandboxChip({ value }) {
89
+ const labels = {
90
+ "read-only": "Read only",
91
+ "workspace-write": "Workspace write",
92
+ "danger-full-access": "Full access",
93
+ };
94
+ return h("span", { className: "pr-chip sandbox" }, labels[value] || value || "sandbox");
95
+ }
96
+
97
+ function PermissionsSection(props) {
98
+ const [state, setState] = useState({ loading: true, error: null, data: null });
99
+ const useSessions = props && props.useSessions;
100
+ const useWorkspaces = props && props.useWorkspaces;
101
+ const sessionId = useSessions ? useSessions(currentSessionSelector) : undefined;
102
+ const workspaceSnapshot = useWorkspaces ? useWorkspaces((snapshot) => snapshot) : undefined;
103
+ const workspaces = Array.isArray(workspaceSnapshot?.items) ? workspaceSnapshot.items : [];
104
+ const workspace = workspaces.find((item) => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId))
105
+ ?? workspaces.find((item) => Array.isArray(item.sessionIds) && item.sessionIds.length > 0)
106
+ ?? workspaces[0];
107
+ const cwd = typeof workspace?.path === "string" ? workspace.path : undefined;
108
+
109
+ useEffect(() => {
110
+ let cancelled = false;
111
+ (async () => {
112
+ try {
113
+ const data = await call(window.__DSH_GUARDRAILS_CTX__, "permissions", { sessionId, cwd });
114
+ if (!cancelled) setState({ loading: false, error: null, data });
115
+ } catch (error) {
116
+ if (!cancelled) setState({ loading: false, error: errorOf(error), data: null });
117
+ }
118
+ })();
119
+ return () => { cancelled = true; };
120
+ }, [sessionId, cwd]);
121
+
122
+ const preset = state.data?.preset;
123
+ const guard = state.data?.guard;
124
+ const options = Array.isArray(preset?.catalog?.options) ? preset.catalog.options : [];
125
+ const rules = Array.isArray(guard?.rules)
126
+ ? [...guard.rules].sort((a, b) => (SEVERITY_ORDER[a.severity] ?? 9) - (SEVERITY_ORDER[b.severity] ?? 9))
127
+ : [];
128
+ const protectedPaths = Array.isArray(guard?.protectedPaths) ? guard.protectedPaths : [];
129
+ const current = preset?.current || "custom";
130
+ const spec = preset?.spec;
131
+ const option = preset?.option;
132
+ const title = option?.name || current;
133
+
134
+ return h("section", { className: "pr-root", "aria-label": "Права и ограничения" },
135
+ h("div", { className: "pr-head" },
136
+ h("div", null,
137
+ h("p", { className: "pr-eyebrow" }, "Guardrails · effective permissions"),
138
+ h("h2", { className: "pr-title" }, "Права"),
139
+ h("p", { className: "pr-sub" }, "Что разрешено в этом чате и что kit запрещает в любом режиме. Режим переключается штатным picker DSH в композере — здесь только прозрачный срез."),
140
+ ),
141
+ ),
142
+ state.error ? h("div", { className: "pr-error", role: "alert" }, state.error) : null,
143
+ state.loading ? h("div", { className: "pr-loading" }, "Читаем эффективные права…") : null,
144
+ !state.loading && state.data ? h(React.Fragment, null,
145
+ h("div", { className: "pr-mode" },
146
+ h("div", { className: "pr-mode-top" },
147
+ h("div", null,
148
+ h("h3", null, title),
149
+ h("p", null, option?.description || spec?.description || "Эффективный режим этого чата."),
150
+ ),
151
+ h("div", { className: "pr-chips" },
152
+ h(SandboxChip, { value: spec?.sandbox }),
153
+ h("span", { className: "pr-chip approval" }, spec?.approval === "never" ? "approval never" : "approval ask"),
154
+ ),
155
+ ),
156
+ h("div", { className: "pr-note" },
157
+ h("b", null, "Не второй picker."),
158
+ h("span", null, "Смена режима — только в DSH. Эта страница не меняет разрешения и не хранит approvals; каждая карточка подтверждения остаётся в чате."),
159
+ ),
160
+ ),
161
+ h("div", { className: "pr-stats" },
162
+ h("div", { className: "pr-stat" }, h("b", null, rules.length), h("span", null, "жёстких правил")),
163
+ h("div", { className: "pr-stat" }, h("b", null, protectedPaths.length), h("span", null, "защищённых путей")),
164
+ h("div", { className: "pr-stat" }, h("b", null, options.length), h("span", null, "пресетов DSH")),
165
+ ),
166
+ h("div", { className: "pr-section" },
167
+ h("h3", null, "Пресеты DSH"),
168
+ h("p", { className: "pr-hint" }, "Доступны в композере. Текущий выделен; kit не дублирует переключатель."),
169
+ h("div", { className: "pr-presets" }, options.map((item) => h("div", { key: item.value, className: `pr-preset${item.value === current ? " active" : ""}` },
170
+ h("b", null, h("span", null, item.name || item.value), item.value === current ? h("em", null, "сейчас") : null),
171
+ h("span", null, item.description || "Без описания"),
172
+ ))),
173
+ ),
174
+ h("div", { className: "pr-section" },
175
+ h("h3", null, "Жёсткие правила kit"),
176
+ h("p", { className: "pr-hint" }, "Действуют даже в Full access. Отключаются только политикой guardrails, не режимом DSH."),
177
+ rules.length > 0 ? h("div", { className: "pr-list" }, rules.map((rule) => h("div", { className: "pr-row", key: rule.id },
178
+ h("span", { className: `pr-sev ${rule.severity}` }, rule.severity),
179
+ h("code", null, rule.id),
180
+ h("span", { title: rule.description }, rule.description || ""),
181
+ ))) : h("div", { className: "pr-empty" }, "Правила отключены политикой guardrails."),
182
+ ),
183
+ h("div", { className: "pr-section" },
184
+ h("h3", null, "Защищённые пути"),
185
+ h("p", { className: "pr-hint" }, "Запись, редактирование и удаление этих путей отклоняются до выполнения."),
186
+ protectedPaths.length > 0 ? h("div", { className: "pr-list" }, protectedPaths.map((entry) => h("div", { className: "pr-path", key: entry.id },
187
+ h("b", null, entry.id),
188
+ h("code", null, `${entry.match} /${entry.pattern}/`),
189
+ ))) : h("div", { className: "pr-empty" }, "Защищённые пути отключены."),
190
+ ),
191
+ ) : null,
192
+ h("div", { className: "pr-foot" },
193
+ h("span", null, guard?.policyPath ? `Политика: ${guard.policyPath}` : "Политика guardrails"),
194
+ h("span", null, guard ? (guard.enabled ? "hooks активны" : "hooks отключены") : ""),
195
+ ),
196
+ );
197
+ }
198
+
199
+ function apply(ctx) {
200
+ window.__DSH_GUARDRAILS_CTX__ = ctx;
201
+ ctx.effect(() => {
202
+ const style = document.createElement("style");
203
+ style.id = "dsh-guardrails";
204
+ style.textContent = CSS;
205
+ document.head.appendChild(style);
206
+ return () => style.remove();
207
+ }, "guardrails: styles");
208
+ ctx.effect(() => ctx.slots.inject("settings.section", () => ctx.slots.register({
209
+ name: "settings.section",
210
+ id: "guardrails",
211
+ order: 35,
212
+ label: () => "Права",
213
+ }, PermissionsSection)), "guardrails: settings");
214
+ }
215
+
216
+ exports.apply = apply;
217
+ exports.inject = ["slots", "connection"];
218
+ return module.exports;
219
+ },
220
+ });
@@ -21,6 +21,7 @@ import fs from "node:fs";
21
21
  import path from "node:path";
22
22
 
23
23
  import { createGuard, createHookState, registerHooks } from "./lib/hooks.js";
24
+ import { registerPermissionsApi } from "./lib/api.js";
24
25
  import { resolveMode } from "./lib/modes.js";
25
26
  import {
26
27
  DEFAULT_COMMAND_RULES,
@@ -385,5 +386,10 @@ export function apply(ctx) {
385
386
  };
386
387
 
387
388
  ctx.tools.register(tool);
389
+ try {
390
+ ctx.inject(["connection"], (child) => registerPermissionsApi(child));
391
+ } catch (error) {
392
+ logger?.warn?.(`[guardrails] permissions UI skipped: ${messageOf(error)}`);
393
+ }
388
394
  logger?.info?.(`[guardrails] tool ready (policy: ${policyPath(env)})`);
389
395
  }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Read-only Permissions RPC.
3
+ *
4
+ * DSH owns the permission picker and the approval card. This endpoint only
5
+ * reports the effective preset plus the kit's independent hard rules, so the
6
+ * Settings page never becomes a second source of truth.
7
+ */
8
+ import { loadPolicy } from "./policy.js";
9
+
10
+ export const RPC_NAMESPACE = "dsh-guardrails";
11
+ const ROUTE_BASE = "/api/dsh-guardrails";
12
+
13
+ function ok(rpcId, value) {
14
+ return Response.json({ type: "server-response", rpcId, result: { ok: true, value } });
15
+ }
16
+
17
+ function fail(rpcId, message) {
18
+ return Response.json({ type: "server-response", rpcId, result: { ok: false, error: { code: "guardrails/bad-request", message, details: {} } } });
19
+ }
20
+
21
+ async function envelope(request) {
22
+ const body = await request.json();
23
+ if (!body || body.type !== "client-request" || typeof body.rpcId !== "string" || typeof body.method !== "string") {
24
+ throw new Error("bad Connection envelope");
25
+ }
26
+ return { rpcId: body.rpcId, method: body.method, payload: body.payload ?? {} };
27
+ }
28
+
29
+ function liveSession(ctx, payload) {
30
+ const sessions = ctx.get?.("sessions");
31
+ if (payload?.sessionId) {
32
+ const direct = sessions?.get?.(payload.sessionId);
33
+ if (direct) return direct;
34
+ }
35
+ const live = typeof sessions?.list === "function" ? sessions.list() : [];
36
+ return live.length > 0 ? live[live.length - 1] : undefined;
37
+ }
38
+
39
+ function presetSnapshot(ctx, session) {
40
+ const service = ctx.get?.("permissionPresets");
41
+ if (!service) return { available: false, current: null, spec: null, option: null, catalog: { options: [], defaultPreset: null } };
42
+ let catalog = { options: [], defaultPreset: null };
43
+ try { catalog = service.catalog(); } catch { /* optional service */ }
44
+ let name = null;
45
+ try { name = session ? service.current(session) : null; } catch { name = null; }
46
+ let spec = null;
47
+ let option = null;
48
+ if (name) {
49
+ try { spec = service.resolve(name); } catch { spec = null; }
50
+ try { option = service.optionOf(name); } catch { option = null; }
51
+ }
52
+ return { available: true, current: name, spec, option, catalog };
53
+ }
54
+
55
+ function guardSnapshot(env) {
56
+ const loaded = loadPolicy({ env });
57
+ const rules = loaded.policy.rules
58
+ .filter((rule) => rule.enabled !== false)
59
+ .map((rule) => ({ id: rule.id, severity: rule.severity, description: rule.description }));
60
+ const protectedPaths = loaded.policy.protectedPaths
61
+ .filter((entry) => entry.enabled !== false)
62
+ .map((entry) => ({ id: entry.id, match: entry.match, pattern: entry.pattern, description: entry.description }));
63
+ return {
64
+ enabled: loaded.enabled,
65
+ killSwitch: loaded.killSwitch,
66
+ policyPath: loaded.path,
67
+ loadedFromFile: loaded.loadedFromFile,
68
+ error: loaded.error,
69
+ warnings: loaded.warnings,
70
+ rules,
71
+ protectedPaths,
72
+ hooks: loaded.policy.hooks,
73
+ };
74
+ }
75
+
76
+ export function registerPermissionsApi(ctx) {
77
+ const route = {
78
+ path: `${ROUTE_BASE}/permissions`,
79
+ methods: ["POST"],
80
+ requestBody: "buffered",
81
+ fetch: async (request) => {
82
+ let rpcId = "invalid-request";
83
+ try {
84
+ const value = await envelope(request);
85
+ rpcId = value.rpcId;
86
+ if (value.method !== `${RPC_NAMESPACE}/permissions`) throw new Error("endpoint/method mismatch");
87
+ const session = liveSession(ctx, value.payload);
88
+ const preset = presetSnapshot(ctx, session);
89
+ return ok(rpcId, {
90
+ project: session?.header?.cwd ?? null,
91
+ preset,
92
+ guard: guardSnapshot(process.env),
93
+ });
94
+ } catch (error) {
95
+ return fail(rpcId, error instanceof Error ? error.message : String(error));
96
+ }
97
+ },
98
+ };
99
+ ctx.effect(() => {
100
+ const dispose = ctx.connection.fetch.register(route);
101
+ return () => { try { void Promise.resolve(dispose()).catch(() => {}); } catch { /* unloading */ } };
102
+ }, "guardrails: permissions route");
103
+ }
@@ -7,11 +7,13 @@
7
7
  "main": "index.js",
8
8
  "exports": {
9
9
  ".": "./index.js",
10
+ "./client": "./client.js",
10
11
  "./lib": "./lib/scan.js",
11
12
  "./package.json": "./package.json"
12
13
  },
13
14
  "files": [
14
15
  "index.js",
16
+ "client.js",
15
17
  "lib/**",
16
18
  "tools/**",
17
19
  "cordis.patch.yml",