@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
249 lines • 12.3 kB
JavaScript
import { decideTarget } from "./decide-target.js";
import { createLocalEventEmitter } from "./events.js";
import { decideExternalPaths } from "./external-spellings.js";
import { identityMatcher, identityWanted, pathRulesOf, prepareIdentity, } from "./identity-decision.js";
import { createMountRewrite, readFirmlinks } from "./alias-detector.js";
import { PendingRequests } from "./pending-requests.js";
import { RuleIdentityCache } from "./rule-identity-cache.js";
import { approvedFileVersion, approvedStoreRealPath, loadApproved } from "./storage.js";
import { DeniedError, } from "./types.js";
/** Classes whose non-deny decision may have mutated the filesystem (M3): everything but the read-only ones. */
const READ_ONLY_PERMISSIONS = new Set(["read", "list", "grep", "external_directory", "eval"]);
function uniq(values) {
return [...new Set(values)];
}
/** Core service for managing permission requests and rule evaluation */
export class PermissionService {
constructor(staticRuleset, approved, emitter = createLocalEventEmitter(), preset, projectDir, agentDir, resolver) {
/**
* The "Always" answers given to this service, keyed by the session (the request's `sessionID`) that
* answered, so one service serving several sessions never lets one session's answer approve another's call.
*/
this.answers = new Map();
this.idCounter = 0;
/** Identity inputs by request id, so a refusal can name the layer of an identity-matched deny. */
this.requestIdentities = new Map();
this.staticRuleset = [...staticRuleset];
this.approved = [...approved];
this.emitter = emitter;
this.preset = preset;
this.resolver = resolver;
this.mountRewrite = createMountRewrite(readFirmlinks());
this.ruleIdentities = new RuleIdentityCache(resolver, projectDir, () => this.pathRules(), emitter);
this.ruleIdentities.fillAll();
this.pendingRequests = new PendingRequests({
emitter,
approve: (rule) => this.remember(this.replyScope ?? "", rule),
decide: (permission, pattern, options) => this.decide(permission, pattern, options, this.replyScope ?? ""),
});
this.projectDir = projectDir;
this.agentDir = agentDir;
this.protectedStorePath =
agentDir !== undefined && projectDir !== undefined ? approvedStoreRealPath(agentDir, projectDir) : undefined;
this.approvedVersion =
agentDir === undefined || projectDir === undefined ? undefined : approvedFileVersion(agentDir, projectDir);
// The resolver is shared by every session of the process and outlives this service, so the
// subscription is released by dispose(); an unreleased one keeps the service's emitter and
// its extension generation reachable across every reload. It is taken last: a constructor that
// throws earlier never hands out the service, so nothing could ever release it.
this.releaseResolverState = resolver?.onState((event) => this.emitter.emitResolverState(event)) ?? (() => { });
}
/** Stops forwarding resolver state to this service's emitter; decisions keep working. */
dispose() {
this.releaseResolverState();
}
identityWanted(permission, kernel) {
return identityWanted(this.resolver, [...this.staticRuleset, ...this.approvedFor()], permission, kernel);
}
pathRules() {
return pathRulesOf([...this.staticRuleset, ...this.approvedFor()]);
}
remember(scope, rule) {
const answers = this.answers.get(scope);
if (answers)
answers.push(rule);
else
this.answers.set(scope, [rule]);
}
/** The shared approved rules, then the given session's answers; with no session, every session's answers. */
approvedFor(scope) {
const answers = scope === undefined ? [...this.answers.values()].flat() : (this.answers.get(scope) ?? []);
return [...this.approved, ...answers];
}
ruleIdentityState(pattern) {
return this.ruleIdentities.stateOf(pattern);
}
ruleAliasBearing(pattern) {
return this.ruleIdentities.aliasBearing(pattern);
}
noteMutation(mutated) {
this.ruleIdentities.noteMutation(mutated);
}
identitySettled() {
return this.ruleIdentities.settled();
}
prepareIdentity(permission, executed, cwd, kernel) {
return prepareIdentity(this.identityContext, permission, executed, cwd, kernel);
}
get identityContext() {
return {
resolver: this.resolver,
cache: this.ruleIdentities,
mountRewrite: this.mountRewrite,
identityWanted: (candidate, kernel) => this.identityWanted(candidate, kernel),
};
}
requestIdentity(requestID) {
return this.requestIdentities.get(requestID);
}
identityMatcher(permission, identity) {
const unavailable = this.resolver?.unavailable !== undefined;
return identityMatcher(this.ruleIdentities, permission, identity, this.mountRewrite, unavailable);
}
/**
* An "Always" answer another open session just persisted is honored on this session's very next
* decision (senpi#2465): the approved store is re-read only when its mtime+size changed, and the
* re-read replaces the shared rules while keeping every session's own answers.
*/
refreshApproved() {
if (this.projectDir === undefined || this.agentDir === undefined)
return;
const version = approvedFileVersion(this.agentDir, this.projectDir);
if (version === this.approvedVersion)
return;
this.approved = loadApproved(this.agentDir, this.projectDir);
this.approvedVersion = version;
}
/**
* The one decision for a call, used when it is asked and again whenever an "Always" reply re-checks
* the requests still pending. External paths use last-match-wins separately for the absolute
* lexical path, physical-prefix spellings from the component walk and their proven on-disk case; the most restrictive
* decision wins (deny > ask > allow). More than 16 spellings or 40 hops asks instead.
* Raw originalPaths are display-only. Remembered approvals
* match the resolved target and cannot override a deny from any spelling.
* Without `presetBound` it is last-match-wins over every rule. With
* `presetBound` the preset's rules and the user's settings and CLI rules are evaluated apart and
* the more restrictive wins, so no configured rule, in any order or layer, can widen the preset;
* only an "Always" answer given in this or an earlier session (`permissions-approved.jsonl`,
* explicit consent for that pattern) can then turn a remaining ask into allow.
*/
decide(permission, target, options, scope) {
return this.dispatchDecision(permission, target, options, scope).action;
}
/**
* Share the decision and its relevant rules with the final dispatch fence. `scope` is the session
* the call belongs to (its requests' `sessionID`): only that session's answers can approve it.
* Without one, every session's answers count, which is one session's answers on a service that
* serves a single session; a caller deciding for one session of a shared service passes it.
*/
dispatchDecision(permission, target, options = {}, scope) {
this.refreshApproved();
const approved = this.approvedFor(scope);
if (permission === "external_directory") {
return decideExternalPaths(target, options.ruleAliases ?? [], (spelling, resolved, canonicalCase) => this.decideTarget(approved, permission, spelling, options, resolved, spelling !== resolved, canonicalCase));
}
return this.decideTarget(approved, permission, options.ruleAliases ?? target, options);
}
decideTarget(approved, permission, target, options, approvedTarget = target, preserveAncestry = false, canonicalCase) {
const context = {
staticRuleset: this.staticRuleset,
approved,
preset: this.preset,
protectedStorePath: this.protectedStorePath,
identityMatcher: (candidate, identity) => this.identityMatcher(candidate, identity),
};
return decideTarget(context, permission, target, options, approvedTarget, preserveAncestry, canonicalCase);
}
/** Request permission for a tool call. Resolves if allowed, throws on denial. */
async ask(request, { autoApproveAsk = false, approveBlanketAsk = false, presetBound = false, ruleAliases, executed, } = {}) {
const info = {
...request,
id: request.id ?? this.nextRequestID(),
};
const deniedPatterns = [];
let needsAsk = false;
// The identity route is taken only with a path-class rule present (R3-H2); every resolver failure
// becomes `unresolvable` here and never a thrown error. Executed strings travel as ruleAliases only,
// so the written pattern stays the displayed and denied one (N8, N9).
let identity;
if (executed && executed.length > 0 && this.identityWanted(info.permission)) {
try {
identity = await this.prepareIdentity(info.permission, executed, this.projectDir);
}
catch (error) {
identity = { canonical: [], unresolvable: error.code ?? "EUNKNOWN" };
}
}
if (identity)
this.requestIdentities.set(info.id, identity);
const options = {
approveBlanketAsk,
presetBound,
ruleAliases,
originalPaths: info.originalPaths,
...(identity ? { identity } : {}),
};
for (const pattern of info.patterns) {
const aliases = executed && executed.length > 0 ? uniq([...(ruleAliases ?? [pattern]), ...executed]) : ruleAliases;
const action = this.decide(info.permission, pattern, { ...options, ruleAliases: aliases }, info.sessionID);
if (action === "deny") {
deniedPatterns.push(pattern);
continue;
}
if (action === "ask" && !autoApproveAsk) {
needsAsk = true;
}
}
if (deniedPatterns.length > 0) {
this.requestIdentities.delete(info.id);
throw new DeniedError(deniedPatterns, identity);
}
if (!READ_ONLY_PERMISSIONS.has(info.permission)) {
if (executed && executed.length > 0)
for (const value of executed)
this.noteMutation(value);
else
this.noteMutation();
}
if (!needsAsk) {
this.requestIdentities.delete(info.id);
this.emitter.emitReplied(info.id, info.sessionID, "allow");
return;
}
const pendingPromise = this.pendingRequests
.register(info, options)
.finally(() => this.requestIdentities.delete(info.id));
this.emitter.emitAsked(info);
await pendingPromise;
}
/** Reply to a pending permission request; an "Always" answer is remembered for the request's session only. */
reply(input) {
this.replyScope = this.pendingRequests.list().find((request) => request.id === input.requestID)?.sessionID;
try {
this.pendingRequests.reply(input);
}
finally {
this.replyScope = undefined;
}
}
/** List all pending permission requests */
list() {
return this.pendingRequests.list();
}
/** Get the current approved ruleset: the shared rules, then every session's answers. */
getApproved() {
return this.approvedFor().map((rule) => ({ ...rule }));
}
/**
* The answers given to this service (every session's), kept apart from the shared rules: a refresh
* that grows or shrinks the persisted store never duplicates or drops them.
*/
getSessionApproved() {
return [...this.answers.values()].flat().map((rule) => ({ ...rule }));
}
nextRequestID() {
this.idCounter += 1;
return `permission-${this.idCounter}`;
}
}
//# sourceMappingURL=service.js.map