@hank-warren/pi-auto-permissions 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.md +16 -0
- package/index.ts +97 -4
- package/loop-context.ts +41 -0
- package/loop-revise-budget.ts +305 -0
- package/package.json +4 -2
- package/review.ts +28 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# @hank-warren/pi-auto-permissions
|
|
2
2
|
|
|
3
|
+
## 0.12.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 897739d: Framed approval card, fresh-session launch, and a loop-safe permission posture.
|
|
8
|
+
|
|
9
|
+
**pi-loop**
|
|
10
|
+
|
|
11
|
+
- The approval card is now a framed `customType` transcript block, emitted once per draft, with its choices in an action menu. It used to go out twice and neither copy was a card: `loop_propose` returned it as tool-result markdown (re-spending the objective's tokens in the model's own context) and `/loop` re-printed it as a toast.
|
|
12
|
+
- `startLoop` is split into `buildLoop` and `installLoop`, and the menu gains **Start loop in a fresh session** — the loop is built in the planning session and installed in a new one, so only the objective crosses and the drafting conversation does not.
|
|
13
|
+
- A loop publishes `PI_LOOP_ACTIVE=1` and `PI_LOOP_ID` on the process while active. This is a contract for other extensions, mirroring `PI_SUBAGENT_CHILD`: no import, no dependency, no RPC.
|
|
14
|
+
- The autonomy posture is reconciled with it. Reshaping a command to get _around_ a permission gate stays forbidden; revising it to satisfy a concern a guardian actually stated is legitimate and bounded. The `⚠ loop blocked` detector is unchanged.
|
|
15
|
+
|
|
16
|
+
**pi-auto-permissions**
|
|
17
|
+
|
|
18
|
+
- While `PI_LOOP_ACTIVE=1`, an `ask_user` verdict returns the guardian's concern to the agent as a non-blocking block instead of opening a modal. A session waiting on a modal is busy, and a busy session starves a loop's continuation path — the prompt would not be answered, it would deadlock the loop until it expired. **The verdict is unchanged; only its delivery is.** The absence of a user is never authorization.
|
|
19
|
+
- Revision is bounded — per concern, per gate, and by consecutive blocked attempts — after which the block names `loop_wait` instead of inviting another try. The bounds survive a compaction and a session restore.
|
|
20
|
+
|
|
21
|
+
Detection is fail-open in both directions: with the environment variables absent, behaviour is exactly as before, and neither package requires the other.
|
|
22
|
+
|
|
23
|
+
## 0.11.1
|
|
24
|
+
|
|
25
|
+
### Patch Changes
|
|
26
|
+
|
|
27
|
+
- 3fbf632: Stop evidence truncation from re-appending the whole record. With a per-record cap of 1-3 the head share rounded up to the entire budget, leaving a zero-length tail — and `slice(-0)` is `slice(0)`, so the "truncated" record was longer than its input and carried an elision marker for text the reviewer could still read. Caps of 4 and above, including every shipped default, are unaffected.
|
|
28
|
+
- Updated dependencies [3fbf632]
|
|
29
|
+
- @hank-warren/pi-permission-selector@1.3.0
|
|
30
|
+
|
|
3
31
|
## 0.11.0
|
|
4
32
|
|
|
5
33
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -313,6 +313,22 @@ When a session is a [pi-subagents](https://github.com/nicobailon/pi-subagents) c
|
|
|
313
313
|
|
|
314
314
|
Subagent sessions have no interactive user, so an `ask_user` verdict blocks the command immediately with a reason instructing the child to route around the gated operation or report the blocker. Reviewer usage records from subagent sessions carry `"subagent": true` in the usage sidecar.
|
|
315
315
|
|
|
316
|
+
## Unattended loop sessions
|
|
317
|
+
|
|
318
|
+
When the session is running an unattended loop, the guardian's decisions are unchanged and only their *delivery* changes: an `ask_user` verdict returns the concern to the agent as a block instead of opening a prompt. This is not a relaxation. A session waiting on a modal is busy, and a busy session starves the loop's own continuation path — no turn completes, no cap trips, and nothing ends the loop until it expires, potentially days later. The prompt would not be answered; it would simply deadlock.
|
|
319
|
+
|
|
320
|
+
Detection is an environment contract, not a dependency. [pi-loop](https://github.com/hank-warren/pi-extensions/tree/main/packages/pi-loop) sets `PI_LOOP_ACTIVE=1` and `PI_LOOP_ID=<id>` on the process while a loop is active and removes them when it is not; this extension reads them exactly as it reads `PI_SUBAGENT_CHILD`. Neither package imports or depends on the other, and with the variables absent — pi-loop not installed, or no loop running — behavior is identical to today.
|
|
321
|
+
|
|
322
|
+
The agent is given a bounded number of revision rounds against the guardian's stated concern, after which the block stops offering that option and instructs it to call `loop_wait` (pi-loop's non-deadlocking way to reach a human). The bound is what keeps "address the objection" from becoming "retry until something is approved":
|
|
323
|
+
|
|
324
|
+
- **3 blocked attempts per concern**, so there are two real revisions: enough for a misread of a terse objection plus a considered fix.
|
|
325
|
+
- **5 blocked attempts per gate.**
|
|
326
|
+
- **5 consecutive blocked attempts**, at any gate, for any concern — the backstop. An approved command resets it, since an agent getting real work past the guardian is not grinding against it.
|
|
327
|
+
|
|
328
|
+
The block reports whichever bound is closest, and the stated remainder falls every time. Both of the first two bounds are keyed on something the *command* determines, and a canary walked through each in turn. The guardian rewords its objection between rounds, so a count keyed on that prose stops advancing and the block repeats "1 revision round remains" forever — the agent read two identical blocks, called the number ambiguous, and stopped trusting it. Then, blocked on `git branch -D`, it tried `git branch --delete`: the same operation under a different rule, which reset both the gate counter and the concern key embedded in it. The consecutive-block count is immune to both, because it measures the argument rather than the command, and a concern or gate first seen mid-argument inherits the argument's length instead of starting over.
|
|
329
|
+
|
|
330
|
+
Counts are held in memory *and* persisted as a session entry, so neither a context compaction nor a session resume hands back a fresh budget. A review that fails for infrastructure reasons blocks without charging a round, since that is not a guardian judgment.
|
|
331
|
+
|
|
316
332
|
## Guardian dispatch
|
|
317
333
|
|
|
318
334
|
Reviewer requests dispatch through the host's model runtime rather than pi-ai's compat layer, so provider transports registered by other extensions (for example `@gotgenes/pi-anthropic-auth` OAuth request shaping) apply to guardian calls. When the runtime seam is unavailable, dispatch falls back to `compat.completeSimple`.
|
package/index.ts
CHANGED
|
@@ -2,6 +2,12 @@ import { cleanupSessionResources, type Message } from "@earendil-works/pi-ai";
|
|
|
2
2
|
import { resolveGuardianCompleteSimple } from "./guardian-transport.js";
|
|
3
3
|
import { isOpenAICodexModel } from "./openai-codex-transport.js";
|
|
4
4
|
import { detectSubagentContext } from "./subagent-context.js";
|
|
5
|
+
import { detectLoopContext } from "./loop-context.js";
|
|
6
|
+
import {
|
|
7
|
+
LoopReviseBudget,
|
|
8
|
+
loopBlockReason,
|
|
9
|
+
type LoopReviseCharge,
|
|
10
|
+
} from "./loop-revise-budget.js";
|
|
5
11
|
import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
|
|
6
12
|
import {
|
|
7
13
|
getSelectListTheme,
|
|
@@ -50,6 +56,7 @@ import {
|
|
|
50
56
|
applyFullRebuildEviction,
|
|
51
57
|
buildReviewEnvelope,
|
|
52
58
|
collectReviewEvidence,
|
|
59
|
+
LOOP_CONTEXT_SYSTEM_PROMPT,
|
|
53
60
|
OVERRIDE_FEEDBACK_SYSTEM_PROMPT,
|
|
54
61
|
parsePermissionVerdict,
|
|
55
62
|
SUBAGENT_CONTEXT_SYSTEM_PROMPT,
|
|
@@ -242,6 +249,17 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
|
|
|
242
249
|
let lastConfigError: string | undefined;
|
|
243
250
|
let lastEvaluationLogError: string | undefined;
|
|
244
251
|
let sessionActive = true;
|
|
252
|
+
/**
|
|
253
|
+
* Revision rounds spent per guardian concern while a loop is active.
|
|
254
|
+
*
|
|
255
|
+
* Session-scoped and held here rather than in the review closure, so a
|
|
256
|
+
* context compaction (which rewrites the conversation, not this process)
|
|
257
|
+
* cannot reset it. Restored from the session branch at session_start so a
|
|
258
|
+
* resume cannot reset it either.
|
|
259
|
+
*/
|
|
260
|
+
const loopReviseBudget = new LoopReviseBudget();
|
|
261
|
+
/** The loop these counts belong to, so a new loop starts with a clean budget. */
|
|
262
|
+
let loopReviseBudgetLoopId: string | undefined;
|
|
245
263
|
let bashRendererRegistered = false;
|
|
246
264
|
let bashRendererSourcePath: string | undefined;
|
|
247
265
|
let clearWidgetTimer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -347,9 +365,12 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
|
|
|
347
365
|
// buildReviewerSystemPrompt append the untrusted project-instructions
|
|
348
366
|
// evidence block, keeping policy contiguous and evidence terminal.
|
|
349
367
|
const subagentContext = detectSubagentContext(ctx.cwd);
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
|
|
368
|
+
const loopContext = detectLoopContext();
|
|
369
|
+
const basePolicyPrompt = [
|
|
370
|
+
config.systemPrompt,
|
|
371
|
+
...(subagentContext ? [SUBAGENT_CONTEXT_SYSTEM_PROMPT] : []),
|
|
372
|
+
...(loopContext ? [LOOP_CONTEXT_SYSTEM_PROMPT] : []),
|
|
373
|
+
].join("\n\n");
|
|
353
374
|
// Appended outside config.systemPrompt so sessions using a customized
|
|
354
375
|
// systemPromptFile still learn how to weigh override records.
|
|
355
376
|
const policyPrompt = `${basePolicyPrompt}\n\n${OVERRIDE_FEEDBACK_SYSTEM_PROMPT}`;
|
|
@@ -382,7 +403,13 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
|
|
|
382
403
|
cwd: ctx.cwd,
|
|
383
404
|
gate: gate.label,
|
|
384
405
|
group: gate.group,
|
|
385
|
-
...(subagentContext
|
|
406
|
+
...(subagentContext && loopContext
|
|
407
|
+
? { execution: { ...subagentContext, ...loopContext } }
|
|
408
|
+
: subagentContext
|
|
409
|
+
? { execution: subagentContext }
|
|
410
|
+
: loopContext
|
|
411
|
+
? { execution: loopContext }
|
|
412
|
+
: {}),
|
|
386
413
|
};
|
|
387
414
|
const makeUserMessage = (records: readonly ReviewEvidenceRecord[], mode: "full" | "delta"): Message => ({
|
|
388
415
|
role: "user",
|
|
@@ -766,6 +793,33 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
|
|
|
766
793
|
}).finally(() => indicator?.stop());
|
|
767
794
|
}
|
|
768
795
|
|
|
796
|
+
/**
|
|
797
|
+
* Charge one revision round against a guardian concern and persist the
|
|
798
|
+
* budget. A loop id different from the one the counts belong to means a new
|
|
799
|
+
* loop: it inherits nothing from the last one's arguments with the guardian.
|
|
800
|
+
*/
|
|
801
|
+
function chargeLoopRevision(
|
|
802
|
+
loopId: string | undefined,
|
|
803
|
+
gateLabel: string,
|
|
804
|
+
reason: string,
|
|
805
|
+
): LoopReviseCharge {
|
|
806
|
+
if (loopReviseBudgetLoopId !== loopId) {
|
|
807
|
+
loopReviseBudget.clear();
|
|
808
|
+
loopReviseBudgetLoopId = loopId;
|
|
809
|
+
}
|
|
810
|
+
const charge = loopReviseBudget.charge(gateLabel, reason);
|
|
811
|
+
try {
|
|
812
|
+
pi.appendEntry(LoopReviseBudget.entryType, {
|
|
813
|
+
...loopReviseBudget.snapshot(),
|
|
814
|
+
...(loopId ? { loopId } : {}),
|
|
815
|
+
});
|
|
816
|
+
} catch {
|
|
817
|
+
// Persistence is what survives a restore; the in-memory count is what
|
|
818
|
+
// survives a compaction. Losing the former never widens the bound now.
|
|
819
|
+
}
|
|
820
|
+
return charge;
|
|
821
|
+
}
|
|
822
|
+
|
|
769
823
|
async function askUser(
|
|
770
824
|
gate: Gate,
|
|
771
825
|
command: string,
|
|
@@ -913,8 +967,33 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
|
|
|
913
967
|
}
|
|
914
968
|
if (verdict.decision === "approve") {
|
|
915
969
|
showReviewDisplay(ctx, config, gate, command, target, "approved", verdict.reason, true);
|
|
970
|
+
// An approval ends the argument at this gate: the per-gate bound exists
|
|
971
|
+
// to stop an agent grinding, not to ration a long loop's whole session.
|
|
972
|
+
loopReviseBudget.settle(gate.label);
|
|
916
973
|
return;
|
|
917
974
|
}
|
|
975
|
+
// An unattended loop cannot answer a modal and must not be handed an
|
|
976
|
+
// unbounded retry loop either, so both non-approving verdicts come back
|
|
977
|
+
// as one bounded block. The verdict itself is unchanged: nothing is
|
|
978
|
+
// approved here that would not have been approved with a user present.
|
|
979
|
+
const loopContext = detectLoopContext();
|
|
980
|
+
if (loopContext) {
|
|
981
|
+
const charge = chargeLoopRevision(loopContext.loopId, gate.label, verdict.reason);
|
|
982
|
+
showReviewDisplay(
|
|
983
|
+
ctx,
|
|
984
|
+
config,
|
|
985
|
+
gate,
|
|
986
|
+
command,
|
|
987
|
+
target,
|
|
988
|
+
verdict.decision === "revise" ? "revise" : "blocked",
|
|
989
|
+
verdict.reason,
|
|
990
|
+
true,
|
|
991
|
+
);
|
|
992
|
+
return {
|
|
993
|
+
block: true,
|
|
994
|
+
reason: loopBlockReason({ gateLabel: gate.label, reason: verdict.reason, ...charge }),
|
|
995
|
+
};
|
|
996
|
+
}
|
|
918
997
|
if (verdict.decision === "revise") {
|
|
919
998
|
showReviewDisplay(ctx, config, gate, command, target, "revise", verdict.reason, true);
|
|
920
999
|
return {
|
|
@@ -929,6 +1008,16 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
|
|
|
929
1008
|
return { block: true, reason: "Auto Permissions review cancelled" };
|
|
930
1009
|
}
|
|
931
1010
|
const reason = error instanceof Error ? error.message : String(error);
|
|
1011
|
+
// A review that failed is an infrastructure fault, not a guardian
|
|
1012
|
+
// judgment, so it charges no revision round — but it still must not open
|
|
1013
|
+
// a modal in a session with nobody to answer it.
|
|
1014
|
+
if (detectLoopContext()) {
|
|
1015
|
+
showReviewDisplay(ctx, config, gate, command, target, "blocked", reason, true);
|
|
1016
|
+
return {
|
|
1017
|
+
block: true,
|
|
1018
|
+
reason: `${gate.label} could not be reviewed (${reason}), and this session is running an unattended /loop, so there is no one to ask. Do not retry the same command hoping the reviewer recovers: call loop_wait naming the reviewer failure, or advance the objective another way.`,
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
932
1021
|
return askUser(
|
|
933
1022
|
gate,
|
|
934
1023
|
command,
|
|
@@ -1151,6 +1240,10 @@ export default function autoPermissionsExtension(pi: ExtensionAPI) {
|
|
|
1151
1240
|
allowedConventionCommands.clear();
|
|
1152
1241
|
permissionOverrides.length = 0;
|
|
1153
1242
|
overrideSeq = 0;
|
|
1243
|
+
// Rebuild the revise budget before the first tool call: a resumed session
|
|
1244
|
+
// that forgot its spent rounds would hand the agent a fresh set of them.
|
|
1245
|
+
loopReviseBudget.restore(ctx.sessionManager.getBranch());
|
|
1246
|
+
loopReviseBudgetLoopId = detectLoopContext()?.loopId;
|
|
1154
1247
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
1155
1248
|
if (entry.type !== "message" || entry.message.role !== "toolResult") continue;
|
|
1156
1249
|
if (entry.message.toolName !== "request_override") continue;
|
package/loop-context.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detecting an unattended pi-loop session.
|
|
3
|
+
*
|
|
4
|
+
* A guardian that decides "ask_user" opens a modal and waits. In an ordinary
|
|
5
|
+
* session that is the whole point — the boundary this extension exists to
|
|
6
|
+
* hold. In a session running a pi-loop it is a deadlock: a session waiting on
|
|
7
|
+
* a modal is `busy`, `busy` makes every loop continuation and every fallback
|
|
8
|
+
* tick skip, so no turn ever completes, no cap ever trips, and nothing ends
|
|
9
|
+
* the loop until it expires — up to seven days later.
|
|
10
|
+
*
|
|
11
|
+
* So the verdict stays exactly the same and only its *delivery* changes: the
|
|
12
|
+
* guardian's concern comes back as a non-blocking block the agent can read and
|
|
13
|
+
* act on, instead of a prompt nobody is there to answer. Nothing is approved
|
|
14
|
+
* that would not have been approved before.
|
|
15
|
+
*
|
|
16
|
+
* Detection mirrors `detectSubagentContext` deliberately: an environment
|
|
17
|
+
* variable, read the same way, with no import of and no dependency on the
|
|
18
|
+
* extension that sets it. pi-loop publishes `PI_LOOP_ACTIVE=1` and
|
|
19
|
+
* `PI_LOOP_ID` while a loop is active and removes them when it is not (see
|
|
20
|
+
* `packages/pi-loop/src/loop-env.ts`). Absent that env — pi-loop not
|
|
21
|
+
* installed, or installed with no loop running — behaviour is unchanged.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Runtime facts about an active loop, forwarded to the guardian as evidence. */
|
|
25
|
+
export interface LoopExecutionContext {
|
|
26
|
+
loop: true;
|
|
27
|
+
/** The loop's id (PI_LOOP_ID), when present. */
|
|
28
|
+
loopId?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function detectLoopContext(
|
|
32
|
+
env: Record<string, string | undefined> = process.env,
|
|
33
|
+
): LoopExecutionContext | undefined {
|
|
34
|
+
if (env.PI_LOOP_ACTIVE !== "1") return undefined;
|
|
35
|
+
const context: LoopExecutionContext = { loop: true };
|
|
36
|
+
// The id reaches the guardian prompt, so cap length and charset the way the
|
|
37
|
+
// subagent run id is capped: an identifier, never a payload.
|
|
38
|
+
const loopId = env.PI_LOOP_ID?.trim().replace(/[^\w.:-]/g, "").slice(0, 128);
|
|
39
|
+
if (loopId) context.loopId = loopId;
|
|
40
|
+
return context;
|
|
41
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounding the revise path for an unattended loop.
|
|
3
|
+
*
|
|
4
|
+
* Turning "ask_user" into a readable block removes the deadlock, but on its
|
|
5
|
+
* own it replaces one failure with a worse one: an agent that can always try
|
|
6
|
+
* again will always try again, and "keep adjusting the command until the
|
|
7
|
+
* guardian stops objecting" is a search for the phrasing that slips past the
|
|
8
|
+
* gate. That is precisely what pi-loop's own autonomy posture forbids, and it
|
|
9
|
+
* is not made safe by the guardian re-reviewing each attempt — the guardian
|
|
10
|
+
* reviews commands, and the thing being optimised against it is the command.
|
|
11
|
+
*
|
|
12
|
+
* So the rounds are counted, per concern, and they run out. Within the bound
|
|
13
|
+
* the agent may revise to *address* what the guardian said. Past it the block
|
|
14
|
+
* stops offering that option and names `loop_wait` instead, which is the only
|
|
15
|
+
* way a loop can ask a human anything without deadlocking itself.
|
|
16
|
+
*
|
|
17
|
+
* The count is keyed on the concern rather than the command precisely because
|
|
18
|
+
* the command is what changes: counting per command would reset the budget on
|
|
19
|
+
* every reshape, which is the behaviour being bounded.
|
|
20
|
+
*
|
|
21
|
+
* Two bounds, not one, and this is the load-bearing detail. A per-concern
|
|
22
|
+
* count is what makes the block specific enough to act on ("one round remains
|
|
23
|
+
* against *this*"), but a concern is prose and prose gets reworded, so a
|
|
24
|
+
* guardian phrasing the same objection differently would hand back a fresh
|
|
25
|
+
* budget — the failure mode this exists to prevent, arriving through the back
|
|
26
|
+
* door. The per-gate count is immune to wording and bounds the whole argument
|
|
27
|
+
* regardless. Whichever runs out first ends it.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const LOOP_REVISIONS_ENTRY_TYPE = "auto-permissions-loop-revisions";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* How many revisions an agent gets against one concern before it must wait.
|
|
34
|
+
*
|
|
35
|
+
* Three blocked attempts, so there are two real revisions: the first is often
|
|
36
|
+
* an honest misunderstanding of a terse concern and the second is the
|
|
37
|
+
* considered fix. A third attempt at the same objection is not a better
|
|
38
|
+
* command, it is a search.
|
|
39
|
+
*/
|
|
40
|
+
export const LOOP_REVISE_ROUNDS = 3;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* How many blocked attempts an agent gets at one gate before it must wait,
|
|
44
|
+
* whatever the concerns were.
|
|
45
|
+
*
|
|
46
|
+
* Deliberately larger than the per-concern bound: a second, genuinely
|
|
47
|
+
* different objection deserves its own rounds. Deliberately finite: an agent
|
|
48
|
+
* collecting objection after objection at the same gate is not converging on
|
|
49
|
+
* an authorized command, and the wording of the objection is not what makes
|
|
50
|
+
* that true.
|
|
51
|
+
*/
|
|
52
|
+
export const LOOP_GATE_ROUNDS = 5;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* How many times in a row an agent may be blocked, at any gate, for any
|
|
56
|
+
* concern, before it must wait.
|
|
57
|
+
*
|
|
58
|
+
* The backstop, and the only bound nothing can reshape its way out of. Both
|
|
59
|
+
* bounds above are keyed on something the *command* determines: the concern is
|
|
60
|
+
* the guardian's prose, and the gate is whichever rule the command text
|
|
61
|
+
* matched. A canary walked straight through both — blocked on
|
|
62
|
+
* `git branch -D`, the agent tried `git branch --delete`, which is the same
|
|
63
|
+
* operation under a different rule, and the budget started over.
|
|
64
|
+
*
|
|
65
|
+
* Counting blocks is immune to both, because it measures the argument rather
|
|
66
|
+
* than the command. Only resolving that argument — an approval at a gate that
|
|
67
|
+
* has been blocking — resets it.
|
|
68
|
+
*/
|
|
69
|
+
export const LOOP_STREAK_ROUNDS = 5;
|
|
70
|
+
|
|
71
|
+
/** Words too common to distinguish one guardian concern from another. */
|
|
72
|
+
const STOPWORDS = new Set([
|
|
73
|
+
"a", "an", "and", "are", "as", "at", "be", "been", "but", "by", "for", "from", "has", "have",
|
|
74
|
+
"in", "is", "it", "its", "not", "of", "on", "or", "that", "the", "this", "to", "was", "were",
|
|
75
|
+
"which", "with", "would", "user", "command", "action", "request", "because", "without",
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
/** Cap on the tokens that form a concern's signature. */
|
|
79
|
+
const SIGNATURE_TOKENS = 10;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A stable key for "the same objection, restated".
|
|
83
|
+
*
|
|
84
|
+
* A guardian writes one concise sentence and writes it slightly differently
|
|
85
|
+
* each time, so exact text would reset the budget on every round. The sorted
|
|
86
|
+
* set of significant words survives rewording, and when two genuinely
|
|
87
|
+
* different concerns do collide the budget only ever binds *tighter* — the
|
|
88
|
+
* safe direction for a bound whose failure mode is unbounded retrying.
|
|
89
|
+
*/
|
|
90
|
+
export function concernKey(gateLabel: string, reason: string): string {
|
|
91
|
+
const tokens = [
|
|
92
|
+
...new Set(
|
|
93
|
+
reason
|
|
94
|
+
.toLowerCase()
|
|
95
|
+
.replace(/[^a-z0-9\s]/g, " ")
|
|
96
|
+
.split(/\s+/)
|
|
97
|
+
.map(stem)
|
|
98
|
+
.filter((token) => token.length > 2 && !STOPWORDS.has(token)),
|
|
99
|
+
),
|
|
100
|
+
]
|
|
101
|
+
.sort()
|
|
102
|
+
.slice(0, SIGNATURE_TOKENS);
|
|
103
|
+
return `${gateLabel}::${tokens.join(" ")}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Crude suffix stripping, so "authorize", "authorized" and "authorizing" are
|
|
108
|
+
* one token. Not linguistics: just enough that the commonest rewording of the
|
|
109
|
+
* same objection lands on the same key. Anything it misses is caught by the
|
|
110
|
+
* per-gate bound, which is why it can afford to be crude.
|
|
111
|
+
*/
|
|
112
|
+
function stem(token: string): string {
|
|
113
|
+
for (const suffix of ["ing", "ed", "es", "s"]) {
|
|
114
|
+
if (token.length > suffix.length + 3 && token.endsWith(suffix)) {
|
|
115
|
+
return token.slice(0, -suffix.length);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return token;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface PersistedBudget {
|
|
122
|
+
concerns?: unknown;
|
|
123
|
+
gates?: unknown;
|
|
124
|
+
streak?: unknown;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Per-concern revision counts for this session.
|
|
129
|
+
*
|
|
130
|
+
* Held in memory *and* persisted as a custom session entry. The memory copy is
|
|
131
|
+
* what survives a context compaction (the process does not restart, so the map
|
|
132
|
+
* is untouched while the conversation around it is rewritten); the persisted
|
|
133
|
+
* copy is what survives a session restore, and what makes the bound
|
|
134
|
+
* reconstructible rather than merely lucky. Both matter: a bound that a
|
|
135
|
+
* compaction silently reset would hand the agent unlimited rounds at exactly
|
|
136
|
+
* the moment its own memory of the concern was summarised away.
|
|
137
|
+
*/
|
|
138
|
+
/** What one charged round leaves the agent with. */
|
|
139
|
+
export interface LoopReviseCharge {
|
|
140
|
+
/** Rounds spent against this concern, including the one being reported. */
|
|
141
|
+
concernSpent: number;
|
|
142
|
+
/** Blocked attempts at this gate, including the one being reported. */
|
|
143
|
+
gateSpent: number;
|
|
144
|
+
/** Consecutive blocked attempts anywhere, including the one being reported. */
|
|
145
|
+
streakSpent: number;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export class LoopReviseBudget {
|
|
149
|
+
private concerns = new Map<string, number>();
|
|
150
|
+
private gates = new Map<string, number>();
|
|
151
|
+
private streak = 0;
|
|
152
|
+
|
|
153
|
+
/** Rebuild from a session branch, fail-open: unreadable state means no rounds spent. */
|
|
154
|
+
restore(entries: readonly unknown[]): void {
|
|
155
|
+
this.concerns = new Map();
|
|
156
|
+
this.gates = new Map();
|
|
157
|
+
this.streak = 0;
|
|
158
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
159
|
+
const entry = entries[index] as
|
|
160
|
+
| { type?: string; customType?: string; data?: unknown }
|
|
161
|
+
| undefined;
|
|
162
|
+
if (entry?.type !== "custom" || entry.customType !== LOOP_REVISIONS_ENTRY_TYPE) continue;
|
|
163
|
+
const data = entry.data as PersistedBudget | undefined;
|
|
164
|
+
readCounts(data?.concerns, this.concerns);
|
|
165
|
+
readCounts(data?.gates, this.gates);
|
|
166
|
+
const streak = data?.streak;
|
|
167
|
+
if (typeof streak === "number" && Number.isSafeInteger(streak) && streak > 0) {
|
|
168
|
+
this.streak = streak;
|
|
169
|
+
}
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The whole budget, as the data half of a session entry. */
|
|
175
|
+
snapshot(): {
|
|
176
|
+
concerns: Record<string, number>;
|
|
177
|
+
gates: Record<string, number>;
|
|
178
|
+
streak: number;
|
|
179
|
+
} {
|
|
180
|
+
return {
|
|
181
|
+
concerns: Object.fromEntries(this.concerns),
|
|
182
|
+
gates: Object.fromEntries(this.gates),
|
|
183
|
+
streak: this.streak,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The custom-entry type this budget persists under. */
|
|
188
|
+
static get entryType(): string {
|
|
189
|
+
return LOOP_REVISIONS_ENTRY_TYPE;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** What `charge` would report without charging. */
|
|
193
|
+
spent(gateLabel: string, reason: string): LoopReviseCharge {
|
|
194
|
+
return {
|
|
195
|
+
concernSpent: this.concerns.get(concernKey(gateLabel, reason)) ?? 0,
|
|
196
|
+
gateSpent: this.gates.get(gateLabel) ?? 0,
|
|
197
|
+
streakSpent: this.streak,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Charge one blocked attempt and return the new totals.
|
|
203
|
+
*
|
|
204
|
+
* A concern seen for the first time *during an argument already under way at
|
|
205
|
+
* this gate* inherits that argument's length rather than starting at one.
|
|
206
|
+
* Without it the count silently stops advancing whenever the guardian
|
|
207
|
+
* rewords its objection, and the block repeats "1 revision round remains"
|
|
208
|
+
* forever. Observed live in a canary, where the agent read two identical
|
|
209
|
+
* blocks and said so: "it says again '1 revision round remains' —
|
|
210
|
+
* ambiguous". A budget whose displayed remainder does not fall is not a
|
|
211
|
+
* budget, and the agent is right not to trust it.
|
|
212
|
+
*/
|
|
213
|
+
charge(gateLabel: string, reason: string): LoopReviseCharge {
|
|
214
|
+
const key = concernKey(gateLabel, reason);
|
|
215
|
+
this.streak += 1;
|
|
216
|
+
const gateSpent = (this.gates.get(gateLabel) ?? 0) + 1;
|
|
217
|
+
const seen = this.concerns.get(key);
|
|
218
|
+
// A concern or a gate first seen mid-argument inherits the argument's
|
|
219
|
+
// length from the streak, which is the only count a reshape cannot move.
|
|
220
|
+
const concernSpent = seen === undefined ? this.streak : seen + 1;
|
|
221
|
+
this.concerns.set(key, concernSpent);
|
|
222
|
+
this.gates.set(gateLabel, gateSpent);
|
|
223
|
+
return { concernSpent, gateSpent, streakSpent: this.streak };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* An approved command ends the argument at that gate.
|
|
228
|
+
*
|
|
229
|
+
* Without this a long loop would accumulate unrelated objections all session
|
|
230
|
+
* and eventually refuse to revise anything. The per-concern counts stay:
|
|
231
|
+
* approving one command is not an answer to a different objection.
|
|
232
|
+
*
|
|
233
|
+
* The streak resets only when the approval lands on a gate that was actually
|
|
234
|
+
* blocking. Resetting it on *any* approval looked reasonable and was not: a
|
|
235
|
+
* canary agent ran three read-only `git log` and `git merge-base` calls
|
|
236
|
+
* between two blocked deletions, each approved, and every one of them handed
|
|
237
|
+
* the budget back. The backstop has to survive an agent looking things up in
|
|
238
|
+
* the middle of an argument, which is exactly what a thoughtful agent does.
|
|
239
|
+
*/
|
|
240
|
+
settle(gateLabel: string): void {
|
|
241
|
+
if (this.gates.delete(gateLabel)) this.streak = 0;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Forget everything: a new loop is not answerable for the last one's rounds. */
|
|
245
|
+
clear(): void {
|
|
246
|
+
this.concerns = new Map();
|
|
247
|
+
this.gates = new Map();
|
|
248
|
+
this.streak = 0;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function readCounts(value: unknown, into: Map<string, number>): void {
|
|
253
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
254
|
+
for (const [key, count] of Object.entries(value as Record<string, unknown>)) {
|
|
255
|
+
if (typeof count !== "number" || !Number.isSafeInteger(count) || count <= 0) continue;
|
|
256
|
+
if (!key || key.length > 512) continue;
|
|
257
|
+
into.set(key, count);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export interface LoopBlockOptions extends LoopReviseCharge {
|
|
262
|
+
gateLabel: string;
|
|
263
|
+
reason: string;
|
|
264
|
+
maxRounds?: number;
|
|
265
|
+
maxGateRounds?: number;
|
|
266
|
+
maxStreakRounds?: number;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The block an unattended loop receives instead of a modal.
|
|
271
|
+
*
|
|
272
|
+
* Within the bound it is an invitation to address the concern; past it, it is
|
|
273
|
+
* not. The final block deliberately offers exactly one next action, because a
|
|
274
|
+
* block that merely says "no" leaves the agent to invent its own way forward,
|
|
275
|
+
* and inventing a way forward past a permission gate is the failure mode.
|
|
276
|
+
*/
|
|
277
|
+
export function loopBlockReason(options: LoopBlockOptions): string {
|
|
278
|
+
const maxRounds = options.maxRounds ?? LOOP_REVISE_ROUNDS;
|
|
279
|
+
const maxGateRounds = options.maxGateRounds ?? LOOP_GATE_ROUNDS;
|
|
280
|
+
const head = `${options.gateLabel} needs user approval, and this session is running an unattended /loop, so there is no one to ask: ${options.reason}`;
|
|
281
|
+
// One number, and it is the binding one. Reporting the per-concern budget
|
|
282
|
+
// alone let a reworded objection hold it still; reporting the per-gate one
|
|
283
|
+
// alone would promise rounds the concern budget will not honour.
|
|
284
|
+
const remaining = Math.min(
|
|
285
|
+
maxRounds - options.concernSpent,
|
|
286
|
+
maxGateRounds - options.gateSpent,
|
|
287
|
+
(options.maxStreakRounds ?? LOOP_STREAK_ROUNDS) - options.streakSpent,
|
|
288
|
+
);
|
|
289
|
+
if (remaining <= 0) {
|
|
290
|
+
return [
|
|
291
|
+
head,
|
|
292
|
+
`You have used every revision round this loop gets against it. Stop reshaping the command — further variations of it will not be approved, and searching for one that is would be an end run around the gate.`,
|
|
293
|
+
"Call loop_wait naming this concern, and record the options in the ledger so a human can answer in one word. If the objective can be advanced another way that does not involve this operation, do that instead.",
|
|
294
|
+
].join("\n");
|
|
295
|
+
}
|
|
296
|
+
return [
|
|
297
|
+
head,
|
|
298
|
+
`You may revise the command to address that specific concern. ${remaining} revision ${plural(remaining, "round")} ${remaining === 1 ? "remains" : "remain"}; after that you must call loop_wait rather than reshaping further.`,
|
|
299
|
+
"Revise only to satisfy the concern as stated. Do not split, obfuscate, or re-route the command to avoid the gate — that is an end run, not a revision.",
|
|
300
|
+
].join("\n");
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function plural(count: number, word: string): string {
|
|
304
|
+
return count === 1 ? word : `${word}s`;
|
|
305
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hank-warren/pi-auto-permissions",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Fork of @ogulcancelik/pi-auto-permissions with dialog-answer user evidence: context-aware Bash permissions for Pi with automated guardian review.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -46,6 +46,8 @@
|
|
|
46
46
|
"guardian-transport.ts",
|
|
47
47
|
"openai-codex-transport.ts",
|
|
48
48
|
"subagent-context.ts",
|
|
49
|
+
"loop-context.ts",
|
|
50
|
+
"loop-revise-budget.ts",
|
|
49
51
|
"evaluation-log.ts",
|
|
50
52
|
"gates.ts",
|
|
51
53
|
"override-evidence.ts",
|
|
@@ -57,7 +59,7 @@
|
|
|
57
59
|
"CHANGELOG.md"
|
|
58
60
|
],
|
|
59
61
|
"dependencies": {
|
|
60
|
-
"@hank-warren/pi-permission-selector": "^1.
|
|
62
|
+
"@hank-warren/pi-permission-selector": "^1.3.0"
|
|
61
63
|
},
|
|
62
64
|
"peerDependencies": {
|
|
63
65
|
"@earendil-works/pi-ai": "*",
|
package/review.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SubagentExecutionContext } from "./subagent-context.js";
|
|
2
|
+
import type { LoopExecutionContext } from "./loop-context.js";
|
|
2
3
|
|
|
3
4
|
export type PermissionDecision = "approve" | "revise" | "ask_user";
|
|
4
5
|
|
|
@@ -13,8 +14,13 @@ export interface CommandReviewRequest {
|
|
|
13
14
|
cwd: string;
|
|
14
15
|
gate: string;
|
|
15
16
|
group: string;
|
|
16
|
-
/**
|
|
17
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Runtime facts for the reviewer, present only in a session that has some:
|
|
19
|
+
* a subagent child, a session running an unattended loop, or both at once
|
|
20
|
+
* (a subagent launched by a looping session is unattended for the same
|
|
21
|
+
* reason its parent is).
|
|
22
|
+
*/
|
|
23
|
+
execution?: SubagentExecutionContext | LoopExecutionContext | (SubagentExecutionContext & LoopExecutionContext);
|
|
18
24
|
}
|
|
19
25
|
|
|
20
26
|
export interface ReviewEvidenceRecord {
|
|
@@ -46,12 +52,20 @@ const TRUNCATION_HEAD_SHARE = 0.7;
|
|
|
46
52
|
* the final segment of command chains, so both are preserved; the marker
|
|
47
53
|
* tells the reviewer content is elided so it can never treat truncation as
|
|
48
54
|
* proof of absence.
|
|
55
|
+
*
|
|
56
|
+
* A cap small enough that the head share rounds up to the whole budget leaves
|
|
57
|
+
* no tail. That case must drop the tail segment entirely rather than emit
|
|
58
|
+
* `slice(-0)`, which is `slice(0)` and would splice the *entire* record back
|
|
59
|
+
* in behind a marker claiming it had been elided — output longer than the
|
|
60
|
+
* input, and a marker the reviewer is told to trust.
|
|
49
61
|
*/
|
|
50
62
|
export function truncateEvidenceText(text: string, maxChars: number): string {
|
|
51
63
|
if (maxChars <= 0 || text.length <= maxChars) return text;
|
|
52
64
|
const head = Math.ceil(maxChars * TRUNCATION_HEAD_SHARE);
|
|
53
65
|
const tail = maxChars - head;
|
|
54
|
-
|
|
66
|
+
const marker = `\n…[truncated ${text.length - maxChars} chars]…`;
|
|
67
|
+
if (tail <= 0) return `${text.slice(0, head)}${marker}`;
|
|
68
|
+
return `${text.slice(0, head)}${marker}\n${text.slice(-tail)}`;
|
|
55
69
|
}
|
|
56
70
|
|
|
57
71
|
const COLLAPSED_TOOL_PATTERN = /^TOOL (\S+)/;
|
|
@@ -136,6 +150,17 @@ Judge risk by effect scope and reversibility relative to the subagent's own work
|
|
|
136
150
|
- Lifecycle commands (including with sudo) for containers or services the subagent itself stood up are part of that workflow. Restarting, reconfiguring, or disabling shared host daemons and system services is host-level configuration, not subagent scope.
|
|
137
151
|
- Reserve "ask_user" for effects that escape the subagent's scope: shared or default branches, remote resources it does not own, host-level configuration, production systems, credential or secret access, and data leaving the machine.`;
|
|
138
152
|
|
|
153
|
+
/**
|
|
154
|
+
* Appended to the reviewer system prompt only when an unattended pi-loop is
|
|
155
|
+
* running (detectLoopContext). Like the subagent section it changes how the
|
|
156
|
+
* reviewer weighs the *absence of a user*, and nothing about what is safe.
|
|
157
|
+
*/
|
|
158
|
+
export const LOOP_CONTEXT_SYSTEM_PROMPT = `UNATTENDED LOOP EXECUTION CONTEXT
|
|
159
|
+
This session is working a long-running objective under an automated loop, with no human watching it. There is no interactive user: an "ask_user" decision does not open a prompt, it returns your concern to the agent as a block. The latest proposed action carries an "execution" object with the loop's runtime facts.
|
|
160
|
+
Decide exactly as you would with a user present. The absence of a user is not authorization, and it is not a reason to approve a medium- or high-risk action that the evidence does not support; it only changes how your decision is delivered.
|
|
161
|
+
The agent is told it may revise the command a bounded number of times to address the concern you state, and must then stop. Write the concern so that a revision is possible where one exists: name the specific property that made the action unsafe, not merely that it was refused.
|
|
162
|
+
An agent that returns with a command differing only cosmetically, split into parts, or re-routed through another tool has not addressed your concern — judge the new command on its own effects and say so again.`;
|
|
163
|
+
|
|
139
164
|
/**
|
|
140
165
|
* Appended to the reviewer policy prompt unconditionally (so sessions using a
|
|
141
166
|
* customized systemPromptFile still receive it). Explains the user-source
|