@restranger/repi-lib 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/README.md +90 -2
- package/package.json +26 -5
- package/src/completion.ts +61 -0
- package/src/config.ts +107 -0
- package/src/contracts/advisor.ts +20 -0
- package/src/contracts/index.ts +5 -0
- package/src/contracts/modes.ts +31 -0
- package/src/contracts/permissions.ts +241 -0
- package/src/contracts/subagents.ts +18 -0
- package/src/contracts/ui.ts +25 -0
- package/src/contracts.ts +39 -0
- package/src/disposable.ts +29 -0
- package/src/index.ts +11 -0
- package/src/model-scoring.ts +118 -0
- package/src/pi.ts +285 -0
- package/src/seam.ts +205 -0
- package/src/session.ts +28 -0
- package/src/shimmer.ts +275 -0
- package/src/text.ts +344 -0
package/README.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @restranger/repi-lib
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Общая библиотека для независимых repi-плагинов. Это **не плагин** и не ядро: `lib` не загружает
|
|
4
|
+
расширения, не знает про `permissions`, `modes` или `ui` и не имеет зависимостей от других
|
|
5
|
+
`@restranger/repi-*` пакетов.
|
|
6
|
+
|
|
7
|
+
## Зачем
|
|
8
|
+
|
|
9
|
+
Pi загружает каждое расширение отдельно и даёт ему `ExtensionAPI`. Плагинам нужен только один
|
|
10
|
+
общий слой, чтобы находить друг друга, когда они установлены вместе, и не падать, когда соседа нет.
|
|
11
|
+
|
|
12
|
+
`lib` даёт четыре вещи:
|
|
13
|
+
|
|
14
|
+
- **contracts** — id контракта с мажорной версией (`re:permissions@1`, `re:modes@1`, `re:ui@1`),
|
|
15
|
+
формы сервисов и `ReadyEvent`;
|
|
16
|
+
- **seam** — process-global реестр сервисов с ключом `contract + sessionId`;
|
|
17
|
+
- **session** — единый способ получить `sessionId` из контекста хоста;
|
|
18
|
+
- **shared types** — `ViewNode`, `Tone`, `Disposable` и структурные типы Pi, чтобы плагинам не
|
|
19
|
+
приходилось импортировать друг друга или тянуть тяжёлый host-пакет в тесты.
|
|
20
|
+
|
|
21
|
+
## Провайдер
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { announceReady, getSessionId, publishService } from "@restranger/repi-lib";
|
|
25
|
+
|
|
26
|
+
export default function permissionsPlugin(pi) {
|
|
27
|
+
const registrations = new Map();
|
|
28
|
+
|
|
29
|
+
pi.on("session_start", (_event, ctx) => {
|
|
30
|
+
const sessionId = getSessionId(ctx);
|
|
31
|
+
registrations.get(sessionId)?.dispose();
|
|
32
|
+
const registration = publishService({
|
|
33
|
+
contract: "re:permissions@1",
|
|
34
|
+
sessionId,
|
|
35
|
+
owner: "repi:permissions",
|
|
36
|
+
impl: permissionsService,
|
|
37
|
+
});
|
|
38
|
+
registrations.set(sessionId, registration);
|
|
39
|
+
|
|
40
|
+
announceReady(pi.events, {
|
|
41
|
+
contract: "re:permissions@1",
|
|
42
|
+
version: 1,
|
|
43
|
+
sessionId,
|
|
44
|
+
owner: "repi:permissions",
|
|
45
|
+
capabilities: ["policy-layer", "decision-events"],
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
50
|
+
const sessionId = getSessionId(ctx);
|
|
51
|
+
registrations.get(sessionId)?.dispose();
|
|
52
|
+
registrations.delete(sessionId);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Потребитель
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { getService, onService } from "@restranger/repi-lib";
|
|
61
|
+
|
|
62
|
+
const current = getService<PermissionsService>("re:permissions@1", sessionId);
|
|
63
|
+
if (current) {
|
|
64
|
+
attach(current);
|
|
65
|
+
} else {
|
|
66
|
+
// Standalone path: permissions not installed, keep working without it.
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const registration = onService<PermissionsService>(
|
|
70
|
+
pi.events,
|
|
71
|
+
"re:permissions@1",
|
|
72
|
+
sessionId,
|
|
73
|
+
(permissions) => attach(permissions),
|
|
74
|
+
);
|
|
75
|
+
pi.on("session_shutdown", () => registration.dispose());
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`onService` сначала подписывается на `repi:ready:v1`, затем делает pull из реестра: публикация
|
|
79
|
+
между этими шагами не теряется. Повторный announce того же сервиса не вызывает обработчик дважды.
|
|
80
|
+
|
|
81
|
+
## Правила
|
|
82
|
+
|
|
83
|
+
- Плагин зависит от `@restranger/repi-lib`, но **никогда** от другого плагина.
|
|
84
|
+
- В рантайме — только `getService` / `onService`; никаких статических импортов чужого плагина.
|
|
85
|
+
- `import type` из чужого плагина тоже не нужен: общие типы живут в `lib`.
|
|
86
|
+
- `sessionId` — часть ключа. Один процесс может содержать несколько сессий; сервисы не должны
|
|
87
|
+
протекать между ними.
|
|
88
|
+
- `publishService` одного владельца заменяет свой же сервис при reload; другой владелец — ошибка.
|
|
89
|
+
- `dispose` идемпотентен и удаляет только свою запись.
|
|
90
|
+
- `globalThis` + `Symbol.for` используются потому, что jiti изолирует модули между расширениями.
|
|
91
|
+
Обычный module-level singleton не будет общим.
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@restranger/repi-lib",
|
|
3
|
+
"version": "0.0.1-1a48fc0",
|
|
4
|
+
"description": "Contracts, service seam registry, TUI display primitives, and session utilities for repi plugins",
|
|
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", "contracts", "seam"],
|
|
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/lib"
|
|
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
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { PiAutocompleteItem } from "./pi.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* One slot of a `/command` argument chain.
|
|
5
|
+
*
|
|
6
|
+
* A declaration is the whole truth about its own slots: a node with `options` continues, a node
|
|
7
|
+
* without them takes free text (`/subagents stop <any id>`), and completing past it offers
|
|
8
|
+
* nothing instead of guessing.
|
|
9
|
+
*/
|
|
10
|
+
export interface ArgumentChoice {
|
|
11
|
+
/** Token inserted for this slot. */
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly description?: string;
|
|
14
|
+
/** Candidates for the next slot; absent or empty means the rest of the arguments are free text. */
|
|
15
|
+
readonly options?: readonly ArgumentChoice[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function toItem(settled: readonly string[], choice: ArgumentChoice): PiAutocompleteItem {
|
|
19
|
+
const value = [...settled, choice.name].join(" ");
|
|
20
|
+
return {
|
|
21
|
+
// A further slot follows: keep the cursor past the separating space so the next Tab descends
|
|
22
|
+
// instead of offering the level the user just accepted.
|
|
23
|
+
value: choice.options && choice.options.length > 0 ? `${value} ` : value,
|
|
24
|
+
label: choice.name,
|
|
25
|
+
...(choice.description ? { description: choice.description } : {}),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Argument completions for a subcommand tree.
|
|
31
|
+
*
|
|
32
|
+
* Pi hands over the raw text after the command name and replaces all of it with the chosen
|
|
33
|
+
* `value`, so entries are built from the tokens already typed plus the candidate. A trailing space
|
|
34
|
+
* means the user is starting a new token; otherwise the last token is partial and only filters.
|
|
35
|
+
* Returns null when there is nothing sensible to offer, which also keeps Pi from opening an empty
|
|
36
|
+
* picker.
|
|
37
|
+
*/
|
|
38
|
+
export function completeArguments(prefix: string, choices: readonly ArgumentChoice[]): PiAutocompleteItem[] | null {
|
|
39
|
+
const complete = /\s$/u.test(prefix);
|
|
40
|
+
const trimmed = prefix.trim();
|
|
41
|
+
const tokens = trimmed.length === 0 ? [] : trimmed.split(/\s+/u);
|
|
42
|
+
const settled = complete ? tokens : tokens.slice(0, -1);
|
|
43
|
+
const partial = (complete ? "" : (tokens[tokens.length - 1] ?? "")).toLowerCase();
|
|
44
|
+
|
|
45
|
+
let level = choices;
|
|
46
|
+
for (const token of settled) {
|
|
47
|
+
const next = level.find((choice) => choice.name.toLowerCase() === token.toLowerCase());
|
|
48
|
+
if (!next?.options || next.options.length === 0) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
level = next.options;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const matching = level.filter((choice) => choice.name.toLowerCase().startsWith(partial));
|
|
55
|
+
// Prefix first, then a substring pass so a half-remembered middle word still completes.
|
|
56
|
+
const pool =
|
|
57
|
+
matching.length > 0 || partial.length === 0
|
|
58
|
+
? matching
|
|
59
|
+
: level.filter((choice) => choice.name.toLowerCase().includes(partial));
|
|
60
|
+
return pool.length === 0 ? null : pool.map((choice) => toItem(settled, choice));
|
|
61
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, join, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* One config layer, lowest priority first.
|
|
7
|
+
*
|
|
8
|
+
* Plugins read a user layer from `<agentDir>/extensions/<ext>.json` and a project layer from
|
|
9
|
+
* `<cwd>/.pi/extensions/<ext>.json` (or `<cwd>/.repi`), gated on workspace trust.
|
|
10
|
+
*/
|
|
11
|
+
export interface PluginConfigLayer {
|
|
12
|
+
readonly source: "user" | "project";
|
|
13
|
+
readonly path: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** One problem found while loading or applying a plugin config file. */
|
|
17
|
+
export type PluginDiagnosticLevel = "warning" | "error";
|
|
18
|
+
|
|
19
|
+
export interface PluginDiagnostic {
|
|
20
|
+
readonly level: PluginDiagnosticLevel;
|
|
21
|
+
readonly message: string;
|
|
22
|
+
/** File (or directory) the problem came from, when it is known. */
|
|
23
|
+
readonly path?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ConfigLayerOptions {
|
|
27
|
+
readonly cwd: string;
|
|
28
|
+
/** Defaults to `os.homedir()`; injectable for tests. */
|
|
29
|
+
readonly homeDir?: string;
|
|
30
|
+
/** Defaults to `process.env`; `PI_CODING_AGENT_DIR` is honored. */
|
|
31
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
32
|
+
/** File name inside the config directory. */
|
|
33
|
+
readonly filename: string;
|
|
34
|
+
/** When false, the project layer is not read at all (fail-closed). */
|
|
35
|
+
readonly workspaceTrusted?: boolean;
|
|
36
|
+
/** Project directory name; defaults to `.repi` when legacy resolution is used. */
|
|
37
|
+
readonly projectDir?: string;
|
|
38
|
+
/** Name of extension folder/file under extensions/, e.g. "repi-subagents", "repi-permissions". */
|
|
39
|
+
readonly extensionName?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const EXTENSION_NAME_MAP: Record<string, string> = {
|
|
43
|
+
"subagents.json": "repi-subagents",
|
|
44
|
+
"permissions.json": "repi-permissions",
|
|
45
|
+
"model-fallback.json": "repi-model-fallback",
|
|
46
|
+
"advisor.json": "repi-advisor",
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export function inferExtensionName(filename: string): string | undefined {
|
|
50
|
+
return EXTENSION_NAME_MAP[filename] ?? EXTENSION_NAME_MAP[basename(filename)];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function findLayerPath(baseCandidates: string[], fallbackPath: string): string {
|
|
54
|
+
for (const candidate of baseCandidates) {
|
|
55
|
+
if (existsSync(candidate)) {
|
|
56
|
+
return candidate;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return fallbackPath;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Resolve the user and (trusted) project layers for one config file. */
|
|
63
|
+
export function resolveConfigLayers(options: ConfigLayerOptions): PluginConfigLayer[] {
|
|
64
|
+
const home = options.homeDir ?? homedir();
|
|
65
|
+
const env = options.env ?? process.env;
|
|
66
|
+
const agentDir = env.PI_CODING_AGENT_DIR ?? join(home, ".pi", "agent");
|
|
67
|
+
const extName = options.extensionName ?? inferExtensionName(options.filename);
|
|
68
|
+
|
|
69
|
+
let userPath: string;
|
|
70
|
+
if (extName) {
|
|
71
|
+
const userCandidates = [
|
|
72
|
+
join(agentDir, "extensions", `${extName}.json`),
|
|
73
|
+
join(agentDir, "extensions", extName, "config.json"),
|
|
74
|
+
join(agentDir, "extensions", extName, options.filename),
|
|
75
|
+
];
|
|
76
|
+
userPath = findLayerPath(userCandidates, join(agentDir, "extensions", `${extName}.json`));
|
|
77
|
+
} else {
|
|
78
|
+
userPath = join(agentDir, "extensions", options.filename);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const layers: PluginConfigLayer[] = [{ source: "user", path: userPath }];
|
|
82
|
+
|
|
83
|
+
if (options.workspaceTrusted !== false) {
|
|
84
|
+
let projectPath: string;
|
|
85
|
+
if (options.projectDir) {
|
|
86
|
+
projectPath = join(resolve(options.cwd), options.projectDir, options.filename);
|
|
87
|
+
} else if (extName) {
|
|
88
|
+
const projectCandidates = [
|
|
89
|
+
join(resolve(options.cwd), ".pi", "extensions", `${extName}.json`),
|
|
90
|
+
join(resolve(options.cwd), ".pi", "extensions", extName, "config.json"),
|
|
91
|
+
join(resolve(options.cwd), ".pi", "extensions", extName, options.filename),
|
|
92
|
+
join(resolve(options.cwd), ".repi", options.filename),
|
|
93
|
+
];
|
|
94
|
+
projectPath = findLayerPath(
|
|
95
|
+
projectCandidates,
|
|
96
|
+
join(resolve(options.cwd), ".pi", "extensions", `${extName}.json`),
|
|
97
|
+
);
|
|
98
|
+
} else {
|
|
99
|
+
projectPath = join(resolve(options.cwd), ".repi", options.filename);
|
|
100
|
+
}
|
|
101
|
+
layers.push({
|
|
102
|
+
source: "project",
|
|
103
|
+
path: projectPath,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return layers;
|
|
107
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export const ADVISOR_CONTRACT_ID = "re:advisor@1";
|
|
2
|
+
|
|
3
|
+
/** Summary of the active advisor configuration published through the service seam. */
|
|
4
|
+
export interface AdvisorSummary {
|
|
5
|
+
readonly model?: string;
|
|
6
|
+
readonly effort?: string;
|
|
7
|
+
readonly fallbackModels?: readonly string[];
|
|
8
|
+
readonly isBlocked?: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Service published by @restranger/repi-advisor.
|
|
13
|
+
* Allows other plugins (e.g. model-fallback) to inspect and configure advisor models and fallbacks.
|
|
14
|
+
*/
|
|
15
|
+
export interface AdvisorService {
|
|
16
|
+
getAdvisor(): AdvisorSummary | undefined;
|
|
17
|
+
setAdvisorModel?(model: string | undefined): void;
|
|
18
|
+
setAdvisorEffort?(effort: string | undefined): void;
|
|
19
|
+
setAdvisorFallbackModels?(fallbackModels: readonly string[]): void;
|
|
20
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Disposable } from "../disposable.js";
|
|
2
|
+
|
|
3
|
+
export const MODES_CONTRACT_ID = "re:modes@1";
|
|
4
|
+
|
|
5
|
+
/** The smallest projection of a mode that another plugin may safely rely on. */
|
|
6
|
+
export interface ModeSummary {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly description: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SetModeOptions {
|
|
13
|
+
/** Target session; defaults to the registry's default session. */
|
|
14
|
+
readonly sessionId?: string;
|
|
15
|
+
/** Arbitrary mode payload kept per session. */
|
|
16
|
+
readonly data?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Optional integration surface published by @restranger/repi-permission-system-modes.
|
|
21
|
+
*
|
|
22
|
+
* Standalone consumers must treat every method as optional in spirit: without the modes service
|
|
23
|
+
* they simply do not show a badge or change tool sets. The subset here is intentionally narrower
|
|
24
|
+
* than the package's own `ModeRegistryService`.
|
|
25
|
+
*/
|
|
26
|
+
export interface ModesService {
|
|
27
|
+
getActiveMode(sessionId?: string): ModeSummary;
|
|
28
|
+
listModes(): readonly ModeSummary[];
|
|
29
|
+
setMode(modeId: string, opts?: SetModeOptions): void;
|
|
30
|
+
onModeChange(handler: (from: ModeSummary, to: ModeSummary, sessionId?: string) => void): Disposable;
|
|
31
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import type { Disposable } from "../disposable.js";
|
|
2
|
+
|
|
3
|
+
/** Contract id: major version is part of the id, additive changes stay within major 1. */
|
|
4
|
+
export const PERMISSIONS_CONTRACT_ID = "re:permissions@1";
|
|
5
|
+
|
|
6
|
+
export type PermissionAction = "allow" | "deny" | "ask" | "rewrite";
|
|
7
|
+
|
|
8
|
+
export type PermissionSource = "agent" | "subagent" | "plugin" | "user";
|
|
9
|
+
|
|
10
|
+
export type RiskLevel = "low" | "medium" | "high" | "critical";
|
|
11
|
+
|
|
12
|
+
export type GrantScope = "command" | "path";
|
|
13
|
+
|
|
14
|
+
export interface PermissionRequest {
|
|
15
|
+
/** Tool name being called: "bash", "read", "edit", "write", etc. */
|
|
16
|
+
readonly tool: string;
|
|
17
|
+
/** Input parameters passed to the tool. */
|
|
18
|
+
readonly input: Record<string, unknown>;
|
|
19
|
+
/** Current working directory. */
|
|
20
|
+
readonly cwd: string;
|
|
21
|
+
/** Source of call; defaults to "agent". */
|
|
22
|
+
readonly source?: PermissionSource;
|
|
23
|
+
/** Current session id; defaults to "default". */
|
|
24
|
+
readonly sessionId?: string;
|
|
25
|
+
/** Turn index; defaults to 0. */
|
|
26
|
+
readonly turnIndex?: number;
|
|
27
|
+
/** Cancellation for long-running checks. */
|
|
28
|
+
readonly signal?: AbortSignal;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type PermissionDecision =
|
|
32
|
+
| { readonly action: "allow"; readonly ruleId?: string; readonly reason?: string }
|
|
33
|
+
| {
|
|
34
|
+
readonly action: "deny";
|
|
35
|
+
readonly ruleId?: string;
|
|
36
|
+
readonly reason: string;
|
|
37
|
+
readonly prompt?: string;
|
|
38
|
+
readonly suggestedAlternative?: string;
|
|
39
|
+
}
|
|
40
|
+
| {
|
|
41
|
+
readonly action: "ask";
|
|
42
|
+
readonly ruleId?: string;
|
|
43
|
+
readonly prompt: string;
|
|
44
|
+
readonly reason?: string;
|
|
45
|
+
readonly riskLevel?: RiskLevel;
|
|
46
|
+
}
|
|
47
|
+
| {
|
|
48
|
+
readonly action: "rewrite";
|
|
49
|
+
readonly ruleId?: string;
|
|
50
|
+
readonly modifiedInput: Record<string, unknown>;
|
|
51
|
+
readonly note: string;
|
|
52
|
+
readonly reason?: string;
|
|
53
|
+
readonly prompt?: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export interface CreateDecisionOptions {
|
|
57
|
+
ruleId?: string;
|
|
58
|
+
reason?: string;
|
|
59
|
+
prompt?: string;
|
|
60
|
+
riskLevel?: RiskLevel;
|
|
61
|
+
suggestedAlternative?: string;
|
|
62
|
+
modifiedInput?: Record<string, unknown>;
|
|
63
|
+
note?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Builds a decision without losing information: a `rewrite` without `modifiedInput` is a bug,
|
|
68
|
+
* so it is rejected instead of silently producing an empty replacement.
|
|
69
|
+
*/
|
|
70
|
+
export function createDecision(action: PermissionAction, opts: CreateDecisionOptions = {}): PermissionDecision {
|
|
71
|
+
if (action === "deny") {
|
|
72
|
+
return {
|
|
73
|
+
action: "deny",
|
|
74
|
+
ruleId: opts.ruleId,
|
|
75
|
+
reason: opts.reason ?? "Denied by security policy",
|
|
76
|
+
prompt: opts.prompt,
|
|
77
|
+
suggestedAlternative: opts.suggestedAlternative,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
if (action === "ask") {
|
|
81
|
+
return {
|
|
82
|
+
action: "ask",
|
|
83
|
+
ruleId: opts.ruleId,
|
|
84
|
+
prompt: opts.prompt ?? "Confirmation required",
|
|
85
|
+
reason: opts.reason,
|
|
86
|
+
riskLevel: opts.riskLevel,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (action === "rewrite") {
|
|
90
|
+
if (!opts.modifiedInput) {
|
|
91
|
+
throw new TypeError(
|
|
92
|
+
`createDecision("rewrite") requires modifiedInput (ruleId: ${opts.ruleId ?? "unknown"}): a rewrite without replacement arguments would wipe the tool input.`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
action: "rewrite",
|
|
97
|
+
ruleId: opts.ruleId,
|
|
98
|
+
modifiedInput: opts.modifiedInput,
|
|
99
|
+
note: opts.note ?? "",
|
|
100
|
+
reason: opts.reason,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
return { action: "allow", ruleId: opts.ruleId, reason: opts.reason };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface PermissionRuleMatch {
|
|
107
|
+
readonly surface: "path" | "bash" | "tool" | "mcp" | "subagent";
|
|
108
|
+
readonly pattern: string;
|
|
109
|
+
readonly action: PermissionAction;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface PermissionExplanation {
|
|
113
|
+
readonly request: PermissionRequest;
|
|
114
|
+
readonly canonicalPath?: string;
|
|
115
|
+
readonly targetCommand?: string;
|
|
116
|
+
readonly decomposedCommands: readonly string[];
|
|
117
|
+
readonly matchedRules: readonly PermissionRuleMatch[];
|
|
118
|
+
readonly decision: PermissionDecision;
|
|
119
|
+
readonly durationMs: number;
|
|
120
|
+
/** Set when the pipeline could not evaluate the request; the decision is always `deny`. */
|
|
121
|
+
readonly error?: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export type PermissionDecisionTransformer = (
|
|
125
|
+
decision: PermissionDecision,
|
|
126
|
+
req: PermissionRequest,
|
|
127
|
+
) => PermissionDecision;
|
|
128
|
+
|
|
129
|
+
export type AskChoice = "allow_once" | "allow_session" | "deny" | "deny_with_feedback";
|
|
130
|
+
|
|
131
|
+
export interface AskPrompt {
|
|
132
|
+
readonly title: string;
|
|
133
|
+
readonly message: string;
|
|
134
|
+
readonly detail?: string;
|
|
135
|
+
readonly riskLevel: RiskLevel;
|
|
136
|
+
readonly ruleId?: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface AskAnswer {
|
|
140
|
+
readonly choice: AskChoice;
|
|
141
|
+
readonly feedback?: string;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Abort plumbing for a pending ask; aborting dismisses the dialog. */
|
|
145
|
+
export interface AskContext {
|
|
146
|
+
readonly signal?: AbortSignal;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export type AskUser = (
|
|
150
|
+
prompt: AskPrompt,
|
|
151
|
+
req: PermissionRequest,
|
|
152
|
+
context?: AskContext,
|
|
153
|
+
) => Promise<AskAnswer | undefined>;
|
|
154
|
+
|
|
155
|
+
export interface PermissionDecisionEvent {
|
|
156
|
+
readonly request: PermissionRequest;
|
|
157
|
+
readonly decision: PermissionDecision;
|
|
158
|
+
readonly sessionId: string;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface PermissionService {
|
|
162
|
+
/** Check tool call against the security pipeline (fail-closed). */
|
|
163
|
+
check(req: PermissionRequest): Promise<PermissionDecision>;
|
|
164
|
+
/** Step-by-step evaluation trace; never throws, a broken pipeline yields `deny` plus `error`. */
|
|
165
|
+
explain(req: PermissionRequest): Promise<PermissionExplanation>;
|
|
166
|
+
/** Grant a temporary permission pattern for one session. */
|
|
167
|
+
grantSession(pattern: string, scope?: GrantScope, sessionId?: string): void;
|
|
168
|
+
/** Clear session grants (all sessions when `sessionId` is omitted). */
|
|
169
|
+
clearSessionGrants(sessionId?: string): void;
|
|
170
|
+
/** Replace the external decision transformer (e.g. from @restranger/repi-permission-system-modes). */
|
|
171
|
+
setDecisionTransformer(transformer: PermissionDecisionTransformer | null): void;
|
|
172
|
+
/** Append a transformer; hard-deny decisions remain frozen even if a transformer tries to lift them. */
|
|
173
|
+
addDecisionTransformer(transformer: PermissionDecisionTransformer): Disposable;
|
|
174
|
+
/** Conservative read-only check used by modes; unknown commands are treated as mutating. */
|
|
175
|
+
isReadOnly(req: PermissionRequest): boolean;
|
|
176
|
+
/** Grants currently stored, useful for diagnostics and tests. */
|
|
177
|
+
listSessionGrants(sessionId?: string): ReadonlyArray<{ pattern: string; scope: GrantScope; sessionId: string }>;
|
|
178
|
+
/** Observe decisions for audit/UI integrations. Optional so minimal implementations stay valid. */
|
|
179
|
+
onDecision?(handler: (event: PermissionDecisionEvent) => void): Disposable;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface PermissionOptions {
|
|
183
|
+
/** How long an `ask` waits for an answer before failing closed. */
|
|
184
|
+
askTimeoutMs?: number;
|
|
185
|
+
/** Tools that skip rule evaluation entirely (an explicit `deny` still wins). */
|
|
186
|
+
trustedTools?: string[];
|
|
187
|
+
/** Require a second press of `y`/`s`/`n`/`r` in the inline TUI dialog. */
|
|
188
|
+
doublePressToConfirm?: boolean;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** One action for everything, or a glob → action map (`{"**": "allow", "** /*.pem": "deny"}`). */
|
|
192
|
+
export type PermissionSurfaceRules = PermissionAction | Record<string, PermissionAction>;
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Flat permission policy.
|
|
196
|
+
*
|
|
197
|
+
* Rules are evaluated most-restrictive-first and nothing is denied implicitly: with an empty policy
|
|
198
|
+
* every request is `ask`. An omitted surface falls back to `"*"`, and `"*"` falls back to `ask`.
|
|
199
|
+
*/
|
|
200
|
+
export interface PermissionPolicy {
|
|
201
|
+
/** Global fallback for every surface that has no matching rule. */
|
|
202
|
+
"*"?: PermissionAction;
|
|
203
|
+
/** Project-relative glob → action, applied to file tools *and* to bash path arguments. */
|
|
204
|
+
path?: Record<string, PermissionAction>;
|
|
205
|
+
/** Shell command pattern → action (`"ls *": "allow"`). Matched after wrapper unwrapping. */
|
|
206
|
+
bash?: Record<string, PermissionAction>;
|
|
207
|
+
/** MCP tool rules (`{"*": "allow", "mcp__github__*": "allow"}`) or single action (`"allow"`). */
|
|
208
|
+
mcp?: PermissionSurfaceRules;
|
|
209
|
+
/**
|
|
210
|
+
* Verdict for tool calls a subagent makes (`request.source === "subagent"`).
|
|
211
|
+
*
|
|
212
|
+
* Default `allow`: an `ask` from the other surfaces is auto-approved for a child session, because
|
|
213
|
+
* the parent already chose to spawn it and a dialog per child call is noise. Rules here *replace*
|
|
214
|
+
* an `ask`, but can never lift a `deny` from `path`/`bash`/`mcp`/config — so `deny` stays final:
|
|
215
|
+
* `{"subagent": {"*": "allow", "bash": "deny"}}` blocks only the child's shell calls.
|
|
216
|
+
*/
|
|
217
|
+
subagent?: PermissionSurfaceRules;
|
|
218
|
+
/**
|
|
219
|
+
* Set `false` to skip the built-in security defaults (secret paths, catastrophic deletions).
|
|
220
|
+
* A project layer cannot disable them; only a user-level config can.
|
|
221
|
+
*/
|
|
222
|
+
builtinDefaults?: boolean;
|
|
223
|
+
/** Shared rule set for paths outside the project root. */
|
|
224
|
+
external_directory?: PermissionSurfaceRules;
|
|
225
|
+
external_directory_read?: PermissionSurfaceRules;
|
|
226
|
+
external_directory_write?: PermissionSurfaceRules;
|
|
227
|
+
askTimeoutMs?: number;
|
|
228
|
+
trustedTools?: string[];
|
|
229
|
+
doublePressToConfirm?: boolean;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Policy as written by a user.
|
|
234
|
+
*
|
|
235
|
+
* The flat form is canonical. The legacy `{"permission": {...}}` wrapper is still accepted and
|
|
236
|
+
* normalized on load so existing config files keep working; flat keys win over wrapped ones.
|
|
237
|
+
*/
|
|
238
|
+
export interface PermissionConfig extends PermissionPolicy {
|
|
239
|
+
/** @deprecated legacy nested wrapper, folded into the flat keys by the loader. */
|
|
240
|
+
permission?: PermissionPolicy & { options?: PermissionOptions };
|
|
241
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const SUBAGENTS_CONTRACT_ID = "re:subagents@1";
|
|
2
|
+
|
|
3
|
+
/** Summary of an agent published through the service seam. */
|
|
4
|
+
export interface SubagentSummary {
|
|
5
|
+
readonly name: string;
|
|
6
|
+
readonly description: string;
|
|
7
|
+
readonly model?: string;
|
|
8
|
+
readonly fallbackModels?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Service published by @restranger/repi-subagents.
|
|
13
|
+
* Allows other plugins (e.g. model-fallback) to inspect and configure subagent models.
|
|
14
|
+
*/
|
|
15
|
+
export interface SubagentsService {
|
|
16
|
+
listAgents(): readonly SubagentSummary[];
|
|
17
|
+
setAgentFallbackModels?(agentName: string, fallbackModels: readonly string[]): void;
|
|
18
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export const UI_CONTRACT_ID = "re:ui@1";
|
|
2
|
+
|
|
3
|
+
export type UiNoticeType = "info" | "warning" | "error";
|
|
4
|
+
|
|
5
|
+
/** Dialog options forwarded to the host's `select`/`confirm`/`input`. */
|
|
6
|
+
export interface UiDialogOptions {
|
|
7
|
+
/** AbortSignal that programmatically dismisses the dialog. */
|
|
8
|
+
readonly signal?: AbortSignal;
|
|
9
|
+
/** Host-side timeout; the dialog dismisses with a live countdown. */
|
|
10
|
+
readonly timeout?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Optional UI capability published by @restranger/repi-ui.
|
|
15
|
+
*
|
|
16
|
+
* Permissions uses it for approval dialogs, modes for badges. Both keep working when the
|
|
17
|
+
* service is absent: permissions fails closed, modes skips the badge.
|
|
18
|
+
*/
|
|
19
|
+
export interface UiService {
|
|
20
|
+
select(title: string, options: string[], opts?: UiDialogOptions): Promise<string | undefined>;
|
|
21
|
+
confirm(title: string, message: string, opts?: UiDialogOptions): Promise<boolean>;
|
|
22
|
+
input(title: string, placeholder?: string, opts?: UiDialogOptions): Promise<string | undefined>;
|
|
23
|
+
notify(message: string, type?: UiNoticeType): void;
|
|
24
|
+
setStatus(key: string, text?: string): void;
|
|
25
|
+
}
|
package/src/contracts.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared vocabulary for optional integration between repi plugins.
|
|
3
|
+
*
|
|
4
|
+
* A contract id carries its major version (`re:permissions@1`). Additive changes stay within the
|
|
5
|
+
* same major; a breaking change gets a new id. The id is the only thing two independently
|
|
6
|
+
* installed plugins must agree on.
|
|
7
|
+
*/
|
|
8
|
+
export type ContractId = string;
|
|
9
|
+
|
|
10
|
+
/** Process-wide channel announcing that a service is available for a contract + session. */
|
|
11
|
+
export const READY_CHANNEL = "repi:ready:v1";
|
|
12
|
+
|
|
13
|
+
/** Plain-data announcement. The service itself is fetched from the seam, never carried here. */
|
|
14
|
+
export interface ReadyEvent {
|
|
15
|
+
readonly contract: ContractId;
|
|
16
|
+
readonly version: number;
|
|
17
|
+
readonly sessionId: string;
|
|
18
|
+
readonly owner: string;
|
|
19
|
+
readonly capabilities: readonly string[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isReadyEvent(value: unknown): value is ReadyEvent {
|
|
23
|
+
if (typeof value !== "object" || value === null) {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
const record = value as Record<string, unknown>;
|
|
27
|
+
return (
|
|
28
|
+
typeof record.contract === "string" &&
|
|
29
|
+
record.contract.length > 0 &&
|
|
30
|
+
typeof record.version === "number" &&
|
|
31
|
+
Number.isFinite(record.version) &&
|
|
32
|
+
typeof record.sessionId === "string" &&
|
|
33
|
+
record.sessionId.length > 0 &&
|
|
34
|
+
typeof record.owner === "string" &&
|
|
35
|
+
record.owner.length > 0 &&
|
|
36
|
+
Array.isArray(record.capabilities) &&
|
|
37
|
+
record.capabilities.every((capability) => typeof capability === "string")
|
|
38
|
+
);
|
|
39
|
+
}
|