@howaboua/pi-notes-compaction 0.0.5 → 0.0.7
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 +14 -0
- package/PCC-INTEGRATION.md +7 -3
- package/README.md +24 -3
- package/package.json +2 -2
- package/src/bridge.ts +5 -0
- package/src/fresh-notes.ts +95 -24
- package/src/index.ts +151 -30
- package/src/lifecycle.ts +146 -38
- package/src/notes.ts +10 -1
- package/src/saved-session.ts +131 -0
- package/src/settings-screen.ts +55 -13
- package/src/settings.ts +55 -0
- package/src/shared-notes.ts +421 -0
- package/src/task-boundary.ts +1 -1
- package/src/tools.ts +69 -26
- package/src/windows.ts +92 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @howaboua/pi-notes-compaction
|
|
2
2
|
|
|
3
|
+
## 0.0.7
|
|
4
|
+
|
|
5
|
+
- Shared local agent history now remains readable after its owner closes or Shepherdr is removed.
|
|
6
|
+
|
|
7
|
+
## 0.0.6
|
|
8
|
+
|
|
9
|
+
- Requires Pi 1.2.0 or newer.
|
|
10
|
+
|
|
11
|
+
- Added per-model activation through `/notes` and an editable whitelist.
|
|
12
|
+
- Added **New window requests: off | pi-limits | unrestricted**. `new_context` requires a successful note write immediately beforehand.
|
|
13
|
+
- Shared local notes now remain readable after their owner closes or Shepherdr is removed.
|
|
14
|
+
- Fixed window identity and recovery guidance disappearing after compaction.
|
|
15
|
+
- Continuations now apply Pi's full prompt and tool preparation.
|
|
16
|
+
|
|
3
17
|
## 0.0.5
|
|
4
18
|
|
|
5
19
|
- 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).
|
package/PCC-INTEGRATION.md
CHANGED
|
@@ -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.
|
|
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
|
|
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.
|
|
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.
|
|
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 and history 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 and preserve its history IDs. When only a retained attachment snapshot is available, notes identify it as detached or potentially stale. Snapshots do not contain history. Cross-agent writes still require their live routing service. Saved history reads do not fetch or decrypt remote history.
|
|
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.
|
|
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.
|
|
3
|
+
"version": "0.0.7",
|
|
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.
|
|
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
|
@@ -72,6 +72,7 @@ export interface NotesOwner {
|
|
|
72
72
|
projectBranch(entries: readonly SessionEntry[]): SessionEntry[];
|
|
73
73
|
/** Consult before compaction work; the owner's hook performs notes-only rollover. */
|
|
74
74
|
allowsCompaction?(reason: SessionBeforeCompactEvent["reason"]): boolean;
|
|
75
|
+
allowsWindowRequests?(): boolean;
|
|
75
76
|
canBind?(ctx: ExtensionContext): boolean;
|
|
76
77
|
snapshotNotes?(
|
|
77
78
|
entries: readonly SessionEntry[],
|
|
@@ -136,6 +137,10 @@ export interface BridgeRequest {
|
|
|
136
137
|
}
|
|
137
138
|
export interface OwnerRequest {
|
|
138
139
|
protocol: 1;
|
|
140
|
+
ctx?: ExtensionContext;
|
|
141
|
+
projection?(
|
|
142
|
+
owner: Pick<NotesOwner, "projectMessages" | "projectBranch">,
|
|
143
|
+
): void;
|
|
139
144
|
reply(owner: NotesOwner): void;
|
|
140
145
|
}
|
|
141
146
|
|
package/src/fresh-notes.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
(
|
|
102
|
+
.filter((receipt): receipt is NoteReceipt =>
|
|
103
|
+
Boolean(
|
|
27
104
|
receipt &&
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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 {
|
|
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) =>
|
|
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() &&
|
|
@@ -113,17 +148,43 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
113
148
|
const stopOwner = pi.events.on(OWNER_CHANNEL, (data) => {
|
|
114
149
|
if (!data || typeof data !== "object") return;
|
|
115
150
|
const request = data as Partial<OwnerRequest>;
|
|
116
|
-
if (request.protocol === 1 &&
|
|
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
|
+
)
|
|
117
162
|
request.reply(owner);
|
|
118
163
|
});
|
|
119
164
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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;
|
|
124
187
|
try {
|
|
125
|
-
Object.assign(lifecycle, readSettings(settingsPath));
|
|
126
|
-
lifecycle.bridge = discoverBridge(pi);
|
|
127
188
|
const claim = lifecycle.bridge?.claim(owner);
|
|
128
189
|
if (claim && !claim.claimed) throw new Error(claim.reason);
|
|
129
190
|
if (claim?.claimed) {
|
|
@@ -146,23 +207,84 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
146
207
|
}
|
|
147
208
|
lifecycle.active = true;
|
|
148
209
|
lifecycle.initialize(ctx);
|
|
149
|
-
|
|
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, {
|
|
150
221
|
notes: NOTES_USAGE,
|
|
151
222
|
history: HISTORY_USAGE,
|
|
152
223
|
});
|
|
153
|
-
|
|
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);
|
|
154
275
|
} catch (error) {
|
|
155
|
-
lifecycle.active = false;
|
|
156
276
|
unavailable = error instanceof Error ? error.message : String(error);
|
|
157
277
|
ctx.ui.notify(`Notes continuity inactive: ${unavailable}`, "warning");
|
|
158
278
|
}
|
|
159
279
|
});
|
|
160
|
-
pi.on("before_agent_start", (
|
|
161
|
-
|
|
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;
|
|
162
287
|
});
|
|
163
|
-
pi.on("input", (event, ctx) =>
|
|
164
|
-
lifecycle.active ? lifecycle.input(event, ctx) : undefined,
|
|
165
|
-
);
|
|
166
288
|
pi.on("agent_before_settle", (event) => {
|
|
167
289
|
if (lifecycle.active) lifecycle.outcome(event.outcome);
|
|
168
290
|
});
|
|
@@ -178,7 +300,7 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
178
300
|
}
|
|
179
301
|
});
|
|
180
302
|
pi.on("turn_end", (event, ctx) => {
|
|
181
|
-
if (!lifecycle.active) return;
|
|
303
|
+
if (!lifecycle.active || lifecycle.newWindowRequests === "off") return;
|
|
182
304
|
const reminder = lifecycle.windows.reminder(
|
|
183
305
|
ctx,
|
|
184
306
|
event.message.role === "assistant" &&
|
|
@@ -202,17 +324,16 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
202
324
|
: undefined;
|
|
203
325
|
});
|
|
204
326
|
pi.on("context", (event, ctx) => {
|
|
205
|
-
if (!lifecycle.active) return;
|
|
206
327
|
try {
|
|
207
328
|
lifecycle.windows.restore(ctx.sessionManager.getBranch());
|
|
208
|
-
return { messages:
|
|
329
|
+
return { messages: owner.projectMessages(event.messages) };
|
|
209
330
|
} catch (error) {
|
|
210
331
|
ctx.abort();
|
|
211
332
|
throw error;
|
|
212
333
|
}
|
|
213
334
|
});
|
|
214
335
|
pi.on("session_before_compact", (event, ctx) =>
|
|
215
|
-
|
|
336
|
+
ready && !unavailable ? lifecycle.beforeCompact(event, ctx) : undefined,
|
|
216
337
|
);
|
|
217
338
|
pi.on("session_compact_failed", async (event, ctx) => {
|
|
218
339
|
if (lifecycle.active) await lifecycle.compactFailed(event, ctx);
|
|
@@ -226,6 +347,7 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
226
347
|
if (lifecycle.active) lifecycle.initialize(ctx);
|
|
227
348
|
});
|
|
228
349
|
pi.on("model_select", (_event, ctx) => {
|
|
350
|
+
refreshActivation(ctx);
|
|
229
351
|
if (lifecycle.active)
|
|
230
352
|
lifecycle.bridge?.configureTools?.(tools, ctx, {
|
|
231
353
|
notes: NOTES_USAGE,
|
|
@@ -237,6 +359,7 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
237
359
|
lifecycle.active = false;
|
|
238
360
|
store.close();
|
|
239
361
|
stopOwner();
|
|
362
|
+
stopAdmission();
|
|
240
363
|
});
|
|
241
364
|
|
|
242
365
|
pi.registerCommand("notes", {
|
|
@@ -250,9 +373,11 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
250
373
|
ctx.ui.notify("Notes settings require interactive Pi.", "warning");
|
|
251
374
|
return;
|
|
252
375
|
}
|
|
253
|
-
const save = (
|
|
254
|
-
writeSettings(settingsPath,
|
|
255
|
-
|
|
376
|
+
const save = (value: NotesSettings) => {
|
|
377
|
+
writeSettings(settingsPath, value);
|
|
378
|
+
applySettings(value);
|
|
379
|
+
refreshActivation(ctx);
|
|
380
|
+
if (lifecycle.active) configureTools(ctx);
|
|
256
381
|
};
|
|
257
382
|
const prune = async () => {
|
|
258
383
|
await ctx.waitForIdle();
|
|
@@ -265,11 +390,7 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
265
390
|
};
|
|
266
391
|
try {
|
|
267
392
|
await openNotesSettings(ctx, {
|
|
268
|
-
settings: () =>
|
|
269
|
-
normalCompaction: lifecycle.normalCompaction,
|
|
270
|
-
idleMinutes: lifecycle.idleMinutes,
|
|
271
|
-
taskBoundaryReminder: lifecycle.taskBoundaryReminder,
|
|
272
|
-
}),
|
|
393
|
+
settings: () => settings,
|
|
273
394
|
save,
|
|
274
395
|
settingsPath,
|
|
275
396
|
prune,
|
|
@@ -278,7 +399,7 @@ export default function notesCompaction(pi: ExtensionAPI): void {
|
|
|
278
399
|
return [
|
|
279
400
|
lifecycle.active
|
|
280
401
|
? "Continuity active"
|
|
281
|
-
: `Continuity inactive: ${unavailable ?? "not initialized"}`,
|
|
402
|
+
: `Continuity inactive: ${unavailable ?? (ready ? "model not in whitelist" : "not initialized")}`,
|
|
282
403
|
`${counts.sessions} sessions · ${counts.revisions} note revisions · ${counts.cachedResponses} cached responses`,
|
|
283
404
|
`Hybrid lookup: ${lifecycle.bridge?.lookup ? "available" : "unavailable"} · Encrypted delivery: ${lifecycle.bridge?.projectResult ? "available" : "unavailable"}`,
|
|
284
405
|
];
|