@restranger/repi-permission-system-modes 0.0.0-stage → 0.0.1-1a48fc0
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.
- package/package.json +40 -5
- package/src/builtin-modes.ts +39 -0
- package/src/index.ts +7 -0
- package/src/mode-selector.ts +159 -0
- package/src/plugin.ts +528 -0
- package/src/preferences.ts +191 -0
- package/src/registry.ts +247 -0
- package/src/types.ts +74 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@restranger/repi-permission-system-modes",
|
|
3
|
+
"version": "0.0.1-1a48fc0",
|
|
4
|
+
"description": "Permission modes (manual, bypass, deny) and /permission-mode command for pi-coding-agent",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"types": "./src/index.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.ts"
|
|
10
|
+
},
|
|
11
|
+
"files": ["src", "README.md", "!src/**/__tests__"],
|
|
12
|
+
"keywords": ["pi-package", "pi-coding-agent", "permissions", "security", "modes"],
|
|
13
|
+
"author": "ReStranger <restranger@disroot.org>",
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/ReStranger/repi-mono.git",
|
|
18
|
+
"directory": "packages/permission-system-modes"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/ReStranger/repi-mono/issues"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/ReStranger/repi-mono#readme",
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"pi": {
|
|
28
|
+
"extensions": ["./src/index.ts"]
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@restranger/repi-lib": "0.0.1-1a48fc0"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@earendil-works/pi-coding-agent": ">=0.79.0"
|
|
35
|
+
},
|
|
36
|
+
"peerDependenciesMeta": {
|
|
37
|
+
"@earendil-works/pi-coding-agent": {
|
|
38
|
+
"optional": true
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ModeDefinition } from "./types.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Three built-in modes, nothing else.
|
|
5
|
+
*
|
|
6
|
+
* They do not contain their own allow/deny lists: the verdict comes from `@restranger/repi-permission-system-core`
|
|
7
|
+
* (config rules, hard deny, grants). A mode only rewrites `ask`:
|
|
8
|
+
*
|
|
9
|
+
* | mode | allow | deny | ask |
|
|
10
|
+
* |-----------|-------|------|-------|
|
|
11
|
+
* | `manual` | allow | deny | ask |
|
|
12
|
+
* | `bypass` | allow | deny | allow |
|
|
13
|
+
* | `deny` | allow | deny | deny |
|
|
14
|
+
*/
|
|
15
|
+
export const MANUAL_MODE: ModeDefinition = {
|
|
16
|
+
id: "manual",
|
|
17
|
+
name: "Manual",
|
|
18
|
+
description: "Config decides: explicit allow/deny is respected, everything else asks",
|
|
19
|
+
permissionsPolicy: "manual",
|
|
20
|
+
badge: { label: "\x1b[38;2;103;103;120m⏸ manual mode\x1b[39m", tone: "muted" },
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const BYPASS_MODE: ModeDefinition = {
|
|
24
|
+
id: "bypass",
|
|
25
|
+
name: "Bypass",
|
|
26
|
+
description: "Auto-approves everything that would ask; explicit deny and hard deny still apply",
|
|
27
|
+
permissionsPolicy: "bypass",
|
|
28
|
+
badge: { label: "\x1b[31m⏵⏵ bypass mode\x1b[39m", tone: "danger" },
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const DENY_MODE: ModeDefinition = {
|
|
32
|
+
id: "deny",
|
|
33
|
+
name: "Deny",
|
|
34
|
+
description: "Auto-denies everything that would ask; explicit allow from config still applies",
|
|
35
|
+
permissionsPolicy: "deny",
|
|
36
|
+
badge: { label: "\x1b[38;2;122;170;255m⊘ deny mode\x1b[39m", tone: "accent" },
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export const BUILTIN_MODES: readonly ModeDefinition[] = [MANUAL_MODE, BYPASS_MODE, DENY_MODE];
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import type { ModeDefinition } from "./types.js";
|
|
2
|
+
|
|
3
|
+
/** A mode picked in the inline selector; `null` means the user cancelled. */
|
|
4
|
+
export interface ModeSelection {
|
|
5
|
+
readonly modeId: string;
|
|
6
|
+
/** Ctrl+S: make the highlighted mode the default for new sessions. */
|
|
7
|
+
readonly makeDefault?: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface ModeSelectorTheme {
|
|
11
|
+
fg(color: string, text: string): string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ModeSelectorKeybindings {
|
|
15
|
+
matches(data: string, key: string): boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ModeSelectorTui {
|
|
19
|
+
requestRender(): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ModeSelectorComponent {
|
|
23
|
+
render(width: number): string[];
|
|
24
|
+
handleInput(data: string): void;
|
|
25
|
+
invalidate(): void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ModeSelectorOptions {
|
|
29
|
+
readonly modes: readonly ModeDefinition[];
|
|
30
|
+
readonly currentId: string;
|
|
31
|
+
readonly tui: ModeSelectorTui;
|
|
32
|
+
readonly theme: ModeSelectorTheme;
|
|
33
|
+
readonly keybindings: ModeSelectorKeybindings;
|
|
34
|
+
readonly done: (selection: ModeSelection | null) => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const CTRL_S = String.fromCharCode(19);
|
|
38
|
+
const SAVE_AS_DEFAULT_KEYS = ["app.models.save", "app.thinking.save"] as const;
|
|
39
|
+
const HINT = "↑/↓ move · enter select · ctrl+s set default · esc cancel";
|
|
40
|
+
|
|
41
|
+
function paint(theme: ModeSelectorTheme, color: string, text: string): string {
|
|
42
|
+
try {
|
|
43
|
+
return theme.fg(color, text);
|
|
44
|
+
} catch {
|
|
45
|
+
return text;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function truncate(text: string, width: number): string {
|
|
50
|
+
if (width <= 0) {
|
|
51
|
+
return "";
|
|
52
|
+
}
|
|
53
|
+
return text.length <= width ? text : `${text.slice(0, width - 1)}…`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Inline `/permission-mode` selector.
|
|
58
|
+
*
|
|
59
|
+
* Enter switches only the current session. `Ctrl+S` instead saves the highlighted mode as
|
|
60
|
+
* the default for new sessions; the caller persists that choice.
|
|
61
|
+
*/
|
|
62
|
+
export function createModeSelector(opts: ModeSelectorOptions): ModeSelectorComponent {
|
|
63
|
+
const currentIndex = opts.modes.findIndex((mode) => mode.id === opts.currentId);
|
|
64
|
+
let highlighted = currentIndex >= 0 ? currentIndex : 0;
|
|
65
|
+
let cachedWidth: number | undefined;
|
|
66
|
+
let cachedLines: string[] | undefined;
|
|
67
|
+
|
|
68
|
+
const invalidate = (): void => {
|
|
69
|
+
cachedWidth = undefined;
|
|
70
|
+
cachedLines = undefined;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const matches = (data: string, key: string): boolean => {
|
|
74
|
+
try {
|
|
75
|
+
return opts.keybindings.matches(data, key);
|
|
76
|
+
} catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const move = (delta: number): void => {
|
|
82
|
+
if (opts.modes.length === 0) {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
highlighted = (highlighted + delta + opts.modes.length) % opts.modes.length;
|
|
86
|
+
invalidate();
|
|
87
|
+
opts.tui.requestRender();
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const selectHighlighted = (makeDefault: boolean): void => {
|
|
91
|
+
const selected = opts.modes[highlighted];
|
|
92
|
+
if (selected) {
|
|
93
|
+
opts.done({ modeId: selected.id, ...(makeDefault ? { makeDefault: true } : {}) });
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const render = (width: number): string[] => {
|
|
98
|
+
if (cachedLines && cachedWidth === width) {
|
|
99
|
+
return cachedLines;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const lines = [paint(opts.theme, "accent", truncate(`Mode — current: ${opts.currentId}`, width))];
|
|
103
|
+
|
|
104
|
+
for (const [index, mode] of opts.modes.entries()) {
|
|
105
|
+
const selected = index === highlighted;
|
|
106
|
+
const current = mode.id === opts.currentId;
|
|
107
|
+
const cursor = selected ? "→ " : " ";
|
|
108
|
+
const marker = current ? "✓ " : " ";
|
|
109
|
+
if (width <= 4) {
|
|
110
|
+
lines.push(truncate(`${cursor}${marker}`, width));
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const content = truncate(`${mode.id} — ${mode.description}`, width - 4);
|
|
114
|
+
const styledCursor = selected ? paint(opts.theme, "accent", cursor) : cursor;
|
|
115
|
+
const styledMarker = current ? paint(opts.theme, "accent", marker) : marker;
|
|
116
|
+
const styledContent = selected ? paint(opts.theme, "accent", content) : content;
|
|
117
|
+
lines.push(`${styledCursor}${styledMarker}${styledContent}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (opts.modes.length === 0) {
|
|
121
|
+
lines.push(paint(opts.theme, "muted", "No modes"));
|
|
122
|
+
}
|
|
123
|
+
lines.push("");
|
|
124
|
+
lines.push(paint(opts.theme, "muted", truncate(HINT, width)));
|
|
125
|
+
|
|
126
|
+
cachedWidth = width;
|
|
127
|
+
cachedLines = lines;
|
|
128
|
+
return cachedLines;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
render,
|
|
133
|
+
invalidate,
|
|
134
|
+
handleInput(data: string): void {
|
|
135
|
+
// `keybindings.matches` takes action ids, not key names. `app.models.save` and
|
|
136
|
+
// `app.thinking.save` both default to ctrl+s and, unlike a raw `\x13` check, they
|
|
137
|
+
// also recognize Kitty/modifyOtherKeys sequences used by modern terminals.
|
|
138
|
+
if (data === CTRL_S || SAVE_AS_DEFAULT_KEYS.some((key) => matches(data, key))) {
|
|
139
|
+
selectHighlighted(true);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (data === "\x1b[A" || data === "k" || matches(data, "tui.select.up")) {
|
|
143
|
+
move(-1);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (data === "\x1b[B" || data === "j" || matches(data, "tui.select.down")) {
|
|
147
|
+
move(1);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (data === "\r" || data === "\n" || matches(data, "tui.select.confirm")) {
|
|
151
|
+
selectHighlighted(false);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (data === "\x1b" || matches(data, "tui.select.cancel")) {
|
|
155
|
+
opts.done(null);
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Disposable,
|
|
3
|
+
MODES_CONTRACT_ID,
|
|
4
|
+
PERMISSIONS_CONTRACT_ID,
|
|
5
|
+
type PermissionService,
|
|
6
|
+
type PiContext,
|
|
7
|
+
type PiExtensionAPI,
|
|
8
|
+
UI_CONTRACT_ID,
|
|
9
|
+
type UiService,
|
|
10
|
+
announceReady,
|
|
11
|
+
getService,
|
|
12
|
+
getSessionId,
|
|
13
|
+
onService,
|
|
14
|
+
publishService,
|
|
15
|
+
sanitize,
|
|
16
|
+
} from "@restranger/repi-lib";
|
|
17
|
+
import { type ModeSelection, createModeSelector } from "./mode-selector.js";
|
|
18
|
+
import { type ModesPreferencesStore, createModesPreferencesStore } from "./preferences.js";
|
|
19
|
+
import { ModeRegistry, UnknownModeError } from "./registry.js";
|
|
20
|
+
import type { ModeDefinition } from "./types.js";
|
|
21
|
+
|
|
22
|
+
export interface ModesPluginOptions {
|
|
23
|
+
permissionService?: PermissionService;
|
|
24
|
+
/** Session used when the host does not pass one in the event context. */
|
|
25
|
+
defaultSessionId?: string;
|
|
26
|
+
/** Explicit UI service override; otherwise resolved from the seam or the Pi context. */
|
|
27
|
+
uiService?: UiService;
|
|
28
|
+
/** Override persisted preferences (tests and custom hosts). */
|
|
29
|
+
preferencesStore?: ModesPreferencesStore;
|
|
30
|
+
/** Preferences file; defaults to `$XDG_CACHE_HOME/repi/permission-system-modes.json`. Pass `false` to disable persistence. */
|
|
31
|
+
preferencesPath?: string | false;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface SessionState {
|
|
35
|
+
registration: Disposable;
|
|
36
|
+
permissionSubscription?: Disposable;
|
|
37
|
+
ctx: PiContext;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Tool name from a `tool_call` payload, tolerating the host's shape variants. */
|
|
41
|
+
function toolNameFromEvent(event: unknown): string | undefined {
|
|
42
|
+
if (typeof event !== "object" || event === null) {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const record = event as Record<string, unknown>;
|
|
46
|
+
for (const key of ["tool", "toolName", "name"]) {
|
|
47
|
+
const value = record[key];
|
|
48
|
+
if (typeof value === "string" && value.length > 0) {
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ModesRuntime {
|
|
56
|
+
readonly registry: ModeRegistry;
|
|
57
|
+
attach(pi: PiExtensionAPI): void;
|
|
58
|
+
dispose(): void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function getHostTheme(): { fg(token: string, text: string): string } | undefined {
|
|
62
|
+
const sym = Symbol.for("@earendil-works/pi-coding-agent:theme");
|
|
63
|
+
const symOld = Symbol.for("@mariozechner/pi-coding-agent:theme");
|
|
64
|
+
const globalRecord = globalThis as unknown as Record<symbol, { fg(token: string, text: string): string }>;
|
|
65
|
+
return globalRecord[sym] ?? globalRecord[symOld];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Format a badge with its associated tone color.
|
|
70
|
+
* If dynamic host theme is available, tokens match the active theme.
|
|
71
|
+
*/
|
|
72
|
+
export function formatBadgeText(badge: ModeDefinition["badge"], modeId?: string): string {
|
|
73
|
+
const hostTheme = getHostTheme();
|
|
74
|
+
if (hostTheme) {
|
|
75
|
+
try {
|
|
76
|
+
const clean = sanitize(badge.label);
|
|
77
|
+
if (modeId === "deny" || badge.tone === "accent") {
|
|
78
|
+
return hostTheme.fg("thinkingLow", clean);
|
|
79
|
+
}
|
|
80
|
+
if (modeId === "manual" || badge.tone === "muted") {
|
|
81
|
+
return hostTheme.fg("muted", clean);
|
|
82
|
+
}
|
|
83
|
+
if (modeId === "bypass" || badge.tone === "danger") {
|
|
84
|
+
return hostTheme.fg("error", clean);
|
|
85
|
+
}
|
|
86
|
+
if (badge.tone === "warning") {
|
|
87
|
+
return hostTheme.fg("warning", clean);
|
|
88
|
+
}
|
|
89
|
+
if (badge.tone === "success") {
|
|
90
|
+
return hostTheme.fg("success", clean);
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
// Fallback below
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (badge.label.includes("\x1b[")) {
|
|
97
|
+
return badge.label;
|
|
98
|
+
}
|
|
99
|
+
switch (badge.tone) {
|
|
100
|
+
case "accent":
|
|
101
|
+
return `\x1b[38;2;122;170;255m${badge.label}\x1b[39m`;
|
|
102
|
+
case "muted":
|
|
103
|
+
return `\x1b[38;2;103;103;120m${badge.label}\x1b[39m`;
|
|
104
|
+
case "danger":
|
|
105
|
+
return `\x1b[31m${badge.label}\x1b[39m`;
|
|
106
|
+
case "warning":
|
|
107
|
+
return `\x1b[33m${badge.label}\x1b[39m`;
|
|
108
|
+
case "success":
|
|
109
|
+
return `\x1b[32m${badge.label}\x1b[39m`;
|
|
110
|
+
default:
|
|
111
|
+
return badge.label;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function uiFromContext(ctx: PiContext): UiService {
|
|
116
|
+
return {
|
|
117
|
+
select: (title, options) => ctx.ui.select(title, options),
|
|
118
|
+
confirm: (title, message) => ctx.ui.confirm(title, message),
|
|
119
|
+
input: (title, placeholder) => ctx.ui.input(title, placeholder),
|
|
120
|
+
notify: (message, type) => ctx.ui.notify(message, type),
|
|
121
|
+
setStatus: (key, text) => ctx.ui.setStatus?.(key, text),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Independent modes extension.
|
|
127
|
+
*
|
|
128
|
+
* It owns three modes (`manual`, `bypass`, `deny`) and a `/permission-mode` command. The authorization
|
|
129
|
+
* verdict itself always comes from `@restranger/repi-permission-system-core`; modes only rewrites `ask` into `allow`
|
|
130
|
+
* (bypass) or `deny` (deny). `bypass` and `deny` are refused when no permission engine is attached,
|
|
131
|
+
* because a mode that cannot transform a verdict would only repaint its badge.
|
|
132
|
+
*/
|
|
133
|
+
export function createModesRuntime(opts: ModesPluginOptions = {}): ModesRuntime {
|
|
134
|
+
const defaultSessionId = opts.defaultSessionId ?? "default";
|
|
135
|
+
const registry = new ModeRegistry();
|
|
136
|
+
const preferencesStore =
|
|
137
|
+
opts.preferencesStore ??
|
|
138
|
+
(opts.preferencesPath === false ? undefined : createModesPreferencesStore(opts.preferencesPath));
|
|
139
|
+
|
|
140
|
+
const sessions = new Map<string, SessionState>();
|
|
141
|
+
let permissionAttachment: Disposable | undefined;
|
|
142
|
+
let permissionService: PermissionService | undefined = opts.permissionService;
|
|
143
|
+
let modeListener: Disposable | undefined;
|
|
144
|
+
let attached = false;
|
|
145
|
+
let disposed = false;
|
|
146
|
+
let persistedDefaultModeId: string | undefined;
|
|
147
|
+
const persistedSessionModes = new Map<string, string>();
|
|
148
|
+
let preferencesWarning: string | undefined;
|
|
149
|
+
let unknownDefaultWarned = false;
|
|
150
|
+
let unknownSessionWarned = false;
|
|
151
|
+
|
|
152
|
+
if (preferencesStore) {
|
|
153
|
+
try {
|
|
154
|
+
const preferences = preferencesStore.load();
|
|
155
|
+
if (preferences.defaultMode) {
|
|
156
|
+
const defMode = preferences.defaultMode === "default" ? "manual" : preferences.defaultMode;
|
|
157
|
+
persistedDefaultModeId = defMode;
|
|
158
|
+
try {
|
|
159
|
+
// A custom mode may not be registered yet; retry when a session starts.
|
|
160
|
+
registry.setDefaultMode(defMode);
|
|
161
|
+
} catch {
|
|
162
|
+
// Keep the id and retry after the host registers custom modes.
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
for (const [sessionId, modeId] of Object.entries(preferences.sessions ?? {})) {
|
|
166
|
+
persistedSessionModes.set(sessionId, modeId === "default" ? "manual" : modeId);
|
|
167
|
+
}
|
|
168
|
+
} catch (err) {
|
|
169
|
+
preferencesWarning = err instanceof Error ? err.message : String(err);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (permissionService) {
|
|
174
|
+
permissionAttachment = registry.attachPermissionEngine(permissionService);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const ensurePermissionEngine = (service: PermissionService): void => {
|
|
178
|
+
if (permissionService === service && permissionAttachment) {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
permissionAttachment?.dispose();
|
|
182
|
+
permissionService = service;
|
|
183
|
+
permissionAttachment = registry.attachPermissionEngine(service);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const resolveUi = (sessionId: string, ctx: PiContext): UiService => {
|
|
187
|
+
return opts.uiService ?? getService<UiService>(UI_CONTRACT_ID, sessionId) ?? uiFromContext(ctx);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const pickMode = async (currentId: string, sessionId: string, ctx: PiContext): Promise<ModeSelection | undefined> => {
|
|
191
|
+
const modes = registry.listModes();
|
|
192
|
+
const custom = ctx.ui.custom?.bind(ctx.ui);
|
|
193
|
+
if (ctx.mode === "tui" && custom) {
|
|
194
|
+
try {
|
|
195
|
+
const picked = await custom<ModeSelection | null | undefined>(
|
|
196
|
+
(tui, theme, keybindings, done) =>
|
|
197
|
+
createModeSelector({
|
|
198
|
+
modes,
|
|
199
|
+
currentId,
|
|
200
|
+
tui,
|
|
201
|
+
theme,
|
|
202
|
+
keybindings,
|
|
203
|
+
done,
|
|
204
|
+
}),
|
|
205
|
+
{ overlay: false },
|
|
206
|
+
);
|
|
207
|
+
// `null` is an explicit cancel; `undefined` means the host has no inline selector,
|
|
208
|
+
// so RPC/print and minimal hosts fall through to the usual `select`.
|
|
209
|
+
if (picked === null) {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
if (picked) {
|
|
213
|
+
return picked;
|
|
214
|
+
}
|
|
215
|
+
} catch {
|
|
216
|
+
// Fall through to select when the host rejects `custom`.
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const ui = resolveUi(sessionId, ctx);
|
|
221
|
+
try {
|
|
222
|
+
const selected = await ui.select(
|
|
223
|
+
`Mode — current: ${currentId}`,
|
|
224
|
+
modes.map((mode) => `${mode.id} — ${mode.description}`),
|
|
225
|
+
);
|
|
226
|
+
const modeId = selected?.split(" — ")[0] ?? selected;
|
|
227
|
+
return modeId ? { modeId } : undefined;
|
|
228
|
+
} catch {
|
|
229
|
+
ui.notify(
|
|
230
|
+
`Mode selection needs an interactive UI. Use /permission-mode <${modes.map((m) => m.id).join("|")}>.`,
|
|
231
|
+
"warning",
|
|
232
|
+
);
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const announceModes = (pi: PiExtensionAPI, sessionId: string): void => {
|
|
238
|
+
announceReady(pi.events, {
|
|
239
|
+
contract: MODES_CONTRACT_ID,
|
|
240
|
+
version: 1,
|
|
241
|
+
sessionId,
|
|
242
|
+
owner: "repi:modes",
|
|
243
|
+
capabilities: ["mode-registry", "tool-filter", "permission-policy"],
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
const refreshSession = (_pi: PiExtensionAPI, sessionId: string): void => {
|
|
248
|
+
const state = sessions.get(sessionId);
|
|
249
|
+
if (!state) {
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
// Only the badge is refreshed. `pi.setActiveTools` is process-global in Pi, so a mode switch
|
|
253
|
+
// in one session used to add or remove tools in every other session and leave the reduced
|
|
254
|
+
// list behind after shutdown. Tool filtering happens per call in the `tool_call` hook below.
|
|
255
|
+
const mode = registry.getActiveMode(sessionId);
|
|
256
|
+
resolveUi(sessionId, state.ctx).setStatus("repi-mode", formatBadgeText(mode.badge, mode.id));
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
const applyPersistedDefault = (): void => {
|
|
260
|
+
if (!persistedDefaultModeId) {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
registry.setDefaultMode(persistedDefaultModeId);
|
|
265
|
+
} catch {
|
|
266
|
+
if (!unknownDefaultWarned) {
|
|
267
|
+
unknownDefaultWarned = true;
|
|
268
|
+
preferencesWarning = `Saved default mode "${persistedDefaultModeId}" is not registered; using "${registry.getDefaultMode().id}".`;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
const hasMode = (modeId: string): boolean => registry.listModes().some((mode) => mode.id === modeId);
|
|
274
|
+
|
|
275
|
+
/** Persist the global default and per-session choices together. */
|
|
276
|
+
const savePreferences = (): string | undefined => {
|
|
277
|
+
if (!preferencesStore) {
|
|
278
|
+
return undefined;
|
|
279
|
+
}
|
|
280
|
+
const sessions = Object.fromEntries(persistedSessionModes);
|
|
281
|
+
try {
|
|
282
|
+
preferencesStore.save({
|
|
283
|
+
...(persistedDefaultModeId ? { defaultMode: persistedDefaultModeId } : {}),
|
|
284
|
+
...(Object.keys(sessions).length > 0 ? { sessions } : {}),
|
|
285
|
+
});
|
|
286
|
+
return undefined;
|
|
287
|
+
} catch (err) {
|
|
288
|
+
return err instanceof Error ? err.message : String(err);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Pin the session to its saved mode (or the current default).
|
|
294
|
+
* Pinning also means a later Ctrl+S only affects new sessions, not this one.
|
|
295
|
+
*/
|
|
296
|
+
const restoreSessionMode = (sessionId: string): void => {
|
|
297
|
+
let modeId = persistedSessionModes.get(sessionId);
|
|
298
|
+
if (modeId && !hasMode(modeId)) {
|
|
299
|
+
if (!unknownSessionWarned) {
|
|
300
|
+
unknownSessionWarned = true;
|
|
301
|
+
preferencesWarning ??= `Saved mode "${modeId}" for session "${sessionId}" is not registered; using "${registry.getDefaultMode().id}".`;
|
|
302
|
+
}
|
|
303
|
+
modeId = undefined;
|
|
304
|
+
}
|
|
305
|
+
const target = modeId ?? registry.getDefaultMode().id;
|
|
306
|
+
try {
|
|
307
|
+
registry.setMode(target, { sessionId });
|
|
308
|
+
} catch {
|
|
309
|
+
// The built-in default is always present; an unknown custom default falls back in the registry.
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
interface SwitchModeOptions {
|
|
314
|
+
/** Ctrl+S: make the highlighted mode the default for new sessions. */
|
|
315
|
+
readonly makeDefault?: boolean;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const switchMode = (
|
|
319
|
+
pi: PiExtensionAPI,
|
|
320
|
+
requestedModeId: string,
|
|
321
|
+
sessionId: string,
|
|
322
|
+
ctx: PiContext,
|
|
323
|
+
options: SwitchModeOptions = {},
|
|
324
|
+
): void => {
|
|
325
|
+
const modeId =
|
|
326
|
+
requestedModeId === "default" && !registry.listModes().some((m) => m.id === "default")
|
|
327
|
+
? "manual"
|
|
328
|
+
: requestedModeId;
|
|
329
|
+
const ui = resolveUi(sessionId, ctx);
|
|
330
|
+
// `bypass` and `deny` are pure decision transformers. Without the permission engine they
|
|
331
|
+
// would only repaint the badge while every tool call ran unguarded, so refuse the switch.
|
|
332
|
+
const target = registry.listModes().find((mode) => mode.id === modeId);
|
|
333
|
+
if (target && target.permissionsPolicy !== "manual" && !permissionService) {
|
|
334
|
+
ui.notify(
|
|
335
|
+
`Mode "${modeId}" needs @restranger/repi-permission-system-core: no permission engine is attached, so it would not restrict anything.`,
|
|
336
|
+
"error",
|
|
337
|
+
);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
registry.setMode(modeId, { sessionId });
|
|
342
|
+
} catch (err) {
|
|
343
|
+
if (err instanceof UnknownModeError) {
|
|
344
|
+
ui.notify(err.message, "warning");
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
throw err;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
persistedSessionModes.set(sessionId, modeId);
|
|
351
|
+
if (options.makeDefault) {
|
|
352
|
+
// Pin every already-open session to its current mode before changing the default,
|
|
353
|
+
// so Ctrl+S only affects sessions created afterwards.
|
|
354
|
+
for (const [id] of sessions) {
|
|
355
|
+
if (id !== sessionId) {
|
|
356
|
+
persistedSessionModes.set(id, registry.getActiveMode(id).id);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
persistedDefaultModeId = modeId;
|
|
360
|
+
registry.setDefaultMode(modeId);
|
|
361
|
+
}
|
|
362
|
+
const saveError = savePreferences();
|
|
363
|
+
refreshSession(pi, sessionId);
|
|
364
|
+
|
|
365
|
+
ui.notify(
|
|
366
|
+
options.makeDefault ? `Default mode for new sessions: ${modeId}` : `Mode for this session: ${modeId}`,
|
|
367
|
+
"info",
|
|
368
|
+
);
|
|
369
|
+
if (saveError) {
|
|
370
|
+
ui.notify(`Could not save mode preferences: ${saveError}`, "warning");
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const publishSession = (pi: PiExtensionAPI, ctx: PiContext): void => {
|
|
375
|
+
const sessionId = getSessionId(ctx, defaultSessionId);
|
|
376
|
+
const existing = sessions.get(sessionId);
|
|
377
|
+
existing?.registration.dispose();
|
|
378
|
+
existing?.permissionSubscription?.dispose();
|
|
379
|
+
|
|
380
|
+
const registration = publishService({
|
|
381
|
+
contract: MODES_CONTRACT_ID,
|
|
382
|
+
sessionId,
|
|
383
|
+
owner: "repi:modes",
|
|
384
|
+
impl: registry,
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
let permissionSubscription: Disposable | undefined;
|
|
388
|
+
if (!opts.permissionService) {
|
|
389
|
+
const current = getService<PermissionService>(PERMISSIONS_CONTRACT_ID, sessionId);
|
|
390
|
+
if (current) {
|
|
391
|
+
ensurePermissionEngine(current);
|
|
392
|
+
}
|
|
393
|
+
permissionSubscription = onService<PermissionService>(pi.events, PERMISSIONS_CONTRACT_ID, sessionId, (service) =>
|
|
394
|
+
ensurePermissionEngine(service),
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
sessions.set(sessionId, {
|
|
399
|
+
registration,
|
|
400
|
+
permissionSubscription,
|
|
401
|
+
ctx,
|
|
402
|
+
});
|
|
403
|
+
applyPersistedDefault();
|
|
404
|
+
restoreSessionMode(sessionId);
|
|
405
|
+
announceModes(pi, sessionId);
|
|
406
|
+
refreshSession(pi, sessionId);
|
|
407
|
+
if (preferencesWarning) {
|
|
408
|
+
const warning = preferencesWarning;
|
|
409
|
+
preferencesWarning = undefined;
|
|
410
|
+
resolveUi(sessionId, ctx).notify(warning, "warning");
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
const attach = (pi: PiExtensionAPI): void => {
|
|
415
|
+
if (disposed) {
|
|
416
|
+
throw new Error("Modes runtime is disposed and cannot be attached.");
|
|
417
|
+
}
|
|
418
|
+
if (attached) {
|
|
419
|
+
throw new Error("Modes runtime is already attached to a Pi extension API.");
|
|
420
|
+
}
|
|
421
|
+
attached = true;
|
|
422
|
+
|
|
423
|
+
modeListener = registry.onModeChange((_from, _to, sessionId) => {
|
|
424
|
+
if (sessionId) {
|
|
425
|
+
refreshSession(pi, sessionId);
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
// Per-call tool filtering: the mode of *this* session decides, nothing global is mutated.
|
|
430
|
+
pi.on("tool_call", (event, ctx) => {
|
|
431
|
+
if (disposed) {
|
|
432
|
+
return { block: false };
|
|
433
|
+
}
|
|
434
|
+
const sessionId = getSessionId(ctx, defaultSessionId);
|
|
435
|
+
if (!sessions.has(sessionId)) {
|
|
436
|
+
return { block: false };
|
|
437
|
+
}
|
|
438
|
+
const tool = toolNameFromEvent(event);
|
|
439
|
+
if (!tool || registry.toolAllowed(tool, sessionId)) {
|
|
440
|
+
return { block: false };
|
|
441
|
+
}
|
|
442
|
+
return {
|
|
443
|
+
block: true,
|
|
444
|
+
reason: `Tool "${tool}" is not available in "${registry.getActiveMode(sessionId).id}" mode.`,
|
|
445
|
+
};
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
pi.on("session_start", (_event, ctx) => {
|
|
449
|
+
if (!disposed) {
|
|
450
|
+
publishSession(pi, ctx);
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
455
|
+
if (disposed) {
|
|
456
|
+
return undefined;
|
|
457
|
+
}
|
|
458
|
+
const sessionId = getSessionId(ctx, defaultSessionId);
|
|
459
|
+
if (!sessions.has(sessionId)) {
|
|
460
|
+
publishSession(pi, ctx);
|
|
461
|
+
} else {
|
|
462
|
+
announceModes(pi, sessionId);
|
|
463
|
+
}
|
|
464
|
+
return undefined;
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
468
|
+
const sessionId = getSessionId(ctx, defaultSessionId);
|
|
469
|
+
const state = sessions.get(sessionId);
|
|
470
|
+
state?.registration.dispose();
|
|
471
|
+
state?.permissionSubscription?.dispose();
|
|
472
|
+
sessions.delete(sessionId);
|
|
473
|
+
registry.clearSession(sessionId);
|
|
474
|
+
resolveUi(sessionId, ctx).setStatus("repi-mode", undefined);
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
pi.registerCommand("permission-mode", {
|
|
478
|
+
description:
|
|
479
|
+
"Switch the mode for this session: /permission-mode [manual|bypass|deny]; Ctrl+S in the picker sets the default for new sessions",
|
|
480
|
+
async handler(args, ctx) {
|
|
481
|
+
const sessionId = getSessionId(ctx, defaultSessionId);
|
|
482
|
+
const target = args.trim();
|
|
483
|
+
if (target.length > 0) {
|
|
484
|
+
switchMode(pi, target, sessionId, ctx);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const current = registry.getActiveMode(sessionId);
|
|
489
|
+
const selected = await pickMode(current.id, sessionId, ctx);
|
|
490
|
+
if (selected) {
|
|
491
|
+
switchMode(pi, selected.modeId, sessionId, ctx, { makeDefault: selected.makeDefault });
|
|
492
|
+
}
|
|
493
|
+
},
|
|
494
|
+
});
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
const dispose = (): void => {
|
|
498
|
+
if (disposed) {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
disposed = true;
|
|
502
|
+
for (const state of sessions.values()) {
|
|
503
|
+
state.registration.dispose();
|
|
504
|
+
state.permissionSubscription?.dispose();
|
|
505
|
+
}
|
|
506
|
+
sessions.clear();
|
|
507
|
+
permissionAttachment?.dispose();
|
|
508
|
+
permissionAttachment = undefined;
|
|
509
|
+
modeListener?.dispose();
|
|
510
|
+
modeListener = undefined;
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
return { registry, attach, dispose };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Return a Pi extension factory; useful for tests and for composition in a custom host. */
|
|
517
|
+
export function createModesPlugin(opts: ModesPluginOptions = {}): (pi: unknown) => void {
|
|
518
|
+
const runtime = createModesRuntime(opts);
|
|
519
|
+
return (pi) => runtime.attach(pi as PiExtensionAPI);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Default Pi entry point (`pi.extensions`). Accepts the host API structurally. */
|
|
523
|
+
export default function modesExtension(pi: unknown): void {
|
|
524
|
+
createModesPlugin()(pi);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** Backwards-compatible export name for hosts that compose extension factories explicitly. */
|
|
528
|
+
export const modesPlugin: (pi: unknown) => void = modesExtension;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Persisted user-level mode preferences. */
|
|
6
|
+
export interface ModesPreferences {
|
|
7
|
+
/** Mode id used by new sessions. Set by Ctrl+S in the selector. */
|
|
8
|
+
readonly defaultMode?: string;
|
|
9
|
+
/** Explicit per-session choices, keyed by Pi session id. */
|
|
10
|
+
readonly sessions?: Readonly<Record<string, string>>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ModesPreferencesStore {
|
|
14
|
+
/** File path when this store is disk-backed; omitted for in-memory stores. */
|
|
15
|
+
readonly path?: string;
|
|
16
|
+
/** Read preferences. Missing files return `{}`; malformed files throw. */
|
|
17
|
+
load(): ModesPreferences;
|
|
18
|
+
/** Persist preferences atomically. */
|
|
19
|
+
save(preferences: ModesPreferences): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class ModesPreferencesError extends Error {
|
|
23
|
+
readonly code = "EMODES_PREFERENCES";
|
|
24
|
+
|
|
25
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
26
|
+
super(message, options);
|
|
27
|
+
this.name = "ModesPreferencesError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const MAX_PERSISTED_SESSIONS = 50;
|
|
32
|
+
|
|
33
|
+
function pruneSessions(sessions?: Readonly<Record<string, string>>): Record<string, string> | undefined {
|
|
34
|
+
if (!sessions) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
const entries = Object.entries(sessions);
|
|
38
|
+
const kept =
|
|
39
|
+
entries.length > MAX_PERSISTED_SESSIONS ? entries.slice(entries.length - MAX_PERSISTED_SESSIONS) : entries;
|
|
40
|
+
if (kept.length === 0) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
kept.sort(([left], [right]) => left.localeCompare(right));
|
|
44
|
+
return Object.fromEntries(kept);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const VERSION = 1;
|
|
48
|
+
|
|
49
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
50
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function validatePreferences(raw: unknown, file: string): ModesPreferences {
|
|
54
|
+
if (!isRecord(raw)) {
|
|
55
|
+
throw new ModesPreferencesError(`Invalid mode preferences in "${file}": expected a JSON object.`);
|
|
56
|
+
}
|
|
57
|
+
if (raw.version !== undefined && raw.version !== VERSION) {
|
|
58
|
+
throw new ModesPreferencesError(
|
|
59
|
+
`Invalid mode preferences in "${file}": unsupported version ${JSON.stringify(raw.version)}.`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const result: { defaultMode?: string; sessions?: Record<string, string> } = {};
|
|
63
|
+
|
|
64
|
+
if (raw.defaultMode !== undefined) {
|
|
65
|
+
if (typeof raw.defaultMode !== "string" || raw.defaultMode.trim().length === 0) {
|
|
66
|
+
throw new ModesPreferencesError(`Invalid "defaultMode" in "${file}": expected a non-empty string.`);
|
|
67
|
+
}
|
|
68
|
+
result.defaultMode = raw.defaultMode.trim();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (raw.sessions !== undefined) {
|
|
72
|
+
if (!isRecord(raw.sessions)) {
|
|
73
|
+
throw new ModesPreferencesError(`Invalid "sessions" in "${file}": expected an object.`);
|
|
74
|
+
}
|
|
75
|
+
const sessions: Record<string, string> = {};
|
|
76
|
+
for (const [sessionId, modeId] of Object.entries(raw.sessions)) {
|
|
77
|
+
if (sessionId.trim().length === 0) {
|
|
78
|
+
throw new ModesPreferencesError(`Invalid session id in "${file}": expected a non-empty key.`);
|
|
79
|
+
}
|
|
80
|
+
if (typeof modeId !== "string" || modeId.trim().length === 0) {
|
|
81
|
+
throw new ModesPreferencesError(
|
|
82
|
+
`Invalid mode for session "${sessionId}" in "${file}": expected a non-empty string.`,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
sessions[sessionId] = modeId.trim();
|
|
86
|
+
}
|
|
87
|
+
if (Object.keys(sessions).length > 0) {
|
|
88
|
+
result.sessions = sessions;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Modes preferences path: `$XDG_CACHE_HOME/repi/permission-system-modes.json`
|
|
97
|
+
* (default `~/.cache/repi/permission-system-modes.json`).
|
|
98
|
+
*
|
|
99
|
+
* The file holds machine-written runtime state (default mode plus per-session choices), not
|
|
100
|
+
* user-authored config, so it lives in the cache directory rather than Pi's extension config folder.
|
|
101
|
+
*/
|
|
102
|
+
export function defaultModesPreferencesPath(env: Readonly<Record<string, string | undefined>> = process.env): string {
|
|
103
|
+
const cacheHome = env.XDG_CACHE_HOME?.trim() || path.join(os.homedir(), ".cache");
|
|
104
|
+
return path.join(cacheHome, "repi", "permission-system-modes.json");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
class FileModesPreferencesStore implements ModesPreferencesStore {
|
|
108
|
+
readonly path: string;
|
|
109
|
+
|
|
110
|
+
constructor(filePath: string) {
|
|
111
|
+
this.path = filePath;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
load(): ModesPreferences {
|
|
115
|
+
let raw: string;
|
|
116
|
+
try {
|
|
117
|
+
raw = fs.readFileSync(this.path, "utf8");
|
|
118
|
+
} catch (err) {
|
|
119
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
120
|
+
return {};
|
|
121
|
+
}
|
|
122
|
+
throw new ModesPreferencesError(`Cannot read mode preferences "${this.path}": ${String(err)}`, { cause: err });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let parsed: unknown;
|
|
126
|
+
try {
|
|
127
|
+
parsed = JSON.parse(raw);
|
|
128
|
+
} catch (err) {
|
|
129
|
+
throw new ModesPreferencesError(`Cannot parse mode preferences "${this.path}": ${String(err)}`, { cause: err });
|
|
130
|
+
}
|
|
131
|
+
return validatePreferences(parsed, this.path);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
save(preferences: ModesPreferences): void {
|
|
135
|
+
const data: Record<string, unknown> = { version: VERSION };
|
|
136
|
+
if (preferences.defaultMode) {
|
|
137
|
+
data.defaultMode = preferences.defaultMode;
|
|
138
|
+
}
|
|
139
|
+
const sessions = pruneSessions(preferences.sessions);
|
|
140
|
+
if (sessions) {
|
|
141
|
+
data.sessions = sessions;
|
|
142
|
+
}
|
|
143
|
+
const body = `${JSON.stringify(data, null, "\t")}\n`;
|
|
144
|
+
const dir = path.dirname(this.path);
|
|
145
|
+
const temp = `${this.path}.${process.pid}.tmp`;
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
149
|
+
fs.writeFileSync(temp, body, { encoding: "utf8", mode: 0o600 });
|
|
150
|
+
try {
|
|
151
|
+
fs.renameSync(temp, this.path);
|
|
152
|
+
} catch (err) {
|
|
153
|
+
// Windows cannot always replace an existing file with rename.
|
|
154
|
+
if (process.platform !== "win32") {
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
fs.rmSync(this.path, { force: true });
|
|
158
|
+
fs.renameSync(temp, this.path);
|
|
159
|
+
}
|
|
160
|
+
} catch (err) {
|
|
161
|
+
try {
|
|
162
|
+
fs.rmSync(temp, { force: true });
|
|
163
|
+
} catch {
|
|
164
|
+
// The original write error is the useful one.
|
|
165
|
+
}
|
|
166
|
+
throw new ModesPreferencesError(`Cannot save mode preferences "${this.path}": ${String(err)}`, { cause: err });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function createModesPreferencesStore(filePath: string = defaultModesPreferencesPath()): ModesPreferencesStore {
|
|
172
|
+
return new FileModesPreferencesStore(filePath);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** In-memory store for tests and hosts that do not want user-level persistence. */
|
|
176
|
+
export class MemoryModesPreferencesStore implements ModesPreferencesStore {
|
|
177
|
+
private current: ModesPreferences;
|
|
178
|
+
|
|
179
|
+
constructor(initial: ModesPreferences = {}) {
|
|
180
|
+
this.current = { ...initial };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
load(): ModesPreferences {
|
|
184
|
+
return { ...this.current, sessions: { ...this.current.sessions } };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
save(preferences: ModesPreferences): void {
|
|
188
|
+
const sessions = pruneSessions(preferences.sessions);
|
|
189
|
+
this.current = { ...preferences, sessions };
|
|
190
|
+
}
|
|
191
|
+
}
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Disposable,
|
|
3
|
+
ModesService,
|
|
4
|
+
PermissionDecision,
|
|
5
|
+
PermissionRequest,
|
|
6
|
+
PermissionService,
|
|
7
|
+
SetModeOptions,
|
|
8
|
+
} from "@restranger/repi-lib";
|
|
9
|
+
import { BUILTIN_MODES, MANUAL_MODE } from "./builtin-modes.js";
|
|
10
|
+
import type { ModeDefinition, ModeRegistryService, RegisterModeOptions } from "./types.js";
|
|
11
|
+
|
|
12
|
+
const DEFAULT_SESSION_ID = "default";
|
|
13
|
+
const MUTATING_TOOL_SET = new Set(["edit", "write", "patch"]);
|
|
14
|
+
|
|
15
|
+
export class ModeConflictError extends Error {
|
|
16
|
+
readonly code = "EMODES_DUPLICATE_MODE";
|
|
17
|
+
|
|
18
|
+
constructor(modeId: string) {
|
|
19
|
+
super(`EMODES_DUPLICATE_MODE: mode "${modeId}" is already registered (pass { override: true } to replace it).`);
|
|
20
|
+
this.name = "ModeConflictError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class UnknownModeError extends Error {
|
|
25
|
+
readonly code = "EMODES_UNKNOWN_MODE";
|
|
26
|
+
|
|
27
|
+
constructor(modeId: string, available: readonly string[]) {
|
|
28
|
+
super(`EMODES_UNKNOWN_MODE: unknown mode "${modeId}". Available modes: ${available.join(", ")}`);
|
|
29
|
+
this.name = "UnknownModeError";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Rewrites only the `ask` verdict. Everything else is the permission engine's decision:
|
|
35
|
+
* explicit `allow` stays allowed, explicit `deny` and hard deny stay denied in every mode.
|
|
36
|
+
*/
|
|
37
|
+
function applyPolicy(policy: ModeDefinition["permissionsPolicy"], decision: PermissionDecision): PermissionDecision {
|
|
38
|
+
if (decision.action !== "ask") {
|
|
39
|
+
return decision;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (policy === "bypass") {
|
|
43
|
+
return {
|
|
44
|
+
action: "allow",
|
|
45
|
+
ruleId: decision.ruleId,
|
|
46
|
+
reason: "Auto-approved by bypass mode",
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (policy === "deny") {
|
|
51
|
+
return {
|
|
52
|
+
action: "deny",
|
|
53
|
+
ruleId: decision.ruleId,
|
|
54
|
+
reason: "Auto-denied by deny mode: this action requires confirmation",
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return decision;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class ModeRegistry implements ModeRegistryService, ModesService {
|
|
62
|
+
private modes = new Map<string, ModeDefinition>();
|
|
63
|
+
private sessionModes = new Map<string, ModeDefinition>();
|
|
64
|
+
private listeners = new Set<(from: ModeDefinition, to: ModeDefinition, sessionId?: string) => void>();
|
|
65
|
+
private defaultSessionId = DEFAULT_SESSION_ID;
|
|
66
|
+
private defaultModeId = MANUAL_MODE.id;
|
|
67
|
+
private permissionTransformer?: Disposable;
|
|
68
|
+
|
|
69
|
+
constructor(permissionService?: PermissionService, modes: readonly ModeDefinition[] = BUILTIN_MODES) {
|
|
70
|
+
for (const mode of modes) {
|
|
71
|
+
this.modes.set(mode.id, mode);
|
|
72
|
+
}
|
|
73
|
+
if (permissionService) {
|
|
74
|
+
this.attachPermissionEngine(permissionService);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Attach the permission engine and return a disposable that detaches only this attachment.
|
|
80
|
+
* Re-attaching replaces the previous transformer, which is what a reload needs.
|
|
81
|
+
*/
|
|
82
|
+
attachPermissionEngine(perm: PermissionService): Disposable {
|
|
83
|
+
this.permissionTransformer?.dispose();
|
|
84
|
+
|
|
85
|
+
// One transformer for all sessions: the mode is resolved per request, which is what makes
|
|
86
|
+
// per-session isolation work (a session-wide transformer used to leak bypass everywhere).
|
|
87
|
+
const transformer = (decision: PermissionDecision, req: PermissionRequest) => this.applyDecision(decision, req);
|
|
88
|
+
const handle = perm.addDecisionTransformer(transformer);
|
|
89
|
+
this.permissionTransformer = handle;
|
|
90
|
+
|
|
91
|
+
let disposed = false;
|
|
92
|
+
return {
|
|
93
|
+
dispose: () => {
|
|
94
|
+
if (disposed) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
disposed = true;
|
|
98
|
+
if (this.permissionTransformer === handle) {
|
|
99
|
+
this.permissionTransformer = undefined;
|
|
100
|
+
}
|
|
101
|
+
handle.dispose();
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
applyDecision(decision: PermissionDecision, req: PermissionRequest): PermissionDecision {
|
|
107
|
+
const mode = this.getActiveMode(req.sessionId);
|
|
108
|
+
const policyApplied = applyPolicy(mode.permissionsPolicy, decision);
|
|
109
|
+
return mode.decisionTransformer ? mode.decisionTransformer(policyApplied, req) : policyApplied;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
registerMode(def: ModeDefinition, opts?: RegisterModeOptions): Disposable {
|
|
113
|
+
const existing = this.modes.get(def.id);
|
|
114
|
+
if (existing && !opts?.override) {
|
|
115
|
+
throw new ModeConflictError(def.id);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
this.modes.set(def.id, def);
|
|
119
|
+
|
|
120
|
+
let disposed = false;
|
|
121
|
+
return {
|
|
122
|
+
dispose: () => {
|
|
123
|
+
if (disposed) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
disposed = true;
|
|
127
|
+
if (this.modes.get(def.id) !== def) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (existing) {
|
|
131
|
+
this.modes.set(def.id, existing);
|
|
132
|
+
for (const [sessionId, mode] of this.sessionModes) {
|
|
133
|
+
if (mode.id === def.id) {
|
|
134
|
+
this.sessionModes.set(sessionId, existing);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
} else {
|
|
138
|
+
this.modes.delete(def.id);
|
|
139
|
+
for (const [sessionId, mode] of this.sessionModes) {
|
|
140
|
+
if (mode.id === def.id) {
|
|
141
|
+
this.sessionModes.delete(sessionId);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
setMode(modeId: string, opts?: SetModeOptions): void {
|
|
150
|
+
const sessionId = opts?.sessionId ?? this.defaultSessionId;
|
|
151
|
+
const resolvedId = modeId === "default" && !this.modes.has("default") ? "manual" : modeId;
|
|
152
|
+
const target = this.modes.get(resolvedId);
|
|
153
|
+
if (!target) {
|
|
154
|
+
throw new UnknownModeError(modeId, [...this.modes.keys()].sort());
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const previous = this.getActiveMode(sessionId);
|
|
158
|
+
this.sessionModes.set(sessionId, target);
|
|
159
|
+
|
|
160
|
+
for (const listener of this.listeners) {
|
|
161
|
+
try {
|
|
162
|
+
listener(previous, target, sessionId);
|
|
163
|
+
} catch {
|
|
164
|
+
// A UI listener must never break a mode switch; the host logs plugin errors.
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
getActiveMode(sessionId: string = this.defaultSessionId): ModeDefinition {
|
|
170
|
+
return this.sessionModes.get(sessionId) ?? this.getDefaultMode();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Mode used by sessions that have not selected one explicitly. */
|
|
174
|
+
getDefaultMode(): ModeDefinition {
|
|
175
|
+
return this.modes.get(this.defaultModeId) ?? this.modes.get(MANUAL_MODE.id) ?? MANUAL_MODE;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Change the default mode for sessions without an explicit selection.
|
|
180
|
+
* Existing per-session selections are preserved; callers that need every session changed
|
|
181
|
+
* should also call `setMode` for those sessions.
|
|
182
|
+
*/
|
|
183
|
+
setDefaultMode(modeId: string): void {
|
|
184
|
+
const resolvedId = modeId === "default" && !this.modes.has("default") ? "manual" : modeId;
|
|
185
|
+
if (!this.modes.has(resolvedId)) {
|
|
186
|
+
throw new UnknownModeError(modeId, [...this.modes.keys()].sort());
|
|
187
|
+
}
|
|
188
|
+
this.defaultModeId = resolvedId;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
listModes(): readonly ModeDefinition[] {
|
|
192
|
+
return [...this.modes.values()].sort((a, b) => a.id.localeCompare(b.id));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Whether the session's mode permits a tool. Filtering is per call, never global state. */
|
|
196
|
+
toolAllowed(toolName: string, sessionId = this.defaultSessionId): boolean {
|
|
197
|
+
const filter = this.getActiveMode(sessionId).toolsFilter;
|
|
198
|
+
if (!filter) {
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
if (filter.allow && !filter.allow.includes(toolName)) {
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
if (filter.deny?.includes(toolName)) {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
if (filter.readOnly && MUTATING_TOOL_SET.has(toolName)) {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
activeTools(allTools: readonly string[], sessionId = this.defaultSessionId): readonly string[] {
|
|
214
|
+
return allTools.filter((name) => this.toolAllowed(name, sessionId));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
clearSession(sessionId: string): void {
|
|
218
|
+
const previous = this.getActiveMode(sessionId);
|
|
219
|
+
this.sessionModes.delete(sessionId);
|
|
220
|
+
const target = this.getDefaultMode();
|
|
221
|
+
|
|
222
|
+
if (previous.id !== target.id) {
|
|
223
|
+
for (const listener of this.listeners) {
|
|
224
|
+
try {
|
|
225
|
+
listener(previous, target, sessionId);
|
|
226
|
+
} catch {
|
|
227
|
+
// ignore listener failures
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
onModeChange(handler: (from: ModeDefinition, to: ModeDefinition, sessionId?: string) => void): Disposable {
|
|
234
|
+
this.listeners.add(handler);
|
|
235
|
+
let disposed = false;
|
|
236
|
+
|
|
237
|
+
return {
|
|
238
|
+
dispose: () => {
|
|
239
|
+
if (disposed) {
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
disposed = true;
|
|
243
|
+
this.listeners.delete(handler);
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Disposable,
|
|
3
|
+
ModeSummary,
|
|
4
|
+
PermissionDecision,
|
|
5
|
+
PermissionRequest,
|
|
6
|
+
PermissionService,
|
|
7
|
+
SetModeOptions,
|
|
8
|
+
Tone,
|
|
9
|
+
} from "@restranger/repi-lib";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* How a mode treats an `ask` verdict produced by `@restranger/repi-permission-system-core`.
|
|
13
|
+
*
|
|
14
|
+
* The engine already answers `allow` for explicit allow rules and `deny` for explicit deny rules,
|
|
15
|
+
* hard deny, secrets and catastrophic commands. A mode only decides what to do with the rest:
|
|
16
|
+
*
|
|
17
|
+
* - `manual` — keep `ask` as is;
|
|
18
|
+
* - `bypass` — turn `ask` into `allow`;
|
|
19
|
+
* - `deny` — turn `ask` into `deny`.
|
|
20
|
+
*/
|
|
21
|
+
export type PermissionsPolicyType = "manual" | "bypass" | "deny";
|
|
22
|
+
|
|
23
|
+
export type ModeDecisionTransformer = (decision: PermissionDecision, req: PermissionRequest) => PermissionDecision;
|
|
24
|
+
|
|
25
|
+
export interface ModeToolsFilter {
|
|
26
|
+
/** Whitelist; when present only these tools stay visible. */
|
|
27
|
+
readonly allow?: readonly string[];
|
|
28
|
+
/** Blacklist; these tools are hidden from the model. */
|
|
29
|
+
readonly deny?: readonly string[];
|
|
30
|
+
/** Hide tools that mutate files (`edit`, `write`, `patch`, ...). */
|
|
31
|
+
readonly readOnly?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ModeDefinition extends ModeSummary {
|
|
35
|
+
/** What happens to `ask` decisions while this mode is active. */
|
|
36
|
+
readonly permissionsPolicy: PermissionsPolicyType;
|
|
37
|
+
/** Tool-level constraints for the model. */
|
|
38
|
+
readonly toolsFilter?: ModeToolsFilter;
|
|
39
|
+
/** Optional custom override applied after `permissionsPolicy`. */
|
|
40
|
+
readonly decisionTransformer?: ModeDecisionTransformer;
|
|
41
|
+
/** Status-line badge. */
|
|
42
|
+
readonly badge: {
|
|
43
|
+
readonly label: string;
|
|
44
|
+
readonly tone: Tone;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface RegisterModeOptions {
|
|
49
|
+
/** Allow replacing a built-in or an already registered mode. Defaults to `false`. */
|
|
50
|
+
readonly override?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ModeRegistryService {
|
|
54
|
+
/** Register a new mode; throws on a conflicting id unless `override` is set. */
|
|
55
|
+
registerMode(def: ModeDefinition, opts?: RegisterModeOptions): Disposable;
|
|
56
|
+
/** Switch the active mode of a session. */
|
|
57
|
+
setMode(modeId: string, opts?: SetModeOptions): void;
|
|
58
|
+
/** Current mode for a session. */
|
|
59
|
+
getActiveMode(sessionId?: string): ModeDefinition;
|
|
60
|
+
/** Mode used by sessions without an explicit selection. */
|
|
61
|
+
getDefaultMode(): ModeDefinition;
|
|
62
|
+
/** Change the default mode used by sessions without an explicit selection. */
|
|
63
|
+
setDefaultMode(modeId: string): void;
|
|
64
|
+
/** All registered modes, sorted by id for stable output. */
|
|
65
|
+
listModes(): readonly ModeDefinition[];
|
|
66
|
+
/** Subscribe to mode changes. */
|
|
67
|
+
onModeChange(handler: (from: ModeDefinition, to: ModeDefinition, sessionId?: string) => void): Disposable;
|
|
68
|
+
/** Compute the tool set visible to the model for the session's active mode. */
|
|
69
|
+
activeTools(allTools: readonly string[], sessionId?: string): readonly string[];
|
|
70
|
+
/** Reset a session to the default mode (used on session shutdown). */
|
|
71
|
+
clearSession(sessionId: string): void;
|
|
72
|
+
/** Attach the permission engine; mode policies then apply per session. */
|
|
73
|
+
attachPermissionEngine(perm: PermissionService): Disposable;
|
|
74
|
+
}
|
package/README.md
DELETED