@howaboua/pi-notes-compaction 0.0.9 → 0.0.10

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +23 -5
  2. package/PCC-INTEGRATION.md +7 -98
  3. package/README.md +21 -13
  4. package/package.json +7 -3
  5. package/src/activation.ts +152 -0
  6. package/src/agent-identity.ts +119 -0
  7. package/src/attachment-snapshot.ts +103 -0
  8. package/src/binding-startup.ts +30 -0
  9. package/src/bridge.ts +1 -43
  10. package/src/compaction-projection.ts +88 -0
  11. package/src/context-owner.ts +103 -0
  12. package/src/context-sharing.ts +144 -0
  13. package/src/extension-hooks.ts +198 -0
  14. package/src/extension-sharing.ts +118 -0
  15. package/src/fresh-checkpoint.ts +117 -0
  16. package/src/fresh-notes.ts +141 -26
  17. package/src/history-search-protocol.ts +39 -0
  18. package/src/history-search-pruning.mjs +120 -0
  19. package/src/history-search-worker.mjs +256 -0
  20. package/src/history-search.ts +269 -0
  21. package/src/history.ts +212 -40
  22. package/src/idle-admission.ts +201 -0
  23. package/src/index.ts +71 -401
  24. package/src/integrations.ts +159 -0
  25. package/src/lifecycle.ts +63 -448
  26. package/src/note-save-marker.ts +112 -0
  27. package/src/notes-lookup.ts +112 -0
  28. package/src/notes.ts +24 -28
  29. package/src/query-executor.ts +190 -0
  30. package/src/remote.ts +357 -0
  31. package/src/rollover.ts +212 -0
  32. package/src/saved-session.ts +44 -7
  33. package/src/session-pruning-content.ts +237 -0
  34. package/src/session-pruning-plan.ts +243 -0
  35. package/src/session-pruning-policy.ts +20 -0
  36. package/src/session-pruning-screen.ts +130 -0
  37. package/src/session-pruning-source.ts +44 -0
  38. package/src/session-pruning-transaction.ts +141 -0
  39. package/src/session-pruning.ts +142 -0
  40. package/src/settings-command.ts +77 -0
  41. package/src/settings-screen.ts +84 -19
  42. package/src/settings.ts +143 -11
  43. package/src/shared-notes.ts +37 -14
  44. package/src/sharing-service.ts +348 -0
  45. package/src/store.ts +31 -0
  46. package/src/task-boundary.ts +6 -1
  47. package/src/tool-contracts.ts +279 -0
  48. package/src/tools.ts +19 -560
  49. package/src/tree-archive.ts +149 -0
  50. package/src/tree-checkpoint.ts +170 -0
  51. package/src/tree-handoff-read.ts +192 -0
  52. package/src/window-checkpoint.ts +105 -0
  53. package/src/windows.ts +25 -9
@@ -0,0 +1,103 @@
1
+ import { Type } from "typebox";
2
+ import { Check } from "typebox/value";
3
+ import type { RemoteNoteReference } from "./context-sharing.js";
4
+ import { normalizeNoteParams, readNotes } from "./notes.js";
5
+ import type { NoteRevision } from "./store.js";
6
+
7
+ const Snapshot = Type.Object({
8
+ protocol: Type.Literal(1),
9
+ timestamp: Type.Number({ minimum: 0 }),
10
+ files: Type.Array(
11
+ Type.Object({
12
+ path: Type.String(),
13
+ text: Type.String(),
14
+ createdAt: Type.Number(),
15
+ updatedAt: Type.Number(),
16
+ operation: Type.Optional(
17
+ Type.Union([
18
+ Type.Literal("local_append_overlay"),
19
+ Type.Literal("local_replacement"),
20
+ ]),
21
+ ),
22
+ }),
23
+ ),
24
+ });
25
+
26
+ /** Retained checkpoints remain readable without a running owner or database. */
27
+ export function readAttachmentSnapshot(
28
+ snapshot: unknown,
29
+ params: Record<string, unknown>,
30
+ ): Record<string, unknown> {
31
+ if (!Check(Snapshot, snapshot))
32
+ throw new Error("Invalid retained note snapshot");
33
+ if (
34
+ !["list_files_by_prefix", "read_file", "search_contents"].includes(
35
+ String(params["action"]),
36
+ )
37
+ )
38
+ throw new Error(
39
+ "Retained checkpoints are read-only; resume the attached owner to write notes",
40
+ );
41
+ const path = params["path"] ?? params["prefix"] ?? params["path_prefix"];
42
+ const agent =
43
+ typeof path === "string"
44
+ ? (/^(\/root(?:\/[a-zA-Z0-9_-]+)*?)\/notes(?:\/|$)/.exec(path)?.[1] ??
45
+ "/root")
46
+ : "/root";
47
+ const notes = new Map<string, NoteRevision>();
48
+ for (const file of snapshot.files) {
49
+ if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*?\/notes\/.+/.test(file.path))
50
+ throw new Error("Invalid retained note path");
51
+ if (!file.path.startsWith(`${agent}/notes/`)) continue;
52
+ const local = file.path.slice(`${agent}/notes/`.length);
53
+ notes.set(local, {
54
+ ...file,
55
+ path: local,
56
+ id: file.path,
57
+ mode: file.operation === "local_append_overlay" ? "append" : "replace",
58
+ });
59
+ }
60
+ return readNotes(notes, normalizeNoteParams(params, agent), agent);
61
+ }
62
+
63
+ export function readRemoteNoteReference(input: unknown): RemoteNoteReference {
64
+ if (
65
+ !input ||
66
+ typeof input !== "object" ||
67
+ !("protocol" in input) ||
68
+ input.protocol !== 1 ||
69
+ !("storage" in input) ||
70
+ input.storage !== "remote" ||
71
+ !("timestamp" in input) ||
72
+ typeof input.timestamp !== "number" ||
73
+ !Number.isFinite(input.timestamp) ||
74
+ input.timestamp < 0 ||
75
+ !("baseUrl" in input) ||
76
+ typeof input.baseUrl !== "string" ||
77
+ !input.baseUrl ||
78
+ input.baseUrl.length > 8192 ||
79
+ !("identity" in input) ||
80
+ !input.identity ||
81
+ typeof input.identity !== "object"
82
+ )
83
+ throw new Error("Invalid Remote checkpoint reference");
84
+ const identity = input.identity as Partial<RemoteNoteReference["identity"]>;
85
+ if (
86
+ identity.protocol !== 1 ||
87
+ identity.storage !== "remote" ||
88
+ typeof identity.threadId !== "string" ||
89
+ !identity.threadId ||
90
+ identity.threadId.length > 512 ||
91
+ typeof identity.sessionId !== "string" ||
92
+ !identity.sessionId ||
93
+ identity.sessionId.length > 512 ||
94
+ typeof identity.agentName !== "string" ||
95
+ identity.agentName.length > 4096 ||
96
+ !/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(identity.agentName) ||
97
+ typeof identity.accountScope !== "string" ||
98
+ !/^[a-f0-9]{64}$/.test(identity.accountScope) ||
99
+ identity.backendUrl !== input.baseUrl
100
+ )
101
+ throw new Error("Invalid Remote checkpoint identity");
102
+ return input as RemoteNoteReference;
103
+ }
@@ -0,0 +1,30 @@
1
+ import type {
2
+ ExtensionContext,
3
+ SessionEntry,
4
+ } from "@earendil-works/pi-coding-agent";
5
+
6
+ export interface ContextFamilyBindingOptions {
7
+ /** Caller asserts entries through this boundary were inherited by a new native fork, before child work. */
8
+ fork?: { lastInheritedEntryId: string };
9
+ }
10
+
11
+ /** Classify only child-owned startup records, without modifying inherited history. */
12
+ export function bindingStartupEntries(
13
+ ctx: ExtensionContext,
14
+ options?: ContextFamilyBindingOptions,
15
+ ): SessionEntry[] {
16
+ const entries = ctx.sessionManager.getEntries();
17
+ if (!options?.fork) return entries;
18
+ const id = options.fork.lastInheritedEntryId;
19
+ const boundary = entries.findIndex((entry) => entry.id === id);
20
+ if (
21
+ !ctx.sessionManager.getHeader()?.parentSession ||
22
+ typeof id !== "string" ||
23
+ !id ||
24
+ boundary < 0
25
+ )
26
+ throw new Error(
27
+ "Fork family binding requires an inherited entry boundary in a new native fork",
28
+ );
29
+ return entries.slice(boundary + 1);
30
+ }
package/src/bridge.ts CHANGED
@@ -2,14 +2,10 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type {
3
3
  AgentToolResult,
4
4
  CustomMessageEntryDraft,
5
- ExtensionAPI,
6
5
  ExtensionContext,
7
- SessionBeforeCompactEvent,
8
6
  SessionEntry,
9
- ToolDefinition,
10
7
  } from "@earendil-works/pi-coding-agent";
11
8
 
12
- export const BRIDGE_CHANNEL = "pi-notes-compaction:bridge:v1";
13
9
  export const OWNER_CHANNEL = "pi-notes-compaction:owner:v1";
14
10
  export const TOOL_NAMES = [
15
11
  "notes",
@@ -74,9 +70,6 @@ export interface NotesOwner {
74
70
  entries?: readonly SessionEntry[],
75
71
  ): AgentMessage[];
76
72
  projectBranch(entries: readonly SessionEntry[]): SessionEntry[];
77
- /** Consult before compaction work; the owner's hook performs notes-only rollover. */
78
- allowsCompaction?(reason: SessionBeforeCompactEvent["reason"]): boolean;
79
- allowsWindowRequests?(): boolean;
80
73
  canBind?(ctx: ExtensionContext, entries?: readonly SessionEntry[]): boolean;
81
74
  snapshotNotes?(
82
75
  entries: readonly SessionEntry[],
@@ -94,23 +87,6 @@ export interface NotesBridge {
94
87
  protocol: 1;
95
88
  /** Preserve the owner's chronological entry while enabling developer-role delivery. */
96
89
  prepareReminder?(entry: CustomMessageEntryDraft): CustomMessageEntryDraft;
97
- /** Synchronous atomic handoff. No legacy registrations or lifecycle owners remain active. */
98
- claim(owner: NotesOwner):
99
- | {
100
- claimed: true;
101
- registerTools(
102
- tools: readonly ToolDefinition[],
103
- ctx: ExtensionContext,
104
- ): void;
105
- }
106
- | { claimed: false; reason: string };
107
- /** Configures PCC nested registrations, visibility and opaque-result capture. Never nests new_context. */
108
- configureTools?(
109
- tools: readonly ToolDefinition[],
110
- ctx: ExtensionContext,
111
- contracts: Readonly<Record<"notes" | "history", string>>,
112
- ): void;
113
- beforeWindow?(ctx: ExtensionContext, signal?: AbortSignal): Promise<void>;
114
90
  lookup?(
115
91
  query: LookupQuery,
116
92
  ctx: ExtensionContext,
@@ -124,6 +100,7 @@ export interface NotesBridge {
124
100
  callId: string,
125
101
  ctx: ExtensionContext,
126
102
  signal?: AbortSignal,
103
+ relay?: boolean,
127
104
  ): Promise<AgentToolResult<unknown>>;
128
105
  agentName?(ctx: ExtensionContext): string;
129
106
  /** Optional family routing. undefined means this agent owns the requested path. */
@@ -135,10 +112,6 @@ export interface NotesBridge {
135
112
  ): Promise<AgentToolResult<unknown> | undefined>;
136
113
  }
137
114
 
138
- export interface BridgeRequest {
139
- protocol: 1;
140
- reply(bridge: NotesBridge): void;
141
- }
142
115
  export interface OwnerRequest {
143
116
  protocol: 1;
144
117
  ctx?: ExtensionContext;
@@ -148,21 +121,6 @@ export interface OwnerRequest {
148
121
  reply(owner: NotesOwner): void;
149
122
  }
150
123
 
151
- export function discoverBridge(pi: ExtensionAPI): NotesBridge | undefined {
152
- let found: NotesBridge | undefined;
153
- pi.events.emit(BRIDGE_CHANNEL, {
154
- protocol: 1,
155
- reply(bridge: NotesBridge) {
156
- if (bridge?.protocol !== 1 || typeof bridge.claim !== "function")
157
- throw new Error("Unsupported notes bridge");
158
- if (found && found !== bridge)
159
- throw new Error("Multiple notes bridges responded");
160
- found = bridge;
161
- },
162
- } satisfies BridgeRequest);
163
- return found;
164
- }
165
-
166
124
  export function queryKey(query: LookupQuery): string {
167
125
  return JSON.stringify([
168
126
  query.namespace,
@@ -0,0 +1,88 @@
1
+ import type {
2
+ ExtensionContext,
3
+ SessionBeforeCompactEvent,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ buildSessionProjection,
7
+ prepareBranchEntries,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { projectTreeCheckpointBranch } from "./tree-checkpoint.js";
10
+ import { projectTreeHandoffBranch } from "./tree-handoff-read.js";
11
+ import type { Windows } from "./windows.js";
12
+
13
+ export function prepareCompactionProjection(
14
+ event: SessionBeforeCompactEvent,
15
+ ctx: ExtensionContext,
16
+ windows: Windows,
17
+ ): { cancel: true } | undefined {
18
+ try {
19
+ const branch = projectTreeHandoffBranch(
20
+ windows.projectBranch(
21
+ projectTreeCheckpointBranch(
22
+ event.branchEntries,
23
+ ctx.sessionManager.getEntries(),
24
+ ),
25
+ ),
26
+ );
27
+ if (
28
+ branch.length === event.branchEntries.length &&
29
+ branch.every((entry, index) => entry === event.branchEntries[index])
30
+ )
31
+ return;
32
+ const physicalCut = event.branchEntries.findIndex(
33
+ (entry) => entry.id === event.preparation.firstKeptEntryId,
34
+ );
35
+ if (physicalCut < 0) throw new Error("Compaction kept boundary is missing");
36
+ const keptIds = new Set(
37
+ event.branchEntries.slice(physicalCut).map((entry) => entry.id),
38
+ );
39
+ const projection = buildSessionProjection([...branch]);
40
+ const projected = projection.entries;
41
+ const summary = projection.messages.find(
42
+ (message) => message.role === "compactionSummary",
43
+ );
44
+ const cut = projected.findIndex((entry) =>
45
+ keptIds.has(entry.sourceEntry.id),
46
+ );
47
+ if (cut < 0) throw new Error("Current context kept boundary is missing");
48
+ const summarized = projected.slice(0, cut);
49
+ const messages = summarized
50
+ .flatMap((entry) => entry.messages)
51
+ .filter(
52
+ (message) =>
53
+ message.role !== "system" && message.role !== "compactionSummary",
54
+ );
55
+ if (!messages.length) {
56
+ ctx.ui.notify(
57
+ "Nothing to compact in the current context window. The existing context remains.",
58
+ "warning",
59
+ );
60
+ return { cancel: true };
61
+ }
62
+ event.branchEntries = [...branch];
63
+ // Pi retains this object for its default summarizer after every hook.
64
+ // Keep that route's auth, provider hooks and retries, and physical kept IDs.
65
+ delete event.preparation.previousSummary;
66
+ Object.assign(event.preparation, {
67
+ ...(summary ? { previousSummary: summary.summary } : {}),
68
+ messagesToSummarize: messages,
69
+ turnPrefixMessages: [],
70
+ isSplitTurn: false,
71
+ fileOps: prepareBranchEntries(
72
+ summarized.flatMap((entry) =>
73
+ entry.messages.map((message) => ({
74
+ ...entry.sourceEntry,
75
+ type: "message" as const,
76
+ message,
77
+ })),
78
+ ),
79
+ ).fileOps,
80
+ });
81
+ } catch (error) {
82
+ ctx.ui.notify(
83
+ `Compaction failed: ${error instanceof Error ? error.message : String(error)}. The existing context remains.`,
84
+ "error",
85
+ );
86
+ return { cancel: true };
87
+ }
88
+ }
@@ -0,0 +1,103 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { NotesOwner } from "./bridge.js";
3
+ import type { HistorySearch } from "./history-search.js";
4
+ import type { NotesLifecycle } from "./lifecycle.js";
5
+ import { exportNotesSnapshot } from "./notes.js";
6
+ import type { NotesStore } from "./store.js";
7
+ import { createSharedExecutor } from "./tools.js";
8
+ import { WINDOW_MESSAGE, windowDetails } from "./windows.js";
9
+
10
+ export function createNotesContextOwner(
11
+ pi: ExtensionAPI,
12
+ store: NotesStore,
13
+ lifecycle: NotesLifecycle,
14
+ search: HistorySearch,
15
+ ): NotesOwner {
16
+ const owner: NotesOwner = {
17
+ protocol: 1,
18
+ owner: "pi-notes-compaction",
19
+ identity: () =>
20
+ lifecycle.windows.current ? { ...lifecycle.windows.current } : undefined,
21
+ projectMessages: (messages, entries) => {
22
+ if (entries) lifecycle.windows.restore(entries);
23
+ const projected = lifecycle.windows.projectMessages(
24
+ messages,
25
+ lifecycle.prepareReminder,
26
+ );
27
+ return lifecycle.active
28
+ ? projected
29
+ : projected.filter(
30
+ (message) =>
31
+ message.role !== "custom" ||
32
+ !message.customType.startsWith("notes-compaction:"),
33
+ );
34
+ },
35
+ projectBranch: (entries) => lifecycle.windows.projectBranch(entries),
36
+ canBind: (ctx, entries = ctx.sessionManager.getEntries()) =>
37
+ lifecycle.active &&
38
+ ctx.isIdle() &&
39
+ entries.every((entry) => {
40
+ // The first startup after an update records a UI-only changelog.
41
+ if (
42
+ entry.type === "custom" &&
43
+ entry.customType === "@howaboua/pi-stuff/changelog"
44
+ )
45
+ return true;
46
+ // PCC links the fresh worker before binding its shared notes family.
47
+ if (
48
+ entry.type === "custom" &&
49
+ entry.customType === "codex-agent-relationship"
50
+ )
51
+ return (
52
+ (entry.data as { threadId?: unknown } | undefined)?.threadId ===
53
+ ctx.sessionManager.getSessionId()
54
+ );
55
+ // Herdr activation persists its empty registry before first task delivery.
56
+ if (
57
+ entry.type === "custom" &&
58
+ entry.customType === "herdr-agents-monitor-state"
59
+ ) {
60
+ const data = entry.data as
61
+ | { version?: unknown; agents?: unknown }
62
+ | undefined;
63
+ return Boolean(
64
+ data?.version === 2 &&
65
+ Array.isArray(data.agents) &&
66
+ data.agents.length === 0,
67
+ );
68
+ }
69
+ // Board adoption precedes context binding on a fresh spawn. These
70
+ // metadata records are preparation, not evidence of a first turn.
71
+ if (
72
+ entry.type === "custom" &&
73
+ [
74
+ "shepherdr-board-binding",
75
+ "shepherdr-board-awareness",
76
+ "codex-context-briefing",
77
+ ].includes(entry.customType)
78
+ )
79
+ return true;
80
+ if (
81
+ ["model_change", "thinking_level_change", "session_info"].includes(
82
+ entry.type,
83
+ )
84
+ )
85
+ return true;
86
+ if (
87
+ entry.type !== "custom_message" ||
88
+ entry.customType !== WINDOW_MESSAGE
89
+ )
90
+ return false;
91
+ const details = windowDetails(entry);
92
+ return Boolean(
93
+ details &&
94
+ details.identity.windowNumber === 0 &&
95
+ !details.trim &&
96
+ (details.kind === "window" || details.kind === "identity"),
97
+ );
98
+ }),
99
+ snapshotNotes: exportNotesSnapshot,
100
+ executeShared: createSharedExecutor(pi, store, lifecycle, search),
101
+ };
102
+ return owner;
103
+ }
@@ -0,0 +1,144 @@
1
+ import type {
2
+ AgentToolResult,
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import type {
7
+ ContextAgentBinding,
8
+ ContextAgentIdentity,
9
+ } from "./agent-identity.js";
10
+ import type { NoteSnapshotData, SerializedCachedResponse } from "./bridge.js";
11
+
12
+ export type {
13
+ ContextAgentBinding,
14
+ ContextAgentIdentity,
15
+ } from "./agent-identity.js";
16
+ export type { ContextFamilyBindingOptions } from "./binding-startup.js";
17
+ export type { NoteSnapshotData } from "./bridge.js";
18
+
19
+ export interface SharedContextRequest {
20
+ sessionId: string;
21
+ agentName: string;
22
+ namespace: "history" | "notes";
23
+ params: Record<string, unknown>;
24
+ /** Legacy encrypted arguments are rejected by local storage. */
25
+ encryptedArguments?: boolean;
26
+ }
27
+
28
+ export type SharedContextResult = AgentToolResult<{
29
+ codexHistoryNotes: Record<string, unknown>;
30
+ externalNotesResponses?: SerializedCachedResponse[];
31
+ }>;
32
+
33
+ export type ContextRouter = ((
34
+ ctx: ExtensionContext,
35
+ request: SharedContextRequest,
36
+ signal?: AbortSignal,
37
+ ) => Promise<SharedContextResult | undefined>) & {
38
+ requiresRemoteScope?(ctx: ExtensionContext): boolean;
39
+ };
40
+
41
+ /** Remote checkpoints retain an authenticated address, never decrypted note contents. */
42
+ export interface RemoteNoteReference {
43
+ protocol: 1;
44
+ storage: "remote";
45
+ timestamp: number;
46
+ identity: ContextAgentIdentity;
47
+ baseUrl: string;
48
+ }
49
+ export type AttachmentNotesData = NoteSnapshotData | RemoteNoteReference;
50
+
51
+ export interface ContextSharingService {
52
+ protocol: 1;
53
+ canCreateChild(ctx: ExtensionContext): boolean;
54
+ describe(ctx: ExtensionContext): ContextAgentIdentity | undefined;
55
+ verify(ctx: ExtensionContext): Promise<void>;
56
+ createChild(
57
+ ctx: ExtensionContext,
58
+ options: { name: string; routing?: unknown },
59
+ ): Promise<{
60
+ binding: ContextAgentBinding;
61
+ adopt(): Promise<void>;
62
+ }>;
63
+ bind(
64
+ ctx: ExtensionContext,
65
+ binding: unknown,
66
+ options?: import("./binding-startup.js").ContextFamilyBindingOptions,
67
+ ): Promise<ContextAgentIdentity>;
68
+ /** Inspect an idle standalone owner for alias attachment without rebinding its identity. */
69
+ inspectAttachment?(
70
+ ctx: ExtensionContext,
71
+ standalone?: boolean,
72
+ ): Promise<ContextAgentIdentity> | ContextAgentIdentity;
73
+ /** Keep the native family identity when retaining a live attachment. */
74
+ retainAttachmentIdentity?(ctx: ExtensionContext): ContextAgentIdentity;
75
+ exportAttachmentNotes?(
76
+ ctx: ExtensionContext,
77
+ ): Promise<AttachmentNotesData> | AttachmentNotesData;
78
+ validateAttachmentNotes?(
79
+ snapshot: unknown,
80
+ identity: ContextAgentIdentity,
81
+ ): void;
82
+ verifyAttachmentAccess?(
83
+ ctx: ExtensionContext,
84
+ snapshot: unknown,
85
+ ): Promise<void>;
86
+ executeRemoteAttachment?(
87
+ ctx: ExtensionContext,
88
+ reference: unknown,
89
+ request: SharedContextRequest,
90
+ signal?: AbortSignal,
91
+ ): Promise<SharedContextResult>;
92
+ /** Parse only the verified owner's persisted active note branch. */
93
+ parseAttachmentNotes?(
94
+ entries: unknown,
95
+ identity: ContextAgentIdentity,
96
+ ): NoteSnapshotData;
97
+ readAttachmentNotes?(
98
+ snapshot: unknown,
99
+ params: Record<string, unknown>,
100
+ ): SharedContextResult;
101
+ execute(
102
+ ctx: ExtensionContext,
103
+ request: SharedContextRequest,
104
+ signal?: AbortSignal,
105
+ ): Promise<SharedContextResult>;
106
+ registerRouter(router: ContextRouter): () => void;
107
+ }
108
+
109
+ export const CONTEXT_SHARING_AVAILABLE =
110
+ "pi-notes-compaction:context-sharing:available";
111
+ export const CONTEXT_SHARING_REQUEST =
112
+ "pi-notes-compaction:context-sharing:request";
113
+
114
+ /** Optional, load-order-independent integration. No provider or tool schema changes. */
115
+ export function connectNotesContextSharing(pi: ExtensionAPI): {
116
+ readonly service: ContextSharingService | undefined;
117
+ dispose(): void;
118
+ } {
119
+ let service: ContextSharingService | undefined;
120
+ const off = pi.events.on(CONTEXT_SHARING_AVAILABLE, (value) => {
121
+ const candidate = value as Partial<ContextSharingService> | undefined;
122
+ if (
123
+ candidate?.protocol === 1 &&
124
+ typeof candidate.canCreateChild === "function" &&
125
+ typeof candidate.describe === "function" &&
126
+ typeof candidate.verify === "function" &&
127
+ typeof candidate.createChild === "function" &&
128
+ typeof candidate.bind === "function" &&
129
+ typeof candidate.execute === "function" &&
130
+ typeof candidate.registerRouter === "function"
131
+ )
132
+ service = candidate as ContextSharingService;
133
+ });
134
+ pi.events.emit(CONTEXT_SHARING_REQUEST, { protocol: 1 });
135
+ return {
136
+ get service() {
137
+ return service;
138
+ },
139
+ dispose() {
140
+ off();
141
+ service = undefined;
142
+ },
143
+ };
144
+ }