@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.14.1.g7d1d3da173aa

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 (141) hide show
  1. package/INTEGRATION.md +31 -0
  2. package/LICENSE +21 -0
  3. package/PCC-INTEGRATION.md +17 -0
  4. package/README.md +53 -2
  5. package/dist/viewer/archive.js +249 -0
  6. package/dist/viewer/config.js +85 -0
  7. package/dist/viewer/contracts.js +1 -0
  8. package/dist/viewer/server.js +177 -0
  9. package/dist/viewer/source.js +29 -0
  10. package/dist/viewer/web/app.js +88 -0
  11. package/dist/viewer/web/index.html +41 -0
  12. package/dist/viewer/web/navigation.js +72 -0
  13. package/dist/viewer/web/posts.js +105 -0
  14. package/dist/viewer/web/render.js +147 -0
  15. package/dist/viewer/web/session.js +86 -0
  16. package/dist/viewer/web/style.css +517 -0
  17. package/dist/viewer/web/updates.js +106 -0
  18. package/docs/BOARD-CHANGELOG.md +49 -0
  19. package/docs/BOARD.md +124 -0
  20. package/docs/NOTES-CHANGELOG.md +127 -0
  21. package/docs/NOTES.md +122 -0
  22. package/index.ts +21 -0
  23. package/package.json +75 -5
  24. package/src/board/AGENTS.md +12 -0
  25. package/src/board/activity.ts +274 -0
  26. package/src/board/archive.ts +118 -0
  27. package/src/board/awareness.ts +179 -0
  28. package/src/board/briefing.ts +25 -0
  29. package/src/board/config.ts +192 -0
  30. package/src/board/consolidation.ts +32 -0
  31. package/src/board/context-briefing.ts +245 -0
  32. package/src/board/contract.ts +254 -0
  33. package/src/board/delivery.ts +85 -0
  34. package/src/board/feature.ts +91 -0
  35. package/src/board/identity.ts +238 -0
  36. package/src/board/integration.ts +55 -0
  37. package/src/board/paging.ts +54 -0
  38. package/src/board/protocol.ts +78 -0
  39. package/src/board/queries.ts +168 -0
  40. package/src/board/response.ts +82 -0
  41. package/src/board/runtime/activation.ts +50 -0
  42. package/src/board/runtime/catchup.ts +96 -0
  43. package/src/board/runtime/coordinator.ts +311 -0
  44. package/src/board/runtime/engine.ts +40 -0
  45. package/src/board/runtime/index.ts +63 -0
  46. package/src/board/runtime/owner.ts +168 -0
  47. package/src/board/runtime/routing.ts +152 -0
  48. package/src/board/runtime/turns.ts +109 -0
  49. package/src/board/search.ts +95 -0
  50. package/src/board/settings/panel.ts +193 -0
  51. package/src/board/store.ts +427 -0
  52. package/src/board/summaries.ts +124 -0
  53. package/src/board/summarizer.ts +201 -0
  54. package/src/board/tool.ts +27 -0
  55. package/src/board/viewer/AGENTS.md +1 -0
  56. package/src/board/viewer/archive.ts +308 -0
  57. package/src/board/viewer/config.ts +111 -0
  58. package/src/board/viewer/contracts.ts +98 -0
  59. package/src/board/viewer/index.ts +162 -0
  60. package/src/board/viewer/server.ts +204 -0
  61. package/src/board/viewer/source.ts +33 -0
  62. package/src/board/viewer/web/app.js +88 -0
  63. package/src/board/viewer/web/index.html +41 -0
  64. package/src/board/viewer/web/navigation.js +72 -0
  65. package/src/board/viewer/web/posts.js +105 -0
  66. package/src/board/viewer/web/render.js +147 -0
  67. package/src/board/viewer/web/session.js +86 -0
  68. package/src/board/viewer/web/style.css +517 -0
  69. package/src/board/viewer/web/updates.js +106 -0
  70. package/src/guidance.ts +121 -0
  71. package/src/notes/AGENTS.md +27 -0
  72. package/src/notes/activation.ts +150 -0
  73. package/src/notes/agent-identity.ts +221 -0
  74. package/src/notes/attachment-sharing.ts +165 -0
  75. package/src/notes/attachment-snapshot.ts +113 -0
  76. package/src/notes/binding-startup.ts +30 -0
  77. package/src/notes/bridge.ts +130 -0
  78. package/src/notes/compaction-projection.ts +88 -0
  79. package/src/notes/context-owner.ts +99 -0
  80. package/src/notes/context-sharing.ts +178 -0
  81. package/src/notes/extension-hooks.ts +200 -0
  82. package/src/notes/extension-sharing.ts +133 -0
  83. package/src/notes/feature.ts +168 -0
  84. package/src/notes/fresh-checkpoint.ts +143 -0
  85. package/src/notes/fresh-notes.ts +323 -0
  86. package/src/notes/history-search-protocol.ts +39 -0
  87. package/src/notes/history-search-pruning.mjs +120 -0
  88. package/src/notes/history-search-worker.mjs +258 -0
  89. package/src/notes/history-search.ts +269 -0
  90. package/src/notes/history-windows.ts +221 -0
  91. package/src/notes/history.ts +158 -0
  92. package/src/notes/idle-admission.ts +201 -0
  93. package/src/notes/index.ts +125 -0
  94. package/src/notes/integrations.ts +174 -0
  95. package/src/notes/lifecycle.ts +308 -0
  96. package/src/notes/model-role-config.ts +79 -0
  97. package/src/notes/model-role-screen.ts +74 -0
  98. package/src/notes/model-roles.ts +225 -0
  99. package/src/notes/note-query.ts +148 -0
  100. package/src/notes/note-result.ts +88 -0
  101. package/src/notes/note-save-marker.ts +128 -0
  102. package/src/notes/notes-lookup.ts +115 -0
  103. package/src/notes/notes.ts +302 -0
  104. package/src/notes/query-executor.ts +242 -0
  105. package/src/notes/query-input.ts +126 -0
  106. package/src/notes/remote.ts +376 -0
  107. package/src/notes/rollover.ts +224 -0
  108. package/src/notes/saved-session-access.ts +117 -0
  109. package/src/notes/saved-session-index.mjs +83 -0
  110. package/src/notes/saved-session.mjs +241 -0
  111. package/src/notes/saved-session.ts +51 -0
  112. package/src/notes/saved-sharing-records.ts +135 -0
  113. package/src/notes/session-pruning-content.ts +237 -0
  114. package/src/notes/session-pruning-plan.ts +243 -0
  115. package/src/notes/session-pruning-policy.ts +20 -0
  116. package/src/notes/session-pruning-screen.ts +204 -0
  117. package/src/notes/session-pruning-source.ts +44 -0
  118. package/src/notes/session-pruning-transaction.ts +141 -0
  119. package/src/notes/session-pruning.ts +155 -0
  120. package/src/notes/settings-command.ts +95 -0
  121. package/src/notes/settings-controls.ts +199 -0
  122. package/src/notes/settings-screen.ts +113 -0
  123. package/src/notes/settings.ts +287 -0
  124. package/src/notes/shared-notes.ts +411 -0
  125. package/src/notes/shared-session-reader.ts +143 -0
  126. package/src/notes/sharing-service.ts +282 -0
  127. package/src/notes/sqlite.mjs +33 -0
  128. package/src/notes/store.ts +283 -0
  129. package/src/notes/task-boundary.ts +37 -0
  130. package/src/notes/tool-contracts.ts +312 -0
  131. package/src/notes/tools.ts +148 -0
  132. package/src/notes/tree-archive-manifest.mjs +27 -0
  133. package/src/notes/tree-archive.ts +129 -0
  134. package/src/notes/tree-checkpoint.ts +170 -0
  135. package/src/notes/tree-handoff-read.ts +192 -0
  136. package/src/notes/window-checkpoint.ts +105 -0
  137. package/src/notes/window-message.ts +185 -0
  138. package/src/notes/windows.ts +272 -0
  139. package/src/settings-navigation.ts +11 -0
  140. package/src/timestamps.ts +3 -0
  141. package/tsconfig.json +9 -0
@@ -0,0 +1,121 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ contextBriefingWindow,
7
+ recordContextBriefing,
8
+ registerContextBriefing,
9
+ } from "./board/context-briefing.js";
10
+ import type { FeatureSettings } from "./settings-navigation.js";
11
+
12
+ export interface CommsFeature extends FeatureSettings {
13
+ enabled(ctx: ExtensionContext): boolean;
14
+ gptPromptMode(): boolean;
15
+ }
16
+
17
+ /** Routing belongs here; feature carriers retain identity, recovery and navigation. */
18
+ function communicationGuidance(
19
+ notes: boolean,
20
+ board: boolean,
21
+ agents: boolean,
22
+ gpt = false,
23
+ ): string {
24
+ return [
25
+ board
26
+ ? gpt
27
+ ? "Board→peer findings/discovery, ownership/decisions/blockers affecting peers. Self-contained detail welcome; direct discovery≠parent relay. Existing thread replies; known shared peers→link≠repeat. No ack/status spam/duplicate completion reports."
28
+ : "Board: share findings, discoveries, ownership, decisions and blockers that change peers' work. Self-contained detail lets peers read directly, without a parent relay. Reply in existing threads. Link rather than repeat for peers with known Board access. Skip acknowledgements, routine status and duplicate completion reports."
29
+ : "",
30
+ notes
31
+ ? [
32
+ board
33
+ ? gpt
34
+ ? "Notes→current work/progress/recovery + Board references."
35
+ : "Notes: current work, progress and recovery, with Board references."
36
+ : "",
37
+ gpt
38
+ ? "Keep Notes checkpoints. Known recipient access→brief outcome/blocker + path; recipient READS checkpoint≠request full report."
39
+ : "Keep checkpoints in Notes. When the recipient is known to have access, return a brief outcome or blocker plus its path. The recipient reads the checkpoint for details rather than asking for a full report.",
40
+ ]
41
+ .filter(Boolean)
42
+ .join(" ")
43
+ : "",
44
+ notes || board
45
+ ? gpt
46
+ ? `${notes && board ? "Notes/Board" : notes ? "Notes" : "Board"} available here≠recipient access. Unknown/unshared access→self-contained actions taken/findings/unresolved state, not bare references.`
47
+ : `${notes && board ? "Notes and Board" : notes ? "Notes" : "Board"} availability here does not establish recipient access. If access is unknown or unshared, send a self-contained account of what you did, found and left unresolved, not just private references.`
48
+ : "",
49
+ agents && notes && board
50
+ ? gpt
51
+ ? "agents→assignments/urgent action≠default peer knowledge bus."
52
+ : "Use agents for assignments and urgent action, not as the default peer knowledge relay."
53
+ : "",
54
+ ]
55
+ .filter(Boolean)
56
+ .join(" ");
57
+ }
58
+
59
+ export function registerCommunicationGuidance(
60
+ pi: ExtensionAPI,
61
+ notes?: CommsFeature,
62
+ board?: CommsFeature,
63
+ ): void {
64
+ const owner =
65
+ notes && board
66
+ ? "agent-comms-routing"
67
+ : notes
68
+ ? "notes-routing"
69
+ : "board-routing";
70
+ registerContextBriefing(
71
+ pi,
72
+ "communication",
73
+ (ctx) => Boolean(notes?.enabled(ctx) || board?.enabled(ctx)),
74
+ async (ctx, windowId, messages) => {
75
+ // Feature owners supply enablement independently of provider declarations.
76
+ // Shepherdr keeps agents active, including as a nested Code/Notebook tool.
77
+ const capabilities = [
78
+ notes?.enabled(ctx) ?? false,
79
+ board?.enabled(ctx) ?? false,
80
+ pi.getActiveTools().includes("agents"),
81
+ Boolean(notes?.gptPromptMode() || board?.gptPromptMode()),
82
+ ] as const;
83
+ const routing = communicationGuidance(...capabilities);
84
+ const previous = messages
85
+ ?.flatMap((message) => {
86
+ if (
87
+ message.role !== "custom" ||
88
+ message.customType !== "codex-context-briefing"
89
+ )
90
+ return [];
91
+ const details = message.details;
92
+ return details &&
93
+ typeof details === "object" &&
94
+ "owner" in details &&
95
+ details.owner === owner &&
96
+ "id" in details &&
97
+ typeof details.id === "string"
98
+ ? [{ id: details.id, content: message.content }]
99
+ : [];
100
+ })
101
+ .at(-1);
102
+ if (!routing && !previous) return;
103
+ const content =
104
+ routing ||
105
+ `${notes && board ? "Notes and Board are" : notes ? "Notes is" : "Board is"} currently inactive. Earlier communication routing no longer applies.`;
106
+ if (previous?.content === content) return;
107
+ await recordContextBriefing(
108
+ pi,
109
+ ctx,
110
+ owner,
111
+ JSON.stringify([
112
+ ctx.sessionManager.getSessionId(),
113
+ contextBriefingWindow(ctx, windowId),
114
+ ...capabilities,
115
+ previous?.id,
116
+ ]),
117
+ async () => content,
118
+ );
119
+ },
120
+ );
121
+ }
@@ -0,0 +1,27 @@
1
+ - Fresh idle family binding accepts foreign plain `custom` startup metadata, not `custom_message` conversation or Notes ownership/work records. Identity checks stay session-wide, including abandoned branches. A host may supply only child-owned entries after validating an explicit inherited fork boundary; omission checks the full session.
2
+ - Public agent names derive from native Pi session IDs. Reject native ID `root` before routing or writes: it collides with legacy `/root`. Keep legacy storage addresses separate, including authenticated remote scopes. `/root` aliases only the family root (`threadId === sessionId`), never an arbitrary shared child. Restore unbound remote ownership only from its native-matching backend pin, not inherited prompt text.
3
+ - Notes owns continuity and its registrations. PCC is optional provider infrastructure. Use public code-mode, prompt-mode, developer-messages and compaction APIs, never arbitration or PCC internal imports.
4
+ - Resolve History's query-only search default before action-scoped hint filtering. Preserve explicit actions; never infer an operation from filters alone.
5
+ - Saved shared-note reads belong to Notes, not live orchestration. SQLite paths are hints, never membership evidence: verify native JSONL identity and an explicit family binding; do not require a live parent for immutable ordinary-family membership. Attachment routes and detach snapshots still own their addresses. Identity is session-wide; note revisions follow the selected branch. Preserve hybrid bases/cache; resolve `machine:local` relative to the containing saved session. Keep the public saved-session `.mjs` reader Node-only; Core bundles it without Pi or TypeScript. History reads Pi JSONL locally or through live family/attachment routing, never backend lookups or cached remote responses; preserve historical persisted records without rewriting them.
6
+ - Notes publishes one canonical payload as text and structuredContent with outputSchema. Preserve it through sharing and alias remapping; PCC consumes it directly. History keeps canonical content. Never derive values from freshness or routing details. Only Notes permits protected-output delivery.
7
+ - History's FTS index is derived and opt-in for the current session only. Disabled and other saved-session reads never build indexes; explicit pruning may delete existing rows. Reconcile committed JSONL pruning generations before indexing: the live SessionManager remains stale until restart. Rank only retired user/assistant visible text: Notes `trim=true` boundaries plus normal compaction's kept-entry cut, not window ID alone. Untrimmed initialization/rollover preserves live context. Never index calls, results, thinking or custom metadata. Explicit live/tool scopes and shared reads stay literal; full canonical reads remain intact. Scope ranked queries to selected JSONL entries after branch/window/tool filters; cached rows are not permission to return them. Keep user queries out of raw FTS syntax and Notes search unchanged.
8
+ - History caches lazy metadata by immutable Pi entry identity, not full rendered content: live entries retain cache values for the session lifetime. Never mutate cached entries. Its checked `.mjs` worker runs outside jiti; Node refuses type stripping under `node_modules`. Keep worker protocol imports type-only and probe a real installed-directory copy, not a checkout symlink.
9
+ - Register compaction preparation through the optional public PCC API so cancellation and projected branch preparation precede provider work in either load order. Manual notes rollover waits for user input. Tool-requested rollover continues.
10
+ - Pi's `Compaction cancelled` notice during Notes-only rollover is cosmetic, not a defect, blocker or delivery caveat. Check the actual window transition instead of chasing or repeatedly reporting the notice.
11
+ - Await optional context-window preparation before a notes-only history cut, then recheck session/window validity. Summary compaction owns its refresh already; identity-only windows do not repeat it.
12
+ - Pi-limited notes-only requests cancel their own eligible pre-compaction hook before provider work. Only that owned cancellation permits rollover; Pi's exact no-work errors retain the window, other failures remain failures. Request permission never changes idle or manual policy.
13
+ - new_context requires a successful own save in the immediately preceding tool-call group, including parallel peers, or completed same-group predecessors. Never flatten groups into a last-call check or accept saves from older groups. Reuse fresh-notes.ts receipts and completed outcomes, including exec/wait; its own unfinished call is not missing-write evidence. Routed writes neither satisfy nor invalidate a local checkpoint in a mixed cell. Idle freshness still requires a completed run.
14
+ - Persist pending nested-write evidence before execution; only its matching completion may replace it. `pending` is required: starts are `pending:true,saved:false`; successful completions are `pending:false,saved:true`. Keep producers, readiness readers, save indicator and cutoff on this persisted meaning; semantic changes require an explicit protocol change, not incidental release edits. Pi's incomplete nested-call log also means omitted arguments, not necessarily unfinished writes.
15
+ - Tree navigation to a user/custom prompt stops at its parent, possibly after that prompt's preparation marker. A marker without delivered conversation must not stale the previous saved checkpoint; explicit run-scoped write proof stays strict.
16
+ - Custom kickoffs skip input hooks. The custom-turn-admission event owns pre-kickoff idle rollover; compaction must finish before Pi reserves startup as busy. Successor custom turns run every before_agent_start hook.
17
+ - Model deactivation yields policy and tools, not committed history cuts. Untrimmed initialization never undoes a prior retirement; real compaction can supersede it. Preserve projection on context and compaction routes in either extension order.
18
+ - Native window checkpoints must cut the complete committed window atomically. Partial context edits invalidate Pi's usage accounting while leaving old history in its estimate. Keep the owned empty summary out of model projection; preserve raw entries and foreign compaction drafts. Restore idle native context before kickoff, never compact inside busy tree preparation.
19
+ - Restore compacted-away identity only in complete context, ahead of its summary. Keep replay slices untouched and developer metadata stable; never queue a turn to restore guidance.
20
+ - Persisted Tree archive/checkpoint/handoff readers preserve source IDs and original protected outputs. Pruning must protect effective archived checkpoints and kept entries at planning and commit, not only Pi's physical context. Never recreate the retired Tree writer or reinterpret missing fork archives as empty history.
21
+ - Return initial and rebound identity from before_agent_start, never send it during startup. Pi inserts its initial system entry ahead of returned hook messages; startup sends otherwise put per-session identity before the shared cache prefix.
22
+ - Automatic rollover uses the successor window message as its custom kickoff. That entry is not yet in the branch during before_agent_start; adopt its identity instead of restoring the outgoing window or returning another boundary.
23
+ - Compaction handoff reads are transient branch contributions anchored to their persisted summary. Rechain only the projected branch, never append contributions or persist their IDs as Pi's first-kept boundary. Compare projected entry identity, not branch length.
24
+ - Session pruning preserves JSONL order/count/IDs and unchanged raw lines; Observatory rebases derived source ranges using header `notesPruning` generations, never a tail receipt alone. Its final tail-copy/rename must contain no await. Released Pi's already-flushed same-path writes are append-only; re-trace SDK rewrite paths when changing this boundary. Do not mutate its live history or coordinate foreign JSONL writers.
25
+ - Pi persists incoming messages after before_agent_start, agent_start and message_end hooks, before returned startup messages. History assigns the kickoff prefix only to the first untrimmed window, never later or identity-only boundaries. Label saved-note continuation prompts in context once their entries exist. Schedule pruning from Notes' admitted window identity, then verify its persisted marker after settlement.
26
+ - Pruning must not turn removed delivered instruction carriers into pending-message redelivery. Coalesce only proven complete state snapshots per branch leaf; unknown custom protocols can contain deltas. Keep current Notes revisions, monitor snapshots, Board routes and notebook epochs, not historical model-facing text disguised as state.
27
+ - Role handoffs prepare the outgoing provider before selecting the successor model and starting the normal window kickoff. Keep checkpoint and compaction gates, rechecking session/window after async work. Role guidance exposes IDs/descriptions only. In-run compaction restores its persisted carrier before the summary without a new turn or prefix edit.
@@ -0,0 +1,150 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { type NotesBridge, TOOL_NAMES } from "./bridge.js";
6
+ import { indexHistory } from "./history.js";
7
+ import type { HistorySearch } from "./history-search.js";
8
+ import type { NotesLifecycle } from "./lifecycle.js";
9
+ import { sessionRef } from "./notes.js";
10
+ import {
11
+ loadNotesSettings,
12
+ modelIsActive,
13
+ type NotesSettings,
14
+ writeSettings,
15
+ } from "./settings.js";
16
+ import type { NotesStore } from "./store.js";
17
+
18
+ export function createNotesActivation(
19
+ pi: ExtensionAPI,
20
+ store: NotesStore,
21
+ search: HistorySearch,
22
+ lifecycle: NotesLifecycle,
23
+ settingsPath: string,
24
+ refreshNested: () => void,
25
+ ) {
26
+ let settings: NotesSettings;
27
+ let ready = false;
28
+ let unavailable: string | undefined;
29
+ function refreshActivation(ctx: ExtensionContext): void {
30
+ if (!ready || unavailable) return;
31
+ const active = modelIsActive(settings, ctx.model);
32
+ if (!active) {
33
+ if (lifecycle.active) lifecycle.reset(ctx);
34
+ lifecycle.active = false;
35
+ search.setSession(undefined);
36
+ store.close();
37
+ pi.setActiveTools(
38
+ pi
39
+ .getActiveTools()
40
+ .filter((name) => !TOOL_NAMES.some((tool) => tool === name)),
41
+ );
42
+ refreshNested();
43
+ return;
44
+ }
45
+ if (lifecycle.active) return;
46
+ try {
47
+ lifecycle.active = true;
48
+ configureTools();
49
+ store.updateFile(sessionRef(ctx));
50
+ refreshHistorySearch(ctx);
51
+ } catch (error) {
52
+ lifecycle.active = false;
53
+ unavailable = error instanceof Error ? error.message : String(error);
54
+ ctx.ui.notify(`Notes continuity inactive: ${unavailable}`, "warning");
55
+ }
56
+ }
57
+ function configureTools(): void {
58
+ const names = TOOL_NAMES.filter(
59
+ (name) => name !== "new_context" || lifecycle.newWindowRequests !== "off",
60
+ );
61
+ pi.setActiveTools([
62
+ ...new Set([
63
+ ...pi
64
+ .getActiveTools()
65
+ .filter((name) => !TOOL_NAMES.some((tool) => tool === name)),
66
+ ...names,
67
+ ]),
68
+ ]);
69
+ refreshNested();
70
+ }
71
+ function refreshHistorySearch(ctx: ExtensionContext, update = false): void {
72
+ const sessionId =
73
+ lifecycle.active && settings.rankedHistorySearch
74
+ ? ctx.sessionManager.getSessionId()
75
+ : undefined;
76
+ const changed = search.setSession(
77
+ sessionId,
78
+ ctx.sessionManager.getSessionFile(),
79
+ );
80
+ if (!sessionId || (!changed && !update)) return;
81
+ void indexHistory(
82
+ ctx.sessionManager.getBranch(),
83
+ sessionId,
84
+ search,
85
+ ctx.sessionManager.getEntries(),
86
+ ).catch((error: unknown) => {
87
+ if (!search.isEnabled(sessionId)) return;
88
+ ctx.ui.notify(
89
+ error instanceof Error ? error.message : String(error),
90
+ "warning",
91
+ );
92
+ });
93
+ }
94
+ function applySettings(value: NotesSettings): void {
95
+ settings = value;
96
+ lifecycle.normalCompaction = value.normalCompaction;
97
+ lifecycle.newWindowRequests = value.newWindowRequests;
98
+ lifecycle.idleMinutes = value.idleMinutes;
99
+ lifecycle.taskBoundaryReminder = value.taskBoundaryReminder;
100
+ }
101
+ function start(
102
+ ctx: ExtensionContext,
103
+ family: NotesBridge,
104
+ initial?: NotesSettings,
105
+ ): void {
106
+ search.setSession(undefined);
107
+ lifecycle.reset(ctx);
108
+ lifecycle.active = false;
109
+ ready = false;
110
+ unavailable = undefined;
111
+ try {
112
+ settings = initial ?? loadNotesSettings(ctx);
113
+ writeSettings(settingsPath, settings);
114
+ applySettings(settings);
115
+ lifecycle.bridge = family;
116
+ ready = true;
117
+
118
+ refreshActivation(ctx);
119
+ } catch (error) {
120
+ unavailable = error instanceof Error ? error.message : String(error);
121
+ ctx.ui.notify(`Notes continuity inactive: ${unavailable}`, "warning");
122
+ }
123
+ }
124
+ function save(value: NotesSettings, ctx: ExtensionContext): void {
125
+ writeSettings(settingsPath, value);
126
+ applySettings(value);
127
+ refreshActivation(ctx);
128
+ refreshHistorySearch(ctx);
129
+ if (lifecycle.active) configureTools();
130
+ }
131
+ return {
132
+ start,
133
+ save,
134
+ refreshActivation,
135
+ refreshHistorySearch,
136
+ get settings() {
137
+ return settings;
138
+ },
139
+ get ready() {
140
+ return ready;
141
+ },
142
+ get unavailable() {
143
+ return unavailable;
144
+ },
145
+ get available() {
146
+ return ready && !unavailable;
147
+ },
148
+ };
149
+ }
150
+ export type NotesActivation = ReturnType<typeof createNotesActivation>;
@@ -0,0 +1,221 @@
1
+ import type {
2
+ ExtensionContext,
3
+ SessionEntry,
4
+ } from "@earendil-works/pi-coding-agent";
5
+
6
+ export const CONTEXT_AGENT_ENTRY = "codex-context-agent";
7
+ const CONTEXT_BACKEND_ENTRY = "codex-context-backend";
8
+
9
+ export interface ContextAgentIdentity {
10
+ protocol: 1;
11
+ sessionId: string;
12
+ threadId: string;
13
+ agentName: string;
14
+ /** Original persisted Notes address; never changes authenticated remote ownership. */
15
+ storageAgentName?: string;
16
+ storage?: "remote" | "session";
17
+ accountScope?: string;
18
+ backendUrl?: string;
19
+ routing?: unknown;
20
+ }
21
+
22
+ export type ContextAgentBinding = Omit<
23
+ ContextAgentIdentity,
24
+ "threadId" | "storage"
25
+ > & {
26
+ storage: "remote" | "session";
27
+ };
28
+
29
+ export const CONTEXT_AGENT_PATTERN =
30
+ "^/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*(?:/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*)*$";
31
+
32
+ export function isContextAgentName(value: unknown): value is string {
33
+ return (
34
+ typeof value === "string" && new RegExp(CONTEXT_AGENT_PATTERN).test(value)
35
+ );
36
+ }
37
+
38
+ export function canonicalAgentName(threadId: string): string {
39
+ if (threadId === "root")
40
+ throw new Error(
41
+ "Pi session ID root conflicts with the legacy /root reference; start a session with another ID",
42
+ );
43
+ const name = `/${threadId}`;
44
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(threadId))
45
+ throw new Error("Invalid Pi session identity");
46
+ return name;
47
+ }
48
+
49
+ export function contextStorageAgentName(
50
+ identity: Pick<ContextAgentIdentity, "agentName" | "storageAgentName">,
51
+ ): string {
52
+ return identity.storageAgentName ?? identity.agentName;
53
+ }
54
+
55
+ /** /root is a local compatibility alias, never an authenticated storage address. */
56
+ export function contextAgentNames(
57
+ identity: Pick<
58
+ ContextAgentIdentity,
59
+ "agentName" | "storageAgentName" | "threadId" | "sessionId"
60
+ >,
61
+ ): string[] {
62
+ return [
63
+ ...new Set([
64
+ identity.agentName,
65
+ contextStorageAgentName(identity),
66
+ ...(identity.threadId === identity.sessionId ? ["/root"] : []),
67
+ ]),
68
+ ];
69
+ }
70
+
71
+ export function canonicalContextIdentity<T extends ContextAgentIdentity>(
72
+ identity: T,
73
+ ): T {
74
+ const agentName = canonicalAgentName(identity.threadId);
75
+ return {
76
+ ...identity,
77
+ agentName,
78
+ ...(contextStorageAgentName(identity) === agentName
79
+ ? {}
80
+ : { storageAgentName: contextStorageAgentName(identity) }),
81
+ };
82
+ }
83
+
84
+ export function parseContextAgentBinding(input: unknown): ContextAgentBinding {
85
+ const value = input as Partial<ContextAgentBinding> | undefined;
86
+ if (
87
+ value?.protocol !== 1 ||
88
+ typeof value.sessionId !== "string" ||
89
+ !value.sessionId ||
90
+ typeof value.agentName !== "string" ||
91
+ !isContextAgentName(value.agentName) ||
92
+ (value.storageAgentName !== undefined &&
93
+ !isContextAgentName(value.storageAgentName)) ||
94
+ (value.storage !== "remote" && value.storage !== "session") ||
95
+ (value.backendUrl !== undefined &&
96
+ (typeof value.backendUrl !== "string" || !value.backendUrl)) ||
97
+ (value.storage === "remote" &&
98
+ (typeof value.accountScope !== "string" ||
99
+ !/^[a-f0-9]{64}$/.test(value.accountScope)))
100
+ )
101
+ throw new Error("Invalid Codex context identity");
102
+ return {
103
+ protocol: 1,
104
+ sessionId: value.sessionId,
105
+ agentName: value.agentName,
106
+ ...(value.storageAgentName === undefined
107
+ ? {}
108
+ : { storageAgentName: value.storageAgentName }),
109
+ storage: value.storage,
110
+ ...(value.accountScope === undefined
111
+ ? {}
112
+ : { accountScope: value.accountScope }),
113
+ ...(value.backendUrl === undefined ? {} : { backendUrl: value.backendUrl }),
114
+ ...(value.routing === undefined ? {} : { routing: value.routing }),
115
+ };
116
+ }
117
+
118
+ /** Older standalone remote owners may have a backend pin without a family binding. */
119
+ export function pinnedContextIdentity(
120
+ threadId: string,
121
+ entries: readonly SessionEntry[],
122
+ ): ContextAgentIdentity | undefined {
123
+ let identity: ContextAgentIdentity | undefined;
124
+ for (const entry of entries) {
125
+ if (entry.type !== "custom" || entry.customType !== CONTEXT_BACKEND_ENTRY)
126
+ continue;
127
+ const pin = entry.data as Partial<ContextAgentIdentity> | undefined;
128
+ if (pin?.threadId !== threadId) continue;
129
+ const binding = parseContextAgentBinding({
130
+ ...pin,
131
+ protocol: 1,
132
+ storage: "remote",
133
+ });
134
+ if (!binding.backendUrl)
135
+ throw new Error("Saved remote context has no backend address");
136
+ if (
137
+ identity &&
138
+ (identity.sessionId !== binding.sessionId ||
139
+ identity.agentName !== binding.agentName ||
140
+ identity.accountScope !== binding.accountScope ||
141
+ identity.backendUrl !== binding.backendUrl)
142
+ )
143
+ throw new Error("Conflicting persisted Remote context backend");
144
+ identity = { ...binding, threadId };
145
+ }
146
+ return identity;
147
+ }
148
+
149
+ export function contextAgentIdentity(
150
+ ctx: Pick<ExtensionContext, "sessionManager">,
151
+ ): ContextAgentIdentity {
152
+ const threadId = ctx.sessionManager.getSessionId();
153
+ let identity: ContextAgentIdentity | undefined;
154
+ // Identity belongs to the session, not its active branch. Forks get a new identity.
155
+ for (const entry of ctx.sessionManager.getEntries()) {
156
+ if (entry.type !== "custom" || entry.customType !== CONTEXT_AGENT_ENTRY)
157
+ continue;
158
+ const value = entry.data as Partial<ContextAgentIdentity> | undefined;
159
+ if (value?.threadId !== threadId) continue;
160
+ if (identity)
161
+ throw new Error("Conflicting persisted Codex context identities");
162
+ identity = { ...parseContextAgentBinding(value), threadId };
163
+ }
164
+ identity ??= pinnedContextIdentity(threadId, ctx.sessionManager.getEntries());
165
+ if (identity?.storage === "remote") {
166
+ for (const entry of ctx.sessionManager.getEntries()) {
167
+ if (entry.type !== "custom" || entry.customType !== CONTEXT_BACKEND_ENTRY)
168
+ continue;
169
+ const pin = entry.data as Partial<ContextAgentIdentity> | undefined;
170
+ if (pin?.threadId !== threadId) continue;
171
+ if (
172
+ pin.sessionId !== identity.sessionId ||
173
+ (pin.storageAgentName ?? pin.agentName) !==
174
+ contextStorageAgentName(identity) ||
175
+ pin.accountScope !== identity.accountScope ||
176
+ typeof pin.backendUrl !== "string" ||
177
+ !pin.backendUrl ||
178
+ (identity.backendUrl && identity.backendUrl !== pin.backendUrl)
179
+ )
180
+ throw new Error("Conflicting persisted Remote context backend");
181
+ identity.backendUrl = pin.backendUrl;
182
+ }
183
+ }
184
+ return canonicalContextIdentity(
185
+ identity ?? {
186
+ protocol: 1,
187
+ sessionId: threadId,
188
+ threadId,
189
+ agentName: canonicalAgentName(threadId),
190
+ },
191
+ );
192
+ }
193
+
194
+ export function contextTargetAgent(
195
+ namespace: "history" | "notes",
196
+ params: Record<string, unknown>,
197
+ agentName: string,
198
+ ): string {
199
+ const value =
200
+ namespace === "history"
201
+ ? params["agent_name"]
202
+ : (params["path"] ?? params["prefix"] ?? params["path_prefix"]);
203
+ if (value === undefined || value === null || value === "") return agentName;
204
+ if (typeof value !== "string")
205
+ throw new Error("Context path must be a string");
206
+ if (namespace === "notes") {
207
+ if (!value.startsWith("/")) return agentName;
208
+ const boundary = /\/notes(?:\/|$)/.exec(value)?.index ?? -1;
209
+ const target = boundary < 0 ? "" : value.slice(0, boundary);
210
+ if (
211
+ !isContextAgentName(target) ||
212
+ !/^\/notes(?:\/|$)/.test(value.slice(boundary))
213
+ )
214
+ throw new Error("Absolute note paths must use <agent>/notes[/path]");
215
+ return target;
216
+ }
217
+ const target = value.startsWith("/") ? value : `${agentName}/${value}`;
218
+ if (!isContextAgentName(target))
219
+ throw new Error("Invalid history agent name");
220
+ return target;
221
+ }
@@ -0,0 +1,165 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ canonicalContextIdentity,
5
+ contextStorageAgentName,
6
+ contextTargetAgent,
7
+ } from "./agent-identity.js";
8
+ import {
9
+ readAttachmentSnapshot,
10
+ readRemoteNoteReference,
11
+ } from "./attachment-snapshot.js";
12
+ import type { ContextSharingService } from "./context-sharing.js";
13
+ import { noteResult } from "./note-result.js";
14
+ import { exportNotesSnapshot } from "./notes.js";
15
+
16
+ export function createAttachmentSharing(
17
+ describe: ContextSharingService["describe"],
18
+ ) {
19
+ return {
20
+ exportAttachmentNotes(ctx) {
21
+ const identity = describe(ctx);
22
+ if (!identity)
23
+ throw new Error("Checkpoint export requires notes-based continuity");
24
+ if (identity.storage === "remote") {
25
+ if (!identity.backendUrl)
26
+ throw new Error("Saved remote context has no backend address");
27
+ return {
28
+ protocol: 1,
29
+ storage: "remote",
30
+ timestamp: Date.now(),
31
+ identity,
32
+ baseUrl: identity.backendUrl,
33
+ };
34
+ }
35
+
36
+ const snapshot = exportNotesSnapshot(
37
+ ctx.sessionManager.getBranch(),
38
+ identity.agentName,
39
+ );
40
+ return {
41
+ ...snapshot,
42
+ files: snapshot.files.filter(
43
+ (file) =>
44
+ contextTargetAgent(
45
+ "notes",
46
+ { path: file.path },
47
+ identity.agentName,
48
+ ) === identity.agentName,
49
+ ),
50
+ };
51
+ },
52
+ validateAttachmentNotes(snapshot, identity) {
53
+ if (identity.storage === "remote") {
54
+ if (
55
+ !isDeepStrictEqual(
56
+ canonicalContextIdentity(
57
+ readRemoteNoteReference(snapshot).identity,
58
+ ),
59
+ canonicalContextIdentity(identity),
60
+ )
61
+ )
62
+ throw new Error("Remote checkpoint owner changed");
63
+ } else {
64
+ readAttachmentSnapshot(snapshot, {
65
+ action: "list_files_by_prefix",
66
+ prefix: `${identity.agentName}/notes`,
67
+ });
68
+ if (
69
+ !snapshot ||
70
+ typeof snapshot !== "object" ||
71
+ !("files" in snapshot) ||
72
+ !Array.isArray(snapshot.files) ||
73
+ snapshot.files.some(
74
+ (file: unknown) =>
75
+ !file ||
76
+ typeof file !== "object" ||
77
+ !("path" in file) ||
78
+ typeof file.path !== "string" ||
79
+ ![identity.agentName, contextStorageAgentName(identity)].includes(
80
+ contextTargetAgent(
81
+ "notes",
82
+ { path: file.path },
83
+ identity.agentName,
84
+ ),
85
+ ),
86
+ )
87
+ )
88
+ throw new Error(
89
+ "Retained checkpoint belongs to a different notes owner",
90
+ );
91
+ }
92
+ },
93
+ async verifyAttachmentAccess(ctx, snapshot) {
94
+ if (
95
+ !snapshot ||
96
+ typeof snapshot !== "object" ||
97
+ !("storage" in snapshot) ||
98
+ snapshot.storage !== "remote"
99
+ )
100
+ return;
101
+ const { verifyRemoteReference } = await import("./remote.js");
102
+ await verifyRemoteReference(ctx, readRemoteNoteReference(snapshot));
103
+ },
104
+ async executeRemoteAttachment(ctx, snapshot, request, signal) {
105
+ if (request.namespace === "history")
106
+ throw new Error(
107
+ "History is unavailable from a saved remote notes attachment. Open its saved Pi JSONL session on this machine, then retry.",
108
+ );
109
+ const { executeRemoteAttachment } = await import("./remote.js");
110
+ return executeRemoteAttachment(
111
+ ctx,
112
+ readRemoteNoteReference(snapshot),
113
+ request,
114
+ signal,
115
+ );
116
+ },
117
+ parseAttachmentNotes(input, identity) {
118
+ if (!Array.isArray(input))
119
+ throw new Error("Invalid persisted checkpoint entries");
120
+ const entries: SessionEntry[] = input.map((entry: unknown) => {
121
+ if (
122
+ !entry ||
123
+ typeof entry !== "object" ||
124
+ !("type" in entry) ||
125
+ !(
126
+ (entry.type === "custom" &&
127
+ "customType" in entry &&
128
+ typeof entry.customType === "string" &&
129
+ "data" in entry) ||
130
+ (entry.type === "branch_summary" && "details" in entry)
131
+ )
132
+ )
133
+ throw new Error("Invalid persisted checkpoint entry");
134
+ return entry as SessionEntry;
135
+ });
136
+ const snapshot = exportNotesSnapshot(entries, identity.agentName);
137
+ return {
138
+ ...snapshot,
139
+ files: snapshot.files.filter(
140
+ (file) =>
141
+ contextTargetAgent(
142
+ "notes",
143
+ { path: file.path },
144
+ identity.agentName,
145
+ ) === identity.agentName,
146
+ ),
147
+ };
148
+ },
149
+ readAttachmentNotes(snapshot, params, annotation) {
150
+ const details = readAttachmentSnapshot(snapshot, params);
151
+ return {
152
+ ...noteResult({ ...details, ...annotation }),
153
+ details: { codexHistoryNotes: { ...details, ...annotation } },
154
+ };
155
+ },
156
+ } satisfies Pick<
157
+ ContextSharingService,
158
+ | "exportAttachmentNotes"
159
+ | "validateAttachmentNotes"
160
+ | "verifyAttachmentAccess"
161
+ | "executeRemoteAttachment"
162
+ | "parseAttachmentNotes"
163
+ | "readAttachmentNotes"
164
+ >;
165
+ }