@howaboua/pi-notes-compaction 0.0.4 → 0.0.6

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,26 @@
1
1
  # @howaboua/pi-notes-compaction
2
2
 
3
+ ## 0.0.6
4
+
5
+ - Requires Pi 1.2.0 or newer.
6
+
7
+ - Added per-model activation through `/notes` and an editable whitelist.
8
+ - Added **New window requests: off | pi-limits | unrestricted**. `new_context` requires a successful note write immediately beforehand.
9
+ - Shared local notes now remain readable after their owner closes or Shepherdr is removed.
10
+ - Fixed window identity and recovery guidance disappearing after compaction.
11
+ - Continuations now apply Pi's full prompt and tool preparation.
12
+
13
+ ## 0.0.5
14
+
15
+ - We've been informed that Astra and Sol currently retain their prompt caches for around an hour. If you use notes-managed idle rollover, consider increasing it from 25 to 55 minutes. Cache retention can vary. YMMV. We'll keep monitoring. Please share your cache-retention and long-context quota observations in [the feedback thread](https://github.com/IgorWarzocha/howaboua-pi-stuff/issues/508).
16
+
17
+ Added configurable task-boundary reminders and a clearer settings layout.
18
+
19
+ - Added optional reminders at preset or custom token counts when context capacity exceeds 272k, showing the remaining percentage.
20
+ - Status text and keyboard hints now wrap to fit narrow terminals.
21
+ - Notes help now lists required arguments. Writes accept `content` when `text` is omitted.
22
+ - Fixed fresh worker startup with Notes enabled.
23
+
3
24
  ## 0.0.4
4
25
 
5
26
  - Fixed note queries and manual context rollover with Codex Conversion.
@@ -12,6 +12,8 @@ Two request channels use synchronous callbacks:
12
12
  // PCC asks whether an external continuity owner is installed.
13
13
  pi.events.emit("pi-notes-compaction:owner:v1", {
14
14
  protocol: 1,
15
+ ctx, // current model, including before preparation and after model selection
16
+ projection(owner) { /* retain historical message and branch projection */ },
15
17
  reply(owner) { /* retain the NotesOwner for this runtime */ }
16
18
  })
17
19
 
@@ -23,6 +25,8 @@ pi.events.on("pi-notes-compaction:bridge:v1", request => {
23
25
 
24
26
  Every extension finishes loading before `session_start`. Both sides must discover again at that boundary. PCC must check for the external owner before its first session initialization and before every activation-plan or tool rewrite. This works in either load order. No prefix edit, timer or module-global import is discovery.
25
27
 
28
+ Ownership is model-dependent. Notes replies only when enabled for the request's current model. If a context-bearing discovery gets no reply after takeover, PCC releases the external owner, resets its pending continuity state and restores its own four tool definitions through its original registration API. Reclaim on a matching model uses the same handoff below. Context-free loading discovery must not release an existing owner. The optional `projection` callback receives only message and branch projection regardless of activation, including when resuming on an excluded model. Historical Notes retirement boundaries remain effective when inactive, but Notes guidance and reminders are removed from model context.
29
+
26
30
  `bridge.claim(owner)` returns either `{ claimed: false, reason }` or `{ claimed: true, registerTools }`. A success synchronously transfers continuity policy ownership. The callback `registerTools(tools, ctx)` registers the supplied four definitions **through PCC's own `pi.registerTool` API**, replacing PCC's existing definitions in place. The new extension does not register duplicate names when takeover succeeds. Pi cannot unregister tools. Hiding a legacy definition in another extension is not sufficient because registry precedence depends on extension order.
27
31
 
28
32
  PCC may defer its legacy registrations until discovery, but it must still use the same PCC-owned registration callback on takeover. With no external owner, PCC retains all existing behavior. A failed claim must leave its legacy owner intact. Do not acknowledge a partial takeover.
@@ -33,7 +37,7 @@ Add an explicit external-owner branch to `adapter/activation/runtime-plan.ts` an
33
37
 
34
38
  Required boundaries in the current source:
35
39
 
36
- - `context-management/tools.ts` and `extension/tools.ts`: replace the four tools through the registration callback. Active-tool and schema rewrites must preserve delegated definitions. Do not reinstall legacy routers on model changes or settings changes.
40
+ - `context-management/tools.ts` and `extension/tools.ts`: replace the four tools through the registration callback. Active-tool and schema rewrites must preserve delegated definitions while Notes owns continuity. Consult optional `owner.allowsWindowRequests()` when selecting active tools. A false result hides `new_context` without removing its registration. Restore legacy routers only when Notes yields ownership.
37
41
  - `extension/session-lifecycle.ts` and `extension/turn-lifecycle.ts`: skip legacy notes/window initialization, input holding, checkpoint admission, note freshness, reminders, settlement records and continuation scheduling. Leave PCC's prompt preparation, runtime synchronization, Notebook status, voice, quota and provider lifecycle active.
38
42
  - `extension/compaction-lifecycle.ts`: consult `owner.allowsCompaction(reason)` before any compaction work. When false, return without work so the owner's hook can cancel and handle notes-only rollover, regardless of extension order. Skip legacy `contextWindows.prepareCompaction` and notes checkpoint overrides. When this extension allows normal compaction, run the unchanged installed PCC normal-compaction path. Overflow stays in the same window. Notebook checkpointing, native compaction, replay, transport reset and presentation remain PCC-owned.
39
43
  - `context-management/window-manager.ts`, `window-request.ts` and native replay serializers: use `owner.identity(ctx)` and `owner.projectBranch(entries)` for the active window and retirement boundary. Preserve PCC request metadata and zero-based generation semantics. Do not recreate remote history-ingest requirements for local notes.
@@ -42,7 +46,7 @@ Required boundaries in the current source:
42
46
 
43
47
  Normal compaction output belongs exclusively to Pi and PCC. This package does not port V2, copy encrypted compaction checkpoints or persist its own compaction records.
44
48
 
45
- `beforeWindow(ctx, signal?)` is optional. PCC can checkpoint Notebook and reset owned transport/window state there. It must fail before a new marker is appended if preparation fails. A rollover continuation is a settled **user** kickoff. Both the checkpoint and successor must run the complete `input` and `before_agent_start` chain, not a captured prompt or developer-message turn.
49
+ `beforeWindow(ctx, signal?)` is optional. PCC can checkpoint Notebook and reset owned transport/window state there. It must fail before a new marker is appended if preparation fails. A rollover continuation is a settled custom-message kickoff through Pi 1.2’s complete `before_agent_start` chain. Checkpoint requests use custom kickoffs too; held user input retains its original `input` admission. The `pi-notes-compaction:custom-turn-admission:v1` event admits idle custom kickoffs before Pi reserves startup as busy, so rollover compaction can finish first.
46
50
 
47
51
  ## Code and Notebook
48
52
 
@@ -93,7 +97,7 @@ For direct calls, extend PCC's `codexHistoryNotes` extraction and Responses conv
93
97
 
94
98
  **Persistence boundary:** `Uint8Array` is only the in-process adapter type. Any bytes placed in persisted result details must be encoded explicitly, for example base64 with the declared encoding. JSON serialization of a typed array is not a supported cache or replay format. SQLite stores the original BLOB. PCC retains its existing serialized opaque-delivery format where possible.
95
99
 
96
- Optional `agentName(ctx)` and `route(query, callId, ctx, signal?)` adapt existing PCC family identity and sharing routes. `route` returns `undefined` for current-agent requests. For another agent it returns the normal routed result, preserving that owner's freshness and delivery semantics. Without this capability, cross-agent targets fail explicitly rather than reading another session by guesswork.
100
+ Optional `agentName(ctx)` and `route(query, callId, ctx, signal?)` adapt existing PCC family identity and sharing routes. `route` returns `undefined` for current-agent requests. For another agent it returns the normal routed result, preserving that owner's freshness and delivery semantics. If routing is absent or unavailable, Notes can read previously shared local notes through persisted family relationships and attachment aliases. It follows recorded local session paths, never a directory scan. Saved identities also preserve agent names without PCC. Authentication, query and cancellation errors do not trigger this fallback. Cross-agent writes and history still require live routing.
97
101
 
98
102
  ## Validation required for the PCC patch
99
103
 
package/README.md CHANGED
@@ -4,7 +4,7 @@ Keep working across fresh context windows with local checkpoint notes, searchabl
4
4
 
5
5
  ## Install
6
6
 
7
- Requires Pi 1.1.0 or newer and Node.js 22.18 or newer.
7
+ Requires Pi 1.2.0 or newer and Node.js 22.18 or newer.
8
8
 
9
9
  ```sh
10
10
  pi install npm:@howaboua/pi-notes-compaction
@@ -18,24 +18,45 @@ With Pi Codex Conversion 3.0.48 or newer, local notes work alongside Codex tools
18
18
 
19
19
  The agent keeps the familiar `notes`, `history`, `new_context` and `get_context_remaining` tools. Notes use virtual paths. Relative paths belong to the current agent. History searches the selected Pi session branch, including earlier windows. It does not create a second transcript archive.
20
20
 
21
+ Previously shared local notes remain readable after the other agent closes or Shepherdr is removed. Notes follows the saved family relationships and attachment aliases without requiring PCC. Reads use the other session's saved branch. When only a retained attachment snapshot is available, the result identifies it as detached or potentially stale. Cross-agent writes and history still require their live routing service.
22
+
21
23
  By default, `new_context` starts a fresh window without generating a summary. The agent receives recent note paths, and Pi's saved history remains available for lookup.
22
24
 
25
+ The tool requires a successful checkpoint write immediately before the request. Direct `notes` writes and writes completed through `exec` or `wait` count. A missing, pending or failed write keeps the current run active and asks the agent to save a note first.
26
+
23
27
  Reminders arrive at 85% and 90% context use. With normal compaction off, `/compact` opens a fresh window immediately if the latest completed turn saved fresh notes. Otherwise it requests a checkpoint first. The new window waits for your next prompt; it does not start a continuation turn. Abort, errors and failed writes retain the old context. Overflow recovery still uses Pi's normal compaction.
24
28
 
25
- Pi rejects `/compact` when there is too little history to prepare compaction, before extensions run. In that case, the agent can still use `new_context`.
29
+ Pi rejects `/compact` when there is too little history to prepare compaction, before extensions run. `new_context` follows the separate **New window requests** setting.
26
30
 
27
- Idle rollover is off by default. Choose 5, 15, 25 or 55 minutes in `/notes`. After that interval, the next input waits for rollover only if the latest completed turn saved fresh notes. Otherwise it proceeds in the current window without requesting a checkpoint. These intervals are user preferences, not provider cache-expiry guarantees. Held input retains its original text, attachments and SDK options. A failed rollover keeps input pending. Submit another prompt to retry, or reload to cancel it.
31
+ Idle rollover is off by default. Choose 5, 15, 25 or 55 minutes in `/notes`. After that interval, the next input waits for rollover only if the latest completed turn saved fresh notes. Otherwise it proceeds in the current window without requesting a checkpoint. These intervals are user preferences, not provider cache-expiry guarantees. Held input retains its original text, attachments and SDK options. If normal compaction has nothing to summarise, input proceeds in the current window. A failed rollover keeps input pending. Submit another prompt to retry, or reload to cancel it.
28
32
 
29
33
  ## Management
30
34
 
31
35
  `/notes` opens the settings panel in interactive Pi. It shows continuity status, storage counts and remote capabilities. Changes save immediately.
32
36
 
37
+ - **Active** selects **All models** (the default) or **Whitelist**. Whitelist enables the extension only for exact model IDs in the global settings file, regardless of provider. Switching models applies the choice immediately; other models keep their installed compaction behaviour.
33
38
  - **Normal compaction** uses the installed Pi or PCC compaction flow for `/compact` and `new_context`. Off keeps notes-only rollover, the default.
39
+ - **New window requests** controls the agent's `new_context` tool independently of the compaction method. **off** disables the tool. **pi-limits** uses Pi's eligibility check and continues in the current window when there is too little history. **unrestricted**, the default, accepts requests at any size. With normal compaction on and nothing to summarise, unrestricted requests open a new window identity without discarding the existing context. Manual `/compact` and idle rollover retain their separate policies.
34
40
  - **Idle rollover** selects the interval or disables it.
35
41
  - **Prune missing sessions** removes records for missing session files after confirmation. Unknown paths, permission errors and the active session are retained.
36
42
 
37
43
  Notes are stored as plaintext in `<Pi agent directory>/notes-compaction/notes.sqlite`, honoring `PI_CODING_AGENT_DIR`. Saved session snapshots preserve notes across forks and branch navigation, including after database pruning. Existing plaintext PCC notes remain readable without an import.
38
44
 
45
+ The whitelist is preseeded in `<Pi agent directory>/notes-compaction/settings.json` (normally `~/.pi/agent/notes-compaction/settings.json`):
46
+
47
+ ```json
48
+ {
49
+ "active": "whitelist",
50
+ "modelWhitelist": ["gpt-6-astra", "gpt-6-sol", "gpt-6-luna", "gpt-6.1-sol"],
51
+ "normalCompaction": false,
52
+ "newWindowRequests": "unrestricted",
53
+ "idleMinutes": 0,
54
+ "taskBoundaryReminder": 0
55
+ }
56
+ ```
57
+
58
+ Add or remove model IDs and reload Pi. Copy the model's exact ID, without Pi's provider selector prefix. If the ID itself contains slashes, keep them. Entries are literal matches, not patterns. A new model is inactive in Whitelist mode until you add its ID.
59
+
39
60
  ## Optional remote lookup
40
61
 
41
62
  With the documented provider bridge, reads and searches automatically combine local notes or JSONL history with remote results. Remote response bytes are cached verbatim in SQLite. Cached lookups can be reused offline, with their original coverage and an explicit exact-query limit. Encrypted listings cannot be searched or expanded locally into queries that were never cached.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-notes-compaction",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -42,7 +42,7 @@
42
42
  "@types/better-sqlite3": "9.6.0"
43
43
  },
44
44
  "peerDependencies": {
45
- "@earendil-works/pi-coding-agent": ">=1.1.0",
45
+ "@earendil-works/pi-coding-agent": ">=1.2.0",
46
46
  "@earendil-works/pi-agent-core": ">=1.0.4",
47
47
  "@earendil-works/pi-ai": ">=1.0.4",
48
48
  "@earendil-works/pi-tui": ">=1.0.4",
package/src/bridge.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type {
3
3
  AgentToolResult,
4
+ CustomMessageEntryDraft,
4
5
  ExtensionAPI,
5
6
  ExtensionContext,
6
7
  SessionBeforeCompactEvent,
@@ -71,6 +72,7 @@ export interface NotesOwner {
71
72
  projectBranch(entries: readonly SessionEntry[]): SessionEntry[];
72
73
  /** Consult before compaction work; the owner's hook performs notes-only rollover. */
73
74
  allowsCompaction?(reason: SessionBeforeCompactEvent["reason"]): boolean;
75
+ allowsWindowRequests?(): boolean;
74
76
  canBind?(ctx: ExtensionContext): boolean;
75
77
  snapshotNotes?(
76
78
  entries: readonly SessionEntry[],
@@ -86,6 +88,8 @@ export interface NotesOwner {
86
88
 
87
89
  export interface NotesBridge {
88
90
  protocol: 1;
91
+ /** Preserve the owner's chronological entry while enabling developer-role delivery. */
92
+ prepareReminder?(entry: CustomMessageEntryDraft): CustomMessageEntryDraft;
89
93
  /** Synchronous atomic handoff. No legacy registrations or lifecycle owners remain active. */
90
94
  claim(owner: NotesOwner):
91
95
  | {
@@ -133,6 +137,10 @@ export interface BridgeRequest {
133
137
  }
134
138
  export interface OwnerRequest {
135
139
  protocol: 1;
140
+ ctx?: ExtensionContext;
141
+ projection?(
142
+ owner: Pick<NotesOwner, "projectMessages" | "projectBranch">,
143
+ ): void;
136
144
  reply(owner: NotesOwner): void;
137
145
  }
138
146
 
@@ -1,8 +1,11 @@
1
+ import type { ToolCall, ToolResultMessage } from "@earendil-works/pi-ai";
1
2
  import {
2
3
  buildSessionProjection,
3
4
  type SessionEntry,
4
5
  } from "@earendil-works/pi-coding-agent";
5
- import { NOTE_RECEIPT, noteReceipt } from "./notes.js";
6
+ import { NOTE_RECEIPT, type NoteReceipt, noteReceipt } from "./notes.js";
7
+
8
+ export const NOTES_RUN_ENTRY = "notes-compaction:run:v1";
6
9
 
7
10
  /** A receipt proves persistence. Current-run tool outcomes prove the checkpoint actually completed. */
8
11
  export function hasFreshNotes(
@@ -10,11 +13,85 @@ export function hasFreshNotes(
10
13
  windowId: string | undefined,
11
14
  runId?: string,
12
15
  ): boolean {
13
- if (!windowId) return false;
16
+ const { messages, receipts } = noteEvidence(branch, windowId, runId);
17
+ const final = messages.findLast((message) => message.role === "assistant");
18
+ if (
19
+ final?.role !== "assistant" ||
20
+ final.stopReason !== "stop" ||
21
+ final.content.some((block) => block.type === "toolCall")
22
+ )
23
+ return false;
24
+ return completedWrites(
25
+ messages.flatMap((message) =>
26
+ message.role === "assistant"
27
+ ? message.content.filter((block) => block.type === "toolCall")
28
+ : [],
29
+ ),
30
+ messages.flatMap((message) =>
31
+ message.role === "toolResult" ? [message] : [],
32
+ ),
33
+ receipts,
34
+ );
35
+ }
36
+
37
+ /** The current request is already in history; only its preceding completed invocation qualifies. */
38
+ export function hasPrecedingNoteWrite(
39
+ branch: readonly SessionEntry[],
40
+ windowId: string | undefined,
41
+ runId: string,
42
+ requestCallId: string,
43
+ ): boolean {
44
+ const { messages, receipts } = noteEvidence(branch, windowId, runId);
45
+ const request = messages.findLastIndex(
46
+ (message) =>
47
+ message.role === "assistant" &&
48
+ message.content.some(
49
+ (block) => block.type === "toolCall" && block.id === requestCallId,
50
+ ),
51
+ );
52
+ if (request < 0) return false;
53
+ const calls = messages
54
+ .slice(0, request + 1)
55
+ .flatMap((message) =>
56
+ message.role === "assistant"
57
+ ? message.content.filter((block) => block.type === "toolCall")
58
+ : [],
59
+ );
60
+ const call =
61
+ calls[calls.findLastIndex((call) => call.id === requestCallId) - 1];
62
+ if (!call) return false;
63
+ const previous = messages.findLast(
64
+ (message) =>
65
+ message.role === "toolResult" &&
66
+ message.toolCallId === call.id &&
67
+ message.toolName === call.name,
68
+ );
69
+ return (
70
+ previous?.role === "toolResult" &&
71
+ completedWrites([call], [previous], receipts)
72
+ );
73
+ }
74
+
75
+ function noteEvidence(
76
+ branch: readonly SessionEntry[],
77
+ windowId: string | undefined,
78
+ runId?: string,
79
+ ) {
14
80
  const lastUser = branch.findLastIndex(
15
81
  (entry) => entry.type === "message" && entry.message.role === "user",
16
82
  );
17
- const run = branch.slice(lastUser + 1);
83
+ // Custom kickoffs have no user message. Scope both receipts and tool outcomes
84
+ // to their native preparation boundary, not an earlier custom-only run.
85
+ const runStart = branch.findLastIndex(
86
+ (entry) =>
87
+ entry.type === "custom" &&
88
+ entry.customType === NOTES_RUN_ENTRY &&
89
+ entry.data &&
90
+ typeof entry.data === "object" &&
91
+ "runId" in entry.data &&
92
+ (!runId || entry.data.runId === runId),
93
+ );
94
+ const run = branch.slice(Math.max(lastUser, runStart) + 1);
18
95
  const receipts = run
19
96
  .filter(
20
97
  (entry) => entry.type === "custom" && entry.customType === NOTE_RECEIPT,
@@ -22,30 +99,24 @@ export function hasFreshNotes(
22
99
  .flatMap((entry) =>
23
100
  entry.type === "custom" ? [noteReceipt(entry.data)] : [],
24
101
  )
25
- .filter(
26
- (receipt) =>
102
+ .filter((receipt): receipt is NoteReceipt =>
103
+ Boolean(
27
104
  receipt &&
28
- receipt.origin !== "routed" &&
29
- receipt.windowId === windowId &&
30
- (!runId || receipt.runId === runId),
105
+ receipt.origin !== "routed" &&
106
+ receipt.windowId === windowId &&
107
+ (!runId || receipt.runId === runId),
108
+ ),
31
109
  );
32
- if (!receipts.length) return false;
33
110
  const messages = buildSessionProjection(run).messages;
34
- const final = messages.findLast((message) => message.role === "assistant");
35
- if (
36
- final?.role !== "assistant" ||
37
- final.stopReason !== "stop" ||
38
- final.content.some((block) => block.type === "toolCall")
39
- )
40
- return false;
41
- const calls = messages.flatMap((message) =>
42
- message.role === "assistant"
43
- ? message.content.filter((block) => block.type === "toolCall")
44
- : [],
45
- );
46
- const results = messages.flatMap((message) =>
47
- message.role === "toolResult" ? [message] : [],
48
- );
111
+ return { messages, receipts };
112
+ }
113
+
114
+ function completedWrites(
115
+ calls: readonly ToolCall[],
116
+ results: readonly ToolResultMessage[],
117
+ receipts: readonly NoteReceipt[],
118
+ ): boolean {
119
+ if (!receipts.length) return false;
49
120
  const writes = calls.filter(
50
121
  (call) =>
51
122
  call.name === "notes" &&
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { join } from "node:path";
2
2
  import {
3
3
  type ExtensionAPI,
4
+ type ExtensionContext,
4
5
  getAgentDir,
5
6
  } from "@earendil-works/pi-coding-agent";
6
7
  import {
@@ -12,7 +13,12 @@ import {
12
13
  } from "./bridge.js";
13
14
  import { NotesLifecycle } from "./lifecycle.js";
14
15
  import { exportNotesSnapshot, sessionRef } from "./notes.js";
15
- import { type NotesSettings, readSettings, writeSettings } from "./settings.js";
16
+ import {
17
+ modelIsActive,
18
+ type NotesSettings,
19
+ readSettings,
20
+ writeSettings,
21
+ } from "./settings.js";
16
22
  import { openNotesSettings } from "./settings-screen.js";
17
23
  import { NotesStore } from "./store.js";
18
24
  import {
@@ -33,6 +39,22 @@ export default function notesCompaction(pi: ExtensionAPI): void {
33
39
  const settingsPath = join(dir, "settings.json");
34
40
  const store = new NotesStore(join(dir, "notes.sqlite"));
35
41
  const lifecycle = new NotesLifecycle(pi, store);
42
+ let settings: NotesSettings;
43
+ let ready = false;
44
+ const stopAdmission = pi.events.on(
45
+ "pi-notes-compaction:custom-turn-admission:v1",
46
+ (value) => {
47
+ const request = value as {
48
+ protocol?: number;
49
+ ctx: Parameters<NotesLifecycle["prepareCustomTurn"]>[0];
50
+ preparation?: Promise<void> | undefined;
51
+ };
52
+ if (request?.protocol === 1 && !request.preparation) {
53
+ refreshActivation(request.ctx);
54
+ request.preparation = lifecycle.prepareCustomTurn(request.ctx);
55
+ }
56
+ },
57
+ );
36
58
  const tools = createTools(pi, store, lifecycle);
37
59
  let ownSource: string | undefined;
38
60
  let unavailable: string | undefined;
@@ -41,9 +63,22 @@ export default function notesCompaction(pi: ExtensionAPI): void {
41
63
  owner: "pi-notes-compaction",
42
64
  identity: () =>
43
65
  lifecycle.windows.current ? { ...lifecycle.windows.current } : undefined,
44
- projectMessages: (messages) => lifecycle.windows.projectMessages(messages),
66
+ projectMessages: (messages) => {
67
+ const projected = lifecycle.windows.projectMessages(
68
+ messages,
69
+ lifecycle.bridge?.prepareReminder,
70
+ );
71
+ return lifecycle.active
72
+ ? projected
73
+ : projected.filter(
74
+ (message) =>
75
+ message.role !== "custom" ||
76
+ !message.customType.startsWith("notes-compaction:"),
77
+ );
78
+ },
45
79
  projectBranch: (entries) => lifecycle.windows.projectBranch(entries),
46
80
  allowsCompaction: (reason) => lifecycle.allowsCompaction(reason),
81
+ allowsWindowRequests: () => lifecycle.newWindowRequests !== "off",
47
82
  canBind: (ctx) =>
48
83
  lifecycle.active &&
49
84
  ctx.isIdle() &&
@@ -54,6 +89,15 @@ export default function notesCompaction(pi: ExtensionAPI): void {
54
89
  entry.customType === "@howaboua/pi-stuff/changelog"
55
90
  )
56
91
  return true;
92
+ // PCC links the fresh worker before binding its shared notes family.
93
+ if (
94
+ entry.type === "custom" &&
95
+ entry.customType === "codex-agent-relationship"
96
+ )
97
+ return (
98
+ (entry.data as { threadId?: unknown } | undefined)?.threadId ===
99
+ ctx.sessionManager.getSessionId()
100
+ );
57
101
  // Herdr activation persists its empty registry before first task delivery.
58
102
  if (
59
103
  entry.type === "custom" &&
@@ -104,17 +148,43 @@ export default function notesCompaction(pi: ExtensionAPI): void {
104
148
  const stopOwner = pi.events.on(OWNER_CHANNEL, (data) => {
105
149
  if (!data || typeof data !== "object") return;
106
150
  const request = data as Partial<OwnerRequest>;
107
- if (request.protocol === 1 && typeof request.reply === "function")
151
+ if (request.protocol === 1 && ready && !unavailable)
152
+ request.projection?.(owner);
153
+ if (
154
+ request.protocol === 1 &&
155
+ typeof request.reply === "function" &&
156
+ ready &&
157
+ !unavailable &&
158
+ (request.ctx
159
+ ? modelIsActive(settings, request.ctx.model)
160
+ : lifecycle.active)
161
+ )
108
162
  request.reply(owner);
109
163
  });
110
164
 
111
- pi.on("session_start", (_event, ctx) => {
112
- lifecycle.reset(ctx);
113
- lifecycle.active = false;
114
- unavailable = undefined;
165
+ function refreshActivation(ctx: ExtensionContext): void {
166
+ if (!ready || unavailable) return;
167
+ const active = modelIsActive(settings, ctx.model);
168
+ if (!active) {
169
+ if (lifecycle.active) lifecycle.reset(ctx);
170
+ lifecycle.active = false;
171
+ if (lifecycle.bridge) {
172
+ // PCC rediscovers ownership before deciding its native policy.
173
+ lifecycle.bridge.configureTools?.(tools, ctx, {
174
+ notes: NOTES_USAGE,
175
+ history: HISTORY_USAGE,
176
+ });
177
+ } else {
178
+ pi.setActiveTools(
179
+ pi
180
+ .getActiveTools()
181
+ .filter((name) => !TOOL_NAMES.some((tool) => tool === name)),
182
+ );
183
+ }
184
+ return;
185
+ }
186
+ if (lifecycle.active) return;
115
187
  try {
116
- Object.assign(lifecycle, readSettings(settingsPath));
117
- lifecycle.bridge = discoverBridge(pi);
118
188
  const claim = lifecycle.bridge?.claim(owner);
119
189
  if (claim && !claim.claimed) throw new Error(claim.reason);
120
190
  if (claim?.claimed) {
@@ -137,23 +207,84 @@ export default function notesCompaction(pi: ExtensionAPI): void {
137
207
  }
138
208
  lifecycle.active = true;
139
209
  lifecycle.initialize(ctx);
140
- lifecycle.bridge?.configureTools?.(tools, ctx, {
210
+ configureTools(ctx);
211
+ store.updateFile(sessionRef(ctx));
212
+ } catch (error) {
213
+ lifecycle.active = false;
214
+ unavailable = error instanceof Error ? error.message : String(error);
215
+ ctx.ui.notify(`Notes continuity inactive: ${unavailable}`, "warning");
216
+ }
217
+ }
218
+ function configureTools(ctx: ExtensionContext): void {
219
+ if (lifecycle.bridge) {
220
+ lifecycle.bridge.configureTools?.(tools, ctx, {
141
221
  notes: NOTES_USAGE,
142
222
  history: HISTORY_USAGE,
143
223
  });
144
- store.updateFile(sessionRef(ctx));
224
+ return;
225
+ }
226
+ const names = TOOL_NAMES.filter(
227
+ (name) => name !== "new_context" || lifecycle.newWindowRequests !== "off",
228
+ );
229
+ pi.setActiveTools([
230
+ ...new Set([
231
+ ...pi
232
+ .getActiveTools()
233
+ .filter((name) => !TOOL_NAMES.some((tool) => tool === name)),
234
+ ...names,
235
+ ]),
236
+ ]);
237
+ }
238
+ function applySettings(value: NotesSettings): void {
239
+ settings = value;
240
+ lifecycle.normalCompaction = value.normalCompaction;
241
+ lifecycle.newWindowRequests = value.newWindowRequests;
242
+ lifecycle.idleMinutes = value.idleMinutes;
243
+ lifecycle.taskBoundaryReminder = value.taskBoundaryReminder;
244
+ }
245
+ pi.on("session_start", (_event, ctx) => {
246
+ lifecycle.reset(ctx);
247
+ lifecycle.active = false;
248
+ ready = false;
249
+ unavailable = undefined;
250
+ try {
251
+ settings = readSettings(settingsPath);
252
+ writeSettings(settingsPath, settings);
253
+ applySettings(settings);
254
+ lifecycle.bridge = discoverBridge(pi);
255
+ ready = true;
256
+ // Register standalone tools even when initially hidden, for later model switches.
257
+ if (!lifecycle.bridge) {
258
+ if (
259
+ pi
260
+ .getAllTools()
261
+ .some(
262
+ (tool) =>
263
+ TOOL_NAMES.some((name) => name === tool.name) &&
264
+ tool.sourceInfo.path !== ownSource,
265
+ )
266
+ )
267
+ throw new Error(
268
+ "Another extension already owns notes continuity. Update it to a version supporting notes integration, then reload Pi.",
269
+ );
270
+ for (const tool of tools) pi.registerTool(tool);
271
+ ownSource = pi.getAllTools().find((tool) => tool.name === "notes")
272
+ ?.sourceInfo.path;
273
+ }
274
+ refreshActivation(ctx);
145
275
  } catch (error) {
146
- lifecycle.active = false;
147
276
  unavailable = error instanceof Error ? error.message : String(error);
148
277
  ctx.ui.notify(`Notes continuity inactive: ${unavailable}`, "warning");
149
278
  }
150
279
  });
151
- pi.on("before_agent_start", (_event, ctx) => {
152
- if (lifecycle.active) lifecycle.beforeStart(ctx);
280
+ pi.on("before_agent_start", (event, ctx) => {
281
+ refreshActivation(ctx);
282
+ if (lifecycle.active) lifecycle.beforeStart(ctx, event);
283
+ });
284
+ pi.on("input", (event, ctx) => {
285
+ refreshActivation(ctx);
286
+ return lifecycle.active ? lifecycle.input(event, ctx) : undefined;
153
287
  });
154
- pi.on("input", (event, ctx) =>
155
- lifecycle.active ? lifecycle.input(event, ctx) : undefined,
156
- );
157
288
  pi.on("agent_before_settle", (event) => {
158
289
  if (lifecycle.active) lifecycle.outcome(event.outcome);
159
290
  });
@@ -168,23 +299,41 @@ export default function notesCompaction(pi: ExtensionAPI): void {
168
299
  );
169
300
  }
170
301
  });
171
- pi.on("turn_end", (_event, ctx) => {
172
- if (!lifecycle.active || lifecycle.fresh(ctx, lifecycle.runId)) return;
173
- const reminder = lifecycle.windows.reminder(ctx);
174
- return reminder ? { entries: [reminder] } : undefined;
302
+ pi.on("turn_end", (event, ctx) => {
303
+ if (!lifecycle.active || lifecycle.newWindowRequests === "off") return;
304
+ const reminder = lifecycle.windows.reminder(
305
+ ctx,
306
+ event.message.role === "assistant" &&
307
+ !ctx.signal?.aborted &&
308
+ !["error", "length", "aborted"].includes(event.message.stopReason) &&
309
+ event.toolResults.length > 0 &&
310
+ pi.getActiveTools().includes("new_context")
311
+ ? lifecycle.taskBoundaryReminder
312
+ : 0,
313
+ !lifecycle.fresh(ctx, lifecycle.runId),
314
+ );
315
+ return reminder
316
+ ? {
317
+ entries: [
318
+ ...event.entries,
319
+ windowDetails(reminder)?.kind === "task-boundary"
320
+ ? (lifecycle.bridge?.prepareReminder?.(reminder) ?? reminder)
321
+ : reminder,
322
+ ],
323
+ }
324
+ : undefined;
175
325
  });
176
326
  pi.on("context", (event, ctx) => {
177
- if (!lifecycle.active) return;
178
327
  try {
179
328
  lifecycle.windows.restore(ctx.sessionManager.getBranch());
180
- return { messages: lifecycle.windows.projectMessages(event.messages) };
329
+ return { messages: owner.projectMessages(event.messages) };
181
330
  } catch (error) {
182
331
  ctx.abort();
183
332
  throw error;
184
333
  }
185
334
  });
186
335
  pi.on("session_before_compact", (event, ctx) =>
187
- lifecycle.active ? lifecycle.beforeCompact(event, ctx) : undefined,
336
+ ready && !unavailable ? lifecycle.beforeCompact(event, ctx) : undefined,
188
337
  );
189
338
  pi.on("session_compact_failed", async (event, ctx) => {
190
339
  if (lifecycle.active) await lifecycle.compactFailed(event, ctx);
@@ -198,6 +347,7 @@ export default function notesCompaction(pi: ExtensionAPI): void {
198
347
  if (lifecycle.active) lifecycle.initialize(ctx);
199
348
  });
200
349
  pi.on("model_select", (_event, ctx) => {
350
+ refreshActivation(ctx);
201
351
  if (lifecycle.active)
202
352
  lifecycle.bridge?.configureTools?.(tools, ctx, {
203
353
  notes: NOTES_USAGE,
@@ -209,6 +359,7 @@ export default function notesCompaction(pi: ExtensionAPI): void {
209
359
  lifecycle.active = false;
210
360
  store.close();
211
361
  stopOwner();
362
+ stopAdmission();
212
363
  });
213
364
 
214
365
  pi.registerCommand("notes", {
@@ -222,9 +373,11 @@ export default function notesCompaction(pi: ExtensionAPI): void {
222
373
  ctx.ui.notify("Notes settings require interactive Pi.", "warning");
223
374
  return;
224
375
  }
225
- const save = (settings: NotesSettings) => {
226
- writeSettings(settingsPath, settings);
227
- Object.assign(lifecycle, settings);
376
+ const save = (value: NotesSettings) => {
377
+ writeSettings(settingsPath, value);
378
+ applySettings(value);
379
+ refreshActivation(ctx);
380
+ if (lifecycle.active) configureTools(ctx);
228
381
  };
229
382
  const prune = async () => {
230
383
  await ctx.waitForIdle();
@@ -237,18 +390,16 @@ export default function notesCompaction(pi: ExtensionAPI): void {
237
390
  };
238
391
  try {
239
392
  await openNotesSettings(ctx, {
240
- settings: () => ({
241
- normalCompaction: lifecycle.normalCompaction,
242
- idleMinutes: lifecycle.idleMinutes,
243
- }),
393
+ settings: () => settings,
244
394
  save,
395
+ settingsPath,
245
396
  prune,
246
397
  status: () => {
247
398
  const counts = store.status();
248
399
  return [
249
400
  lifecycle.active
250
401
  ? "Continuity active"
251
- : `Continuity inactive: ${unavailable ?? "not initialized"}`,
402
+ : `Continuity inactive: ${unavailable ?? (ready ? "model not in whitelist" : "not initialized")}`,
252
403
  `${counts.sessions} sessions · ${counts.revisions} note revisions · ${counts.cachedResponses} cached responses`,
253
404
  `Hybrid lookup: ${lifecycle.bridge?.lookup ? "available" : "unavailable"} · Encrypted delivery: ${lifecycle.bridge?.projectResult ? "available" : "unavailable"}`,
254
405
  ];