pi-delegation-policy 0.21.1 → 0.22.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 CHANGED
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.22.0 - 2026-10-21
4
+
5
+ ### Added
6
+
7
+ - One ephemeral configuration-change notice on the next user turn after an effective configuration
8
+ change, whether a `/delegate` save or an edit of the global defaults that reaches the session. It
9
+ lists the values that changed since the configuration the model was last shown: intensity,
10
+ preference, ordinary roles, Visual Design, thinking policies, Advisor entries, mode and launch, the
11
+ ContextShunt mode, and the reader role, toggle and answer limit. The ContextShunt enforcement
12
+ tuning (`limits`, `exceptionPatterns`, `delegationHintPatterns`) is left out on purpose: it changes
13
+ how much the shunt preserves or compacts, not the assignments the model follows. The notice exists
14
+ only in the requests of that turn, never in the conversation, and stays identical across their
15
+ retries. With both axes off by configuration it reports one line,
16
+ `Delegation and Advisor disabled by this policy.`, and then injects nothing; an Advisor left on but
17
+ unusable is not reported as disabled.
18
+ - The reference is the configuration the model was actually shown. Changes made before a turn are
19
+ grouped, a reversion reports nothing, an edit that leaves effective values unchanged reports
20
+ nothing, and a change made while a turn is running waits for the next turn. The notice is consumed
21
+ when the run ends with its last recorded outcome completed, read from the final `agent_end`, so a
22
+ retried error that then succeeds consumes it while an error or abort reported before that point
23
+ leaves the change pending. Residual: an abort or a thrown error after the last successful response,
24
+ which the host reports through no later public event, can still consume it. Session starts,
25
+ reloads, forks and tree moves set the reference silently, and a prompt another extension sends with
26
+ `sendUserMessage` neither receives nor consumes the notice.
27
+
28
+ ### Compatibility and verification
29
+
30
+ - No configuration, schema or dependency change. The notice uses public Pi `0.87.1` events,
31
+ is converted to user text by the host like any custom message and identifies itself as an extension
32
+ notice; it is not system policy and changes no model, permission or authority. The extension writes
33
+ no notice text to session history or its local log. This does not limit request retention by the
34
+ provider or other authorized host components. The existing local JSONL log keeps its fields.
35
+ - Covered against the registered hooks with a synthetic host: grouping and reversion, no-op saves,
36
+ retries, a mid-turn change, a completed turn followed by a failed continuation, error and abort, an
37
+ unknown run outcome, the accepted abort/throw window after a completed response, the both-off
38
+ notice, an extension-sent prompt, session and tree resets, global changes, the Advisor context mode,
39
+ and the real host conversion and payload repair. No real-provider run was performed. The synthetic
40
+ host encodes Pi `0.87.1`'s event order instead of exercising a host process, so a future host that
41
+ reordered `input` and `before_agent_start` would not be detected.
42
+
3
43
  ## 0.21.1 - 2026-10-19
4
44
 
5
45
  ### Fixed
package/README.md CHANGED
@@ -6,7 +6,7 @@ general subagent runner. Only explicit tools can request reader work or Advisor
6
6
  the authorized host executor; hooks never launch children.
7
7
 
8
8
  > **Docs:** [yivas.github.io/pi-delegation-policy](https://yivas.github.io/pi-delegation-policy/).
9
- > Version **0.21.1** requires Pi `0.87.1` or later (`>=0.87.1`); it re-applies its marked policy block in the final provider payload.
9
+ > Version **0.22.0** requires Pi `0.87.1` or later (`>=0.87.1`); it re-applies its marked policy block in the final provider payload.
10
10
  > Version `0.14.1` supports Pi `0.84.3` or later (`>=0.84.3`).
11
11
  >
12
12
  > Independent Advisor mode and its companion file are available from version `0.17.0`.
@@ -15,7 +15,7 @@ the authorized host executor; hooks never launch children.
15
15
  ## Install
16
16
 
17
17
  ```bash
18
- pi install npm:pi-delegation-policy@0.21.1
18
+ pi install npm:pi-delegation-policy@0.22.0
19
19
  # restart Pi, or run /reload
20
20
  ```
21
21
 
@@ -33,7 +33,7 @@ to inheritance later.
33
33
 
34
34
  | Intensity | What the guidance asks |
35
35
  | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
- | `off` | No execution-delegation guidance. An independently enabled Advisor still injects its own section; with both off nothing is injected. |
36
+ | `off` | No execution-delegation guidance. An independently enabled Advisor still injects its own section; with both off no policy block is injected. |
37
37
  | `normal` | Delegate substantial, separable work only when the expected benefit clearly outweighs briefing, supervision, review, and integration. Borderline work stays with the main agent. |
38
38
  | `aggressive` | Delegate suitable substantial, separable, independently checkable work by default when objective and acceptance criteria are clear. |
39
39
  | `orchestrator` | Delegate all transferable execution before it begins whenever an enabled capable role and an authorized launcher exist, regardless of size: small lookups, reading, detailed planning, edits, tests, writing, detailed review, and integration mechanics. Direct work needs a briefly stated exception, and final acceptance stays with the main agent. |
@@ -105,7 +105,7 @@ Local timeouts and cancellation do not cap external generation, retries or cost.
105
105
  | `off` | Inject no Advisor guidance and keep the saved model and thinking policy. |
106
106
  | `with-delegation` | Consult only while delegation is active and an Advisor is configured. Default when the key is absent. |
107
107
 
108
- `D:OFF A:ON` shows consultation-only guidance; `D:OFF A:OFF` shows nothing injected. `/delegate reset`
108
+ `D:OFF A:ON` shows consultation-only guidance; `D:OFF A:OFF` means neither axis injects a policy block. `/delegate reset`
109
109
  turns both off for the branch; `/delegate off` leaves an independently enabled Advisor active.
110
110
 
111
111
  Errors are reported per axis. Each entry validates independently: `A:ON` means all valid, `A:PART` means one of two valid
@@ -190,6 +190,49 @@ example `advisor-mode=with-delegation (global); A:OFF` and `thinking-advisor=uns
190
190
  `D:OFF`, `D:NORM`, `D:AGG`, and `D:ORCH` describe delegation; `A:OFF`, `A:ON`, `A:PART`, and `A:ERR` describe
191
191
  Advisor. None of them proves that a launch happened or that another system followed the guidance.
192
192
 
193
+ ### Configuration change notice
194
+
195
+ Available from `0.22.0`. The declared Pi peer remains
196
+ `>=0.87.1`; the notice hooks and conversion are verified against `0.87.1` with a synthetic harness,
197
+ not a full host process or later host versions.
198
+
199
+ After an effective configuration change — a `/delegate` save, or an edit of the global defaults that
200
+ changes effective values — the next user turn carries one extension-owned notice in the request
201
+ context. It lists the values that changed since the configuration the model was last shown:
202
+ intensity, preference, ordinary roles, Visual Design, thinking policies, Advisor entries, mode and
203
+ launch, the ContextShunt mode, and the reader role, toggle and answer limit. The ContextShunt
204
+ enforcement tuning (`limits`, `exceptionPatterns`, `delegationHintPatterns`) is left out on purpose:
205
+ it changes how much the shunt preserves or compacts, not the assignments the model follows. The
206
+ notice is not system policy and never enters the conversation: it exists only in the requests of
207
+ that turn, identical across their retries, and it disappears with the turn.
208
+
209
+ The reference is the configuration the model was actually shown, so changes made before a turn are
210
+ grouped, a reversion before the turn reports nothing, and an edit that leaves effective values
211
+ unchanged reports nothing. Opening or cancelling the editor writes nothing and reports nothing. A
212
+ change made while a turn is already running reaches the policy immediately and is reported on the
213
+ next turn; a revision that has not been shown is never consumed by an earlier turn.
214
+
215
+ Consumption happens when the run ends and its last recorded outcome is a completed response: the
216
+ extension reads the last assistant message of the final `agent_end` and keeps the presented revision
217
+ only when that response completed. An error the host retries and that then succeeds counts as
218
+ completed, so the notice is consumed there. An error or an abort reported before that point leaves
219
+ the change pending, and the next user turn reports it again. Residual: an abort or a thrown error
220
+ after the last successful response, which the host reports through no later public event, can still
221
+ consume the notice; no public signal separates that window.
222
+
223
+ With delegation off and Advisor off by configuration, one notice says `Delegation and Advisor
224
+ disabled by this policy.` and nothing further is injected while both stay off. An Advisor left on but
225
+ unusable is not reported as disabled, because the configuration did not disable it. Every notice is
226
+ scoped to this extension and revokes no other instruction, permission, or authority. Session starts,
227
+ reloads, forks and tree navigation set the reference silently, so no notice appears at startup.
228
+ The extension writes no notice text to session history or its local log, so compaction summaries
229
+ and branches cannot inherit one from stored history. This does not limit the provider's or other
230
+ authorized host components' request retention. A prompt another extension sends with
231
+ `sendUserMessage` is not a user turn: it neither receives nor consumes the notice. The notice reports configuration, not availability: an unusable model keeps its value in the
232
+ list and the policy block that would assign it may simply be absent, so nothing in the notice
233
+ presents that model as usable. For new work, the notice points the model at the current valid
234
+ assignments and thinking rules in this policy rather than earlier settings in the conversation.
235
+
193
236
  ## ContextShunt
194
237
 
195
238
  ContextShunt is a separate opt-in layer, off by default. `observe` records what enforcement would
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-delegation-policy",
3
- "version": "0.21.1",
3
+ "version": "0.22.0",
4
4
  "private": false,
5
5
  "description": "A Pi extension for configurable delegation intensity and exact subagent role model references.",
6
6
  "type": "module",
@@ -0,0 +1,211 @@
1
+ import type { ContextWithSystemEvent } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ ROLE_LABELS,
4
+ type AdvisorLaunch,
5
+ type AdvisorMode,
6
+ type ContextShuntMode,
7
+ type EffectiveDelegateState,
8
+ type Intensity,
9
+ type ModelRef,
10
+ type ModelRole,
11
+ type OrdinaryRoleSetting,
12
+ type Preference,
13
+ type ThinkingPolicy,
14
+ } from "./types.ts";
15
+
16
+ /** Custom message type of the notice. The host keeps it on the request copy only. */
17
+ export const CONFIG_NOTICE_TYPE = "pi-delegation-policy.config-notice";
18
+ /** The scope belongs to this policy, never to any other instruction or authority. */
19
+ export const BOTH_OFF_LINE = "Delegation and Advisor disabled by this policy.";
20
+
21
+ export type ConfigNoticeMessage = ContextWithSystemEvent["messages"][number];
22
+
23
+ /**
24
+ * An ordinary role has three effective states, and they must stay apart: not configured is an error
25
+ * while delegation is on, explicitly disabled is a valid partial policy, and a model reference
26
+ * delegates. The effective state of Visual Design only distinguishes present from absent, so it
27
+ * never carries `unset`.
28
+ */
29
+ type RoleText = { kind: "unset" } | { kind: "disabled" } | { kind: "model"; reference: string };
30
+ /** `level:<level>`, `range:<min>..<max>`, or `null` when the role has no thinking policy. */
31
+ type ThinkingText = string | null;
32
+
33
+ /**
34
+ * Deterministic view of the effective configuration that the notice compares. Derived status stays
35
+ * out: model availability, credentials, diagnostics, value provenance and the Advisor context mode
36
+ * cannot produce a notice, and neither can the rendered policy text.
37
+ */
38
+ export type NoticeProjection = {
39
+ intensity: Intensity;
40
+ preference: Preference;
41
+ roles: Record<ModelRole, RoleText>;
42
+ uiDesign: RoleText;
43
+ thinking: Record<ModelRole | "uiDesign", ThinkingText>;
44
+ advisors: Array<{ model: string; thinking: ThinkingText }>;
45
+ advisorMode: AdvisorMode;
46
+ advisorLaunch: AdvisorLaunch;
47
+ context: {
48
+ mode: ContextShuntMode;
49
+ readerEnabled: boolean;
50
+ readerRole: ModelRole;
51
+ answerMaxBytes: number;
52
+ };
53
+ };
54
+
55
+ function thinkingText(policy: ThinkingPolicy | undefined): ThinkingText {
56
+ if (!policy) return null;
57
+ return "level" in policy ? `level:${policy.level}` : `range:${policy.min}..${policy.max}`;
58
+ }
59
+
60
+ function ordinaryRoleText(setting: OrdinaryRoleSetting | undefined): RoleText {
61
+ if (setting === null) return { kind: "disabled" };
62
+ if (!setting) return { kind: "unset" };
63
+ return { kind: "model", reference: `${setting.provider}/${setting.model}` };
64
+ }
65
+
66
+ function optionalRoleText(setting: ModelRef | undefined): RoleText {
67
+ if (!setting) return { kind: "disabled" };
68
+ return { kind: "model", reference: `${setting.provider}/${setting.model}` };
69
+ }
70
+
71
+ export function projectNoticeConfig(effective: EffectiveDelegateState): NoticeProjection {
72
+ return {
73
+ intensity: effective.intensity,
74
+ preference: effective.preference,
75
+ roles: {
76
+ small: ordinaryRoleText(effective.small),
77
+ medium: ordinaryRoleText(effective.medium),
78
+ large: ordinaryRoleText(effective.large),
79
+ },
80
+ uiDesign: optionalRoleText(effective.uiDesign),
81
+ thinking: {
82
+ small: thinkingText(effective.thinking.small),
83
+ medium: thinkingText(effective.thinking.medium),
84
+ large: thinkingText(effective.thinking.large),
85
+ uiDesign: thinkingText(effective.thinking.uiDesign),
86
+ },
87
+ advisors: effective.advisors.map((advisor) => ({
88
+ model: `${advisor.provider}/${advisor.model}`,
89
+ thinking: thinkingText(advisor.thinking),
90
+ })),
91
+ advisorMode: effective.advisorMode,
92
+ advisorLaunch: effective.advisorLaunch,
93
+ // The configured mode keeps an intensity edit from fabricating a second change.
94
+ context: {
95
+ mode: effective.contextShunt.configuredMode,
96
+ readerEnabled: effective.contextShunt.readerEnabled,
97
+ readerRole: effective.contextShunt.readerRole,
98
+ answerMaxBytes: effective.contextShunt.answerMaxBytes,
99
+ },
100
+ };
101
+ }
102
+
103
+ type NoticeField = { label: string; value: string };
104
+
105
+ const TEXT_ROLES: readonly (ModelRole | "uiDesign")[] = ["small", "medium", "large", "uiDesign"];
106
+
107
+ function roleValue(text: RoleText): string {
108
+ if (text.kind === "model") return text.reference;
109
+ return text.kind === "disabled" ? "disabled" : "not configured";
110
+ }
111
+
112
+ function advisorModelValue(model: string | undefined): string {
113
+ return model ?? "none";
114
+ }
115
+
116
+ function thinkingValue(text: ThinkingText | undefined): string {
117
+ if (text === null || text === undefined) return "unset";
118
+ return text.startsWith("level:")
119
+ ? `fixed ${text.slice("level:".length)}`
120
+ : `range ${text.slice("range:".length)}`;
121
+ }
122
+
123
+ /**
124
+ * Fields in one canonical order. Advisor count is taken from both projections so a removed Advisor
125
+ * still reports its own two fields.
126
+ */
127
+ function projectionFields(projection: NoticeProjection, advisorCount: number): NoticeField[] {
128
+ return [
129
+ { label: "Delegation intensity", value: projection.intensity },
130
+ { label: "Model preference", value: projection.preference },
131
+ ...TEXT_ROLES.map((role) => ({
132
+ label: `${ROLE_LABELS[role]} model`,
133
+ value: roleValue(role === "uiDesign" ? projection.uiDesign : projection.roles[role]),
134
+ })),
135
+ ...TEXT_ROLES.map((role) => ({
136
+ label: `${ROLE_LABELS[role]} thinking`,
137
+ value: thinkingValue(projection.thinking[role]),
138
+ })),
139
+ { label: "Advisor mode", value: projection.advisorMode },
140
+ { label: "Advisor launch", value: projection.advisorLaunch },
141
+ ...Array.from({ length: advisorCount }, (_, index) => {
142
+ const advisor = projection.advisors[index];
143
+ return [
144
+ { label: `Advisor ${index + 1} model`, value: advisorModelValue(advisor?.model) },
145
+ { label: `Advisor ${index + 1} thinking`, value: thinkingValue(advisor?.thinking) },
146
+ ];
147
+ }).flat(),
148
+ { label: "Context protection", value: projection.context.mode },
149
+ {
150
+ label: "Context reader",
151
+ value: projection.context.readerEnabled ? "enabled" : "disabled",
152
+ },
153
+ { label: "Context reader role", value: projection.context.readerRole },
154
+ {
155
+ label: "Context reader answer limit",
156
+ value: `${projection.context.answerMaxBytes} bytes`,
157
+ },
158
+ ];
159
+ }
160
+
161
+ /** One `- label: previous -> current` line per changed field, in the canonical field order. */
162
+ export function changedValueLines(previous: NoticeProjection, current: NoticeProjection): string[] {
163
+ const advisorCount = Math.max(previous.advisors.length, current.advisors.length);
164
+ const before = projectionFields(previous, advisorCount);
165
+ const after = projectionFields(current, advisorCount);
166
+ return after.flatMap((field, index) => {
167
+ const previousValue = before[index]!.value;
168
+ return previousValue === field.value
169
+ ? []
170
+ : [`- ${field.label}: ${previousValue} -> ${field.value}`];
171
+ });
172
+ }
173
+
174
+ /**
175
+ * Lines the notice reports for one observed change. While both axes are already off a value edit
176
+ * changes nothing the model can act on, so only the transition into that state speaks, once.
177
+ */
178
+ export function noticeLines(change: {
179
+ previous: NoticeProjection;
180
+ current: NoticeProjection;
181
+ previouslyOff: boolean;
182
+ currentlyOff: boolean;
183
+ }): string[] {
184
+ const lines = changedValueLines(change.previous, change.current);
185
+ if (!lines.length || !change.currentlyOff) return lines;
186
+ return change.previouslyOff ? [] : [`- ${BOTH_OFF_LINE}`];
187
+ }
188
+
189
+ export function renderConfigNotice(lines: string[]): string {
190
+ return [
191
+ "<delegation_config_notice>",
192
+ "<!-- pi-delegation-policy:notice -->",
193
+ "This notice comes from the pi-delegation-policy extension, not from the user.",
194
+ "The /delegate configuration changed before this turn:",
195
+ ...lines,
196
+ "The delegation policy in the system prompt, when present, states the values in force for the present request.",
197
+ "For new work, follow the current valid assignments and thinking rules in this policy, not earlier settings in the conversation.",
198
+ "This notice only records what changed in this extension's configuration and revokes no other instruction, permission, or authority.",
199
+ "</delegation_config_notice>",
200
+ ].join("\n");
201
+ }
202
+
203
+ export function createConfigNotice(lines: string[], timestamp: number): ConfigNoticeMessage {
204
+ return {
205
+ role: "custom",
206
+ customType: CONFIG_NOTICE_TYPE,
207
+ content: renderConfigNotice(lines),
208
+ display: false,
209
+ timestamp,
210
+ };
211
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import type {
2
+ AgentActivityOutcome,
3
+ AgentEndEvent,
2
4
  ExtensionAPI,
3
5
  ExtensionCommandContext,
4
6
  ExtensionContext,
7
+ InputSource,
5
8
  } from "@earendil-works/pi-coding-agent";
6
9
  import type { AutocompleteItem } from "@earendil-works/pi-tui";
7
10
  import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
@@ -19,6 +22,13 @@ import {
19
22
  ADVISOR_AGENT_NAME,
20
23
  } from "./advisor-executor.ts";
21
24
  import { AdvisorLog } from "./advisor-log.ts";
25
+ import {
26
+ createConfigNotice,
27
+ noticeLines,
28
+ projectNoticeConfig,
29
+ type ConfigNoticeMessage,
30
+ type NoticeProjection,
31
+ } from "./config-notice.ts";
22
32
  import { ContextShuntAdapter } from "./context-shunt-adapter.ts";
23
33
  import { ContextShuntExecutor } from "./context-shunt-executor.ts";
24
34
  import {
@@ -176,6 +186,28 @@ function isContextShuntDisabled(state: RuntimeState): boolean {
176
186
  state.effective.contextShunt.suspended
177
187
  );
178
188
  }
189
+ function bothAxesOff(state: RuntimeState): boolean {
190
+ return state.effective.intensity === "off" && !isAdvisorEnabled(state.effective);
191
+ }
192
+ /** What the model has been told: the configuration shown by the last consumed notice. */
193
+ type ConfigReference = { projection: NoticeProjection; axesOff: boolean };
194
+ /**
195
+ * The host decides a turn's outcome from the last assistant message, and reports `completed` for
196
+ * every stop reason except an abort or an error. The same rule keeps the notice's consume rule
197
+ * aligned with the host's own notion of a finished turn.
198
+ */
199
+ function endOutcome(messages: AgentEndEvent["messages"]): AgentActivityOutcome | undefined {
200
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
201
+ const message = messages[index];
202
+ if (message?.role !== "assistant") continue;
203
+ return message.stopReason === "aborted"
204
+ ? "aborted"
205
+ : message.stopReason === "error"
206
+ ? "error"
207
+ : "completed";
208
+ }
209
+ return undefined;
210
+ }
179
211
  function synchronizeContextShunt(shunt: ContextShuntAdapter, state: RuntimeState): void {
180
212
  if (isContextShuntDisabled(state)) shunt.clearPending();
181
213
  }
@@ -384,6 +416,58 @@ export function createPiDelegationPolicy(options: PiDelegationPolicyOptions = {}
384
416
  readerEpoch += 1;
385
417
  executor.cancel();
386
418
  };
419
+ // The notice follows the user's turns, not host turns. `input` reports where the next prompt
420
+ // comes from, `before_agent_start` opens one run per fresh prompt, and the comparison runs on
421
+ // that user turn's first request. A change made while a turn is already running updates the
422
+ // policy as usual and is reported on the next user turn, so no request carries a notice that
423
+ // contradicts the policy of the same request.
424
+ let configBaseline: ConfigReference | undefined;
425
+ let inputSource: InputSource | undefined;
426
+ let userTurn = 0;
427
+ let runToken = 0;
428
+ let diffedTurn: number | undefined;
429
+ let runOutcome: AgentActivityOutcome | undefined;
430
+ let presentedNotice:
431
+ { runToken: number; reference: ConfigReference; message: ConfigNoticeMessage } | undefined;
432
+ const startConfigBaseline = (state: RuntimeState): void => {
433
+ configBaseline = {
434
+ projection: projectNoticeConfig(state.effective),
435
+ axesOff: bothAxesOff(state),
436
+ };
437
+ userTurn = 0;
438
+ runToken = 0;
439
+ diffedTurn = undefined;
440
+ runOutcome = undefined;
441
+ presentedNotice = undefined;
442
+ };
443
+ const configNotice = (state: RuntimeState): ConfigNoticeMessage | undefined => {
444
+ if (diffedTurn !== userTurn) {
445
+ diffedTurn = userTurn;
446
+ presentedNotice = undefined;
447
+ const current: ConfigReference = {
448
+ projection: projectNoticeConfig(state.effective),
449
+ axesOff: bothAxesOff(state),
450
+ };
451
+ // Every session start and tree move sets a baseline. Only an unreadable configuration
452
+ // defers it to this first successful refresh, which then reports nothing.
453
+ if (configBaseline === undefined) configBaseline = current;
454
+ else {
455
+ const lines = noticeLines({
456
+ previous: configBaseline.projection,
457
+ current: current.projection,
458
+ previouslyOff: configBaseline.axesOff,
459
+ currentlyOff: current.axesOff,
460
+ });
461
+ if (lines.length)
462
+ presentedNotice = {
463
+ runToken,
464
+ reference: current,
465
+ message: createConfigNotice(lines, Date.now()),
466
+ };
467
+ }
468
+ }
469
+ return presentedNotice?.runToken === runToken ? presentedNotice.message : undefined;
470
+ };
387
471
  const rememberRuntime = (state: RuntimeState): RuntimeState => {
388
472
  if (
389
473
  readerAuthorization(latestRuntime)?.fingerprint !== readerAuthorization(state)?.fingerprint
@@ -802,7 +886,7 @@ export function createPiDelegationPolicy(options: PiDelegationPolicyOptions = {}
802
886
  });
803
887
  pi.on("session_start", async (_event, ctx) => {
804
888
  advisorContext = undefined;
805
- await refreshRuntime(ctx);
889
+ startConfigBaseline(await refreshRuntime(ctx));
806
890
  });
807
891
  pi.on("session_tree", async (_event, ctx) => {
808
892
  readerEpoch += 1;
@@ -810,7 +894,30 @@ export function createPiDelegationPolicy(options: PiDelegationPolicyOptions = {}
810
894
  advisorExecutor.rotate();
811
895
  shunt.clearPending();
812
896
  advisorContext = undefined;
813
- await refreshRuntime(ctx);
897
+ startConfigBaseline(await refreshRuntime(ctx));
898
+ });
899
+ pi.on("input", async (event) => {
900
+ // The host emits this for every submitted input immediately before the prompt it belongs to,
901
+ // and `before_agent_start` follows only for a fresh prompt. Attribution therefore depends on
902
+ // that order, which Pi 0.87.1 keeps for every path that reaches it; a host that emitted the
903
+ // anchor first would leave the previous source in place, so the notice would follow the
904
+ // earlier prompt instead of skipping an extension one. No public signal can detect that
905
+ // change, so it stays a documented residual.
906
+ inputSource = event.source;
907
+ });
908
+ pi.on("before_agent_start", async () => {
909
+ const source = inputSource;
910
+ inputSource = undefined;
911
+ runToken += 1;
912
+ runOutcome = undefined;
913
+ // Commands, input interception and tool iterations never reach this event, and the host
914
+ // emits it once per fresh prompt. A prompt an extension sends is not the user's turn, so it
915
+ // neither receives nor consumes a notice waiting for the user.
916
+ if (source === "extension") {
917
+ diffedTurn = userTurn;
918
+ return;
919
+ }
920
+ userTurn += 1;
814
921
  });
815
922
  pi.on("context_with_system", async (event, ctx) => {
816
923
  const state = await refreshRuntime(ctx);
@@ -822,7 +929,7 @@ export function createPiDelegationPolicy(options: PiDelegationPolicyOptions = {}
822
929
  typeof systemMessage.content !== "string"
823
930
  )
824
931
  return undefined;
825
-
932
+ const notice = configNotice(state);
826
933
  const ownedPolicyBlock =
827
934
  /(?:\n\n)?<delegation_policy>\n<!-- pi-delegation-policy:owned -->[\s\S]*?<\/delegation_policy>/g;
828
935
  let replacedPolicy = false;
@@ -856,15 +963,35 @@ export function createPiDelegationPolicy(options: PiDelegationPolicyOptions = {}
856
963
  ...(sections && Object.keys(sections).length > 0 ? { sections } : {}),
857
964
  },
858
965
  ...event.messages.slice(1),
966
+ // Appended last, never inside the system block: a tool call stays adjacent to its result,
967
+ // the stored transcript prefix of the request is unchanged, and the host already sends
968
+ // user-role text after a tool result for its own custom messages.
969
+ ...(notice ? [notice] : []),
859
970
  ],
860
971
  };
861
972
  });
973
+ pi.on("agent_settled", async () => {
974
+ // The notice is consumed when the last outcome the run reported was a completed response:
975
+ // `agent_end` reports one outcome per low-level run, and this event marks the end of the whole
976
+ // run, emitted once in the host's `finally` after retries, compaction and queued continuations.
977
+ // A completed settle boundary can still be followed by another request, or by an aborted one,
978
+ // so the last recorded outcome decides and an unknown one never consumes. Accepted residual:
979
+ // an abort or a throw after the last completed response, which the host reports through no
980
+ // later public event, leaves that `completed` standing and consumes the notice.
981
+ if (runOutcome !== "completed" || presentedNotice?.runToken !== runToken) return;
982
+ // The revision the model received, not the live one: a change made after that request stays
983
+ // pending for the next turn.
984
+ configBaseline = presentedNotice.reference;
985
+ });
862
986
  pi.on("before_provider_request", async (event, ctx) => {
863
987
  const state = await refreshProviderRuntime(ctx);
864
988
  if (!state) return event.payload;
865
989
  return updateProviderPolicy(event.payload, renderPolicy(ctx, state));
866
990
  });
867
- pi.on("agent_end", async () => {
991
+ pi.on("agent_end", async (event) => {
992
+ // The event carries the messages of this low-level run; a run that reports none has no
993
+ // outcome to trust, and an unknown outcome never consumes a notice.
994
+ runOutcome = endOutcome(event.messages ?? []);
868
995
  shunt.clearConsumed();
869
996
  });
870
997
  pi.on("tool_call", async (event) => {
@@ -923,6 +1050,9 @@ export function createPiDelegationPolicy(options: PiDelegationPolicyOptions = {}
923
1050
  pi.on("session_shutdown", async (_event, ctx) => {
924
1051
  readerEpoch += 1;
925
1052
  latestRuntime = undefined;
1053
+ configBaseline = undefined;
1054
+ presentedNotice = undefined;
1055
+ runOutcome = undefined;
926
1056
  executor.close();
927
1057
  advisorExecutor.close();
928
1058
  await advisorLog.close();