@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.
- package/INTEGRATION.md +31 -0
- package/LICENSE +21 -0
- package/PCC-INTEGRATION.md +17 -0
- package/README.md +53 -2
- package/dist/viewer/archive.js +249 -0
- package/dist/viewer/config.js +85 -0
- package/dist/viewer/contracts.js +1 -0
- package/dist/viewer/server.js +177 -0
- package/dist/viewer/source.js +29 -0
- package/dist/viewer/web/app.js +88 -0
- package/dist/viewer/web/index.html +41 -0
- package/dist/viewer/web/navigation.js +72 -0
- package/dist/viewer/web/posts.js +105 -0
- package/dist/viewer/web/render.js +147 -0
- package/dist/viewer/web/session.js +86 -0
- package/dist/viewer/web/style.css +517 -0
- package/dist/viewer/web/updates.js +106 -0
- package/docs/BOARD-CHANGELOG.md +49 -0
- package/docs/BOARD.md +124 -0
- package/docs/NOTES-CHANGELOG.md +127 -0
- package/docs/NOTES.md +122 -0
- package/index.ts +21 -0
- package/package.json +75 -5
- package/src/board/AGENTS.md +12 -0
- package/src/board/activity.ts +274 -0
- package/src/board/archive.ts +118 -0
- package/src/board/awareness.ts +179 -0
- package/src/board/briefing.ts +25 -0
- package/src/board/config.ts +192 -0
- package/src/board/consolidation.ts +32 -0
- package/src/board/context-briefing.ts +245 -0
- package/src/board/contract.ts +254 -0
- package/src/board/delivery.ts +85 -0
- package/src/board/feature.ts +91 -0
- package/src/board/identity.ts +238 -0
- package/src/board/integration.ts +55 -0
- package/src/board/paging.ts +54 -0
- package/src/board/protocol.ts +78 -0
- package/src/board/queries.ts +168 -0
- package/src/board/response.ts +82 -0
- package/src/board/runtime/activation.ts +50 -0
- package/src/board/runtime/catchup.ts +96 -0
- package/src/board/runtime/coordinator.ts +311 -0
- package/src/board/runtime/engine.ts +40 -0
- package/src/board/runtime/index.ts +63 -0
- package/src/board/runtime/owner.ts +168 -0
- package/src/board/runtime/routing.ts +152 -0
- package/src/board/runtime/turns.ts +109 -0
- package/src/board/search.ts +95 -0
- package/src/board/settings/panel.ts +193 -0
- package/src/board/store.ts +427 -0
- package/src/board/summaries.ts +124 -0
- package/src/board/summarizer.ts +201 -0
- package/src/board/tool.ts +27 -0
- package/src/board/viewer/AGENTS.md +1 -0
- package/src/board/viewer/archive.ts +308 -0
- package/src/board/viewer/config.ts +111 -0
- package/src/board/viewer/contracts.ts +98 -0
- package/src/board/viewer/index.ts +162 -0
- package/src/board/viewer/server.ts +204 -0
- package/src/board/viewer/source.ts +33 -0
- package/src/board/viewer/web/app.js +88 -0
- package/src/board/viewer/web/index.html +41 -0
- package/src/board/viewer/web/navigation.js +72 -0
- package/src/board/viewer/web/posts.js +105 -0
- package/src/board/viewer/web/render.js +147 -0
- package/src/board/viewer/web/session.js +86 -0
- package/src/board/viewer/web/style.css +517 -0
- package/src/board/viewer/web/updates.js +106 -0
- package/src/guidance.ts +121 -0
- package/src/notes/AGENTS.md +27 -0
- package/src/notes/activation.ts +150 -0
- package/src/notes/agent-identity.ts +221 -0
- package/src/notes/attachment-sharing.ts +165 -0
- package/src/notes/attachment-snapshot.ts +113 -0
- package/src/notes/binding-startup.ts +30 -0
- package/src/notes/bridge.ts +130 -0
- package/src/notes/compaction-projection.ts +88 -0
- package/src/notes/context-owner.ts +99 -0
- package/src/notes/context-sharing.ts +178 -0
- package/src/notes/extension-hooks.ts +200 -0
- package/src/notes/extension-sharing.ts +133 -0
- package/src/notes/feature.ts +168 -0
- package/src/notes/fresh-checkpoint.ts +143 -0
- package/src/notes/fresh-notes.ts +323 -0
- package/src/notes/history-search-protocol.ts +39 -0
- package/src/notes/history-search-pruning.mjs +120 -0
- package/src/notes/history-search-worker.mjs +258 -0
- package/src/notes/history-search.ts +269 -0
- package/src/notes/history-windows.ts +221 -0
- package/src/notes/history.ts +158 -0
- package/src/notes/idle-admission.ts +201 -0
- package/src/notes/index.ts +125 -0
- package/src/notes/integrations.ts +174 -0
- package/src/notes/lifecycle.ts +308 -0
- package/src/notes/model-role-config.ts +79 -0
- package/src/notes/model-role-screen.ts +74 -0
- package/src/notes/model-roles.ts +225 -0
- package/src/notes/note-query.ts +148 -0
- package/src/notes/note-result.ts +88 -0
- package/src/notes/note-save-marker.ts +128 -0
- package/src/notes/notes-lookup.ts +115 -0
- package/src/notes/notes.ts +302 -0
- package/src/notes/query-executor.ts +242 -0
- package/src/notes/query-input.ts +126 -0
- package/src/notes/remote.ts +376 -0
- package/src/notes/rollover.ts +224 -0
- package/src/notes/saved-session-access.ts +117 -0
- package/src/notes/saved-session-index.mjs +83 -0
- package/src/notes/saved-session.mjs +241 -0
- package/src/notes/saved-session.ts +51 -0
- package/src/notes/saved-sharing-records.ts +135 -0
- package/src/notes/session-pruning-content.ts +237 -0
- package/src/notes/session-pruning-plan.ts +243 -0
- package/src/notes/session-pruning-policy.ts +20 -0
- package/src/notes/session-pruning-screen.ts +204 -0
- package/src/notes/session-pruning-source.ts +44 -0
- package/src/notes/session-pruning-transaction.ts +141 -0
- package/src/notes/session-pruning.ts +155 -0
- package/src/notes/settings-command.ts +95 -0
- package/src/notes/settings-controls.ts +199 -0
- package/src/notes/settings-screen.ts +113 -0
- package/src/notes/settings.ts +287 -0
- package/src/notes/shared-notes.ts +411 -0
- package/src/notes/shared-session-reader.ts +143 -0
- package/src/notes/sharing-service.ts +282 -0
- package/src/notes/sqlite.mjs +33 -0
- package/src/notes/store.ts +283 -0
- package/src/notes/task-boundary.ts +37 -0
- package/src/notes/tool-contracts.ts +312 -0
- package/src/notes/tools.ts +148 -0
- package/src/notes/tree-archive-manifest.mjs +27 -0
- package/src/notes/tree-archive.ts +129 -0
- package/src/notes/tree-checkpoint.ts +170 -0
- package/src/notes/tree-handoff-read.ts +192 -0
- package/src/notes/window-checkpoint.ts +105 -0
- package/src/notes/window-message.ts +185 -0
- package/src/notes/windows.ts +272 -0
- package/src/settings-navigation.ts +11 -0
- package/src/timestamps.ts +3 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { readdir, stat } from "node:fs/promises";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
|
|
6
|
+
/** Exact path hints only. Neither the index nor a filename establishes Notes membership.
|
|
7
|
+
* Missing indexes are normal for old sessions; other index failures are reported.
|
|
8
|
+
* @param {string} threadId
|
|
9
|
+
* @param {string} [agentDir]
|
|
10
|
+
* @param {AbortSignal} [signal]
|
|
11
|
+
* @returns {Promise<string[]>}
|
|
12
|
+
*/
|
|
13
|
+
export async function findSavedNotesSessions(threadId, agentDir, signal) {
|
|
14
|
+
signal?.throwIfAborted();
|
|
15
|
+
if (
|
|
16
|
+
!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(threadId) ||
|
|
17
|
+
threadId === "root"
|
|
18
|
+
)
|
|
19
|
+
throw new Error("Invalid saved session thread ID");
|
|
20
|
+
const configured =
|
|
21
|
+
agentDir ??
|
|
22
|
+
process.env["PI_CODING_AGENT_DIR"] ??
|
|
23
|
+
join(homedir(), ".pi", "agent");
|
|
24
|
+
const dir =
|
|
25
|
+
configured === "~" || configured.startsWith("~/")
|
|
26
|
+
? join(homedir(), configured.slice(2))
|
|
27
|
+
: resolve(configured);
|
|
28
|
+
const paths = new Set();
|
|
29
|
+
const index = join(dir, "notes-compaction", "notes.sqlite");
|
|
30
|
+
try {
|
|
31
|
+
await stat(index);
|
|
32
|
+
/** @type {import("node:sqlite").DatabaseSync} */
|
|
33
|
+
const db = process.versions["bun"]
|
|
34
|
+
? new (createRequire(import.meta.url)("bun:sqlite").Database)(index, {
|
|
35
|
+
readonly: true,
|
|
36
|
+
})
|
|
37
|
+
: new (await import("node:sqlite")).DatabaseSync(index, {
|
|
38
|
+
readOnly: true,
|
|
39
|
+
});
|
|
40
|
+
try {
|
|
41
|
+
signal?.throwIfAborted();
|
|
42
|
+
const table = db
|
|
43
|
+
.prepare(
|
|
44
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sessions'",
|
|
45
|
+
)
|
|
46
|
+
.get();
|
|
47
|
+
if (table) {
|
|
48
|
+
const row = db
|
|
49
|
+
.prepare("SELECT file_path FROM sessions WHERE id = ?")
|
|
50
|
+
.get(threadId);
|
|
51
|
+
if (row && typeof row["file_path"] === "string" && row["file_path"])
|
|
52
|
+
paths.add(row["file_path"]);
|
|
53
|
+
}
|
|
54
|
+
} finally {
|
|
55
|
+
db.close();
|
|
56
|
+
}
|
|
57
|
+
} catch (error) {
|
|
58
|
+
signal?.throwIfAborted();
|
|
59
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
60
|
+
throw new Error(
|
|
61
|
+
"Saved session index is unavailable. Restore access to the Notes index and retry.",
|
|
62
|
+
{ cause: error },
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
const sessions = join(dir, "sessions");
|
|
66
|
+
try {
|
|
67
|
+
for (const cwd of await readdir(sessions, { withFileTypes: true })) {
|
|
68
|
+
signal?.throwIfAborted();
|
|
69
|
+
if (!cwd.isDirectory()) continue;
|
|
70
|
+
const directory = join(sessions, cwd.name);
|
|
71
|
+
for (const file of await readdir(directory, { withFileTypes: true })) {
|
|
72
|
+
signal?.throwIfAborted();
|
|
73
|
+
if (file.isFile() && file.name.endsWith(`_${threadId}.jsonl`))
|
|
74
|
+
paths.add(join(directory, file.name));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} catch (error) {
|
|
78
|
+
signal?.throwIfAborted();
|
|
79
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
return [...paths].sort();
|
|
83
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { open, stat } from "node:fs/promises";
|
|
3
|
+
import {
|
|
4
|
+
isTreeArchiveManifestData,
|
|
5
|
+
MAX_ARCHIVE_DEPTH,
|
|
6
|
+
TREE_ARCHIVE_ENTRY_TYPE,
|
|
7
|
+
} from "./tree-archive-manifest.mjs";
|
|
8
|
+
|
|
9
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
10
|
+
function object(value) {
|
|
11
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
/** @param {unknown} value @returns {value is {type:"session",id:string}} */
|
|
14
|
+
function isSessionHeader(value) {
|
|
15
|
+
return (
|
|
16
|
+
object(value) &&
|
|
17
|
+
value["type"] === "session" &&
|
|
18
|
+
typeof value["id"] === "string"
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
/** @param {unknown} value @returns {value is import("@earendil-works/pi-coding-agent").SessionEntry} */
|
|
22
|
+
function isRecord(value) {
|
|
23
|
+
return (
|
|
24
|
+
object(value) &&
|
|
25
|
+
typeof value["type"] === "string" &&
|
|
26
|
+
typeof value["id"] === "string" &&
|
|
27
|
+
(value["parentId"] === null || typeof value["parentId"] === "string") &&
|
|
28
|
+
typeof value["timestamp"] === "string"
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
/** @param {unknown} value @returns {value is import("@earendil-works/pi-coding-agent").CustomEntry} */
|
|
32
|
+
function isCustom(value) {
|
|
33
|
+
return (
|
|
34
|
+
isRecord(value) &&
|
|
35
|
+
value.type === "custom" &&
|
|
36
|
+
typeof value.customType === "string" &&
|
|
37
|
+
"data" in value
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
/** @param {unknown} value @returns {value is import("@earendil-works/pi-coding-agent").BranchSummaryEntry} */
|
|
41
|
+
function isHandoff(value) {
|
|
42
|
+
return (
|
|
43
|
+
isRecord(value) &&
|
|
44
|
+
value.type === "branch_summary" &&
|
|
45
|
+
typeof value.fromId === "string" &&
|
|
46
|
+
typeof value.summary === "string" &&
|
|
47
|
+
object(value.details) &&
|
|
48
|
+
"codexContextNoteHandoff" in value.details
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const NOTE_ENTRIES = new Set([
|
|
52
|
+
"notes-compaction:note:v1",
|
|
53
|
+
"notes-compaction:cache:v1",
|
|
54
|
+
"codex-context-note",
|
|
55
|
+
"codex-context-note-snapshot",
|
|
56
|
+
]);
|
|
57
|
+
const SHARING_ENTRIES = new Set([
|
|
58
|
+
"codex-context-agent",
|
|
59
|
+
"codex-context-backend",
|
|
60
|
+
"herdr-context-child",
|
|
61
|
+
"shepherdr-attachment-route",
|
|
62
|
+
"shepherdr-attachment-owner",
|
|
63
|
+
"shepherdr-attachment-detached",
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
/** @param {import("node:fs/promises").FileHandle} file @param {number} size @param {AbortSignal} [signal] */
|
|
67
|
+
async function* reverseChunks(file, size, signal) {
|
|
68
|
+
let position = size;
|
|
69
|
+
while (position > 0) {
|
|
70
|
+
signal?.throwIfAborted();
|
|
71
|
+
const length = Math.min(64 * 1024, position);
|
|
72
|
+
position -= length;
|
|
73
|
+
const chunk = Buffer.allocUnsafe(length);
|
|
74
|
+
let offset = 0;
|
|
75
|
+
while (offset < length) {
|
|
76
|
+
const { bytesRead } = await file.read(
|
|
77
|
+
chunk,
|
|
78
|
+
offset,
|
|
79
|
+
length - offset,
|
|
80
|
+
position + offset,
|
|
81
|
+
);
|
|
82
|
+
if (!bytesRead)
|
|
83
|
+
throw new Error(
|
|
84
|
+
"Saved notes changed during the read. Retry the lookup.",
|
|
85
|
+
);
|
|
86
|
+
offset += bytesRead;
|
|
87
|
+
}
|
|
88
|
+
yield chunk;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @param {import("node:fs/promises").FileHandle} file @param {number} size @param {import("node:crypto").Hash} hash @param {AbortSignal} [signal] */
|
|
93
|
+
async function* reverseLines(file, size, hash, signal) {
|
|
94
|
+
/** @type {Buffer[]} */
|
|
95
|
+
let parts = [];
|
|
96
|
+
for await (const chunk of reverseChunks(file, size, signal)) {
|
|
97
|
+
hash.update(chunk);
|
|
98
|
+
let end = chunk.length;
|
|
99
|
+
for (let index = chunk.length - 1; index >= 0; index--) {
|
|
100
|
+
if (chunk[index] !== 10) continue;
|
|
101
|
+
const tail = chunk.subarray(index + 1, end);
|
|
102
|
+
// Long JSONL records span many chunks. Scan each byte once and join
|
|
103
|
+
// fragments only at the newline, rather than recopying a growing line.
|
|
104
|
+
if (parts.length) {
|
|
105
|
+
parts.push(tail);
|
|
106
|
+
yield Buffer.concat(parts.reverse());
|
|
107
|
+
parts = [];
|
|
108
|
+
} else yield tail;
|
|
109
|
+
end = index;
|
|
110
|
+
}
|
|
111
|
+
if (end) parts.push(chunk.subarray(0, end));
|
|
112
|
+
}
|
|
113
|
+
yield Buffer.concat(parts.reverse());
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Read only recorded session paths. Identity is session-wide; notes follow the active parent chain. */
|
|
117
|
+
/** @param {string} path @param {AbortSignal} [signal] @param {boolean} [history] @returns {Promise<import("./saved-session.js").SavedNotesSession>} */
|
|
118
|
+
export async function readSavedNotesSession(path, signal, history = false) {
|
|
119
|
+
signal?.throwIfAborted();
|
|
120
|
+
const file = await open(path, "r");
|
|
121
|
+
try {
|
|
122
|
+
const before = await file.stat();
|
|
123
|
+
const hash = createHash("sha256");
|
|
124
|
+
/** @type {import("@earendil-works/pi-coding-agent").SessionEntry[]} */
|
|
125
|
+
const entries = [];
|
|
126
|
+
/** @type {import("@earendil-works/pi-coding-agent").SessionEntry[]} */
|
|
127
|
+
const branch = [];
|
|
128
|
+
/** @type {Map<string, {base:string|null,depth:number}[]>} */
|
|
129
|
+
const archived = new Map();
|
|
130
|
+
/** @type {string | undefined} */
|
|
131
|
+
let threadId;
|
|
132
|
+
/** @type {string | null | undefined} */
|
|
133
|
+
let target;
|
|
134
|
+
for await (const line of reverseLines(file, before.size, hash, signal)) {
|
|
135
|
+
signal?.throwIfAborted();
|
|
136
|
+
if (!line.length) continue;
|
|
137
|
+
/** @type {unknown} */
|
|
138
|
+
let entry;
|
|
139
|
+
try {
|
|
140
|
+
entry = JSON.parse(line.toString("utf8"));
|
|
141
|
+
} catch {
|
|
142
|
+
throw new Error(
|
|
143
|
+
"Saved notes are being updated. Retry after the session settles.",
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
if (isSessionHeader(entry)) {
|
|
147
|
+
threadId = entry.id;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (!isRecord(entry)) throw new Error("Invalid saved session record");
|
|
151
|
+
if (target === undefined) target = entry.id;
|
|
152
|
+
const active = entry.id === target;
|
|
153
|
+
if (active) target = entry.parentId;
|
|
154
|
+
if (history) {
|
|
155
|
+
// Pi appends descendants after their parents, including Tree manifests
|
|
156
|
+
// after their archived leaves. Follow only active manifests' ancestry.
|
|
157
|
+
const paths = archived.get(entry.id) ?? [];
|
|
158
|
+
archived.delete(entry.id);
|
|
159
|
+
for (const path of paths) {
|
|
160
|
+
if (++path.depth >= MAX_ARCHIVE_DEPTH || entry.parentId === path.base)
|
|
161
|
+
continue;
|
|
162
|
+
if (entry.parentId !== null) {
|
|
163
|
+
const parents = archived.get(entry.parentId) ?? [];
|
|
164
|
+
parents.push(path);
|
|
165
|
+
archived.set(entry.parentId, parents);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (
|
|
169
|
+
active &&
|
|
170
|
+
isCustom(entry) &&
|
|
171
|
+
entry.customType === TREE_ARCHIVE_ENTRY_TYPE &&
|
|
172
|
+
isTreeArchiveManifestData(entry.data) &&
|
|
173
|
+
entry.data.archivedLeafId !== entry.data.branchBaseId
|
|
174
|
+
) {
|
|
175
|
+
const paths = archived.get(entry.data.archivedLeafId) ?? [];
|
|
176
|
+
paths.push({ base: entry.data.branchBaseId, depth: 0 });
|
|
177
|
+
archived.set(entry.data.archivedLeafId, paths);
|
|
178
|
+
}
|
|
179
|
+
if (
|
|
180
|
+
active ||
|
|
181
|
+
paths.length ||
|
|
182
|
+
(isCustom(entry) && SHARING_ENTRIES.has(entry.customType))
|
|
183
|
+
)
|
|
184
|
+
entries.push(entry);
|
|
185
|
+
if (active) branch.push(entry);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (isCustom(entry)) {
|
|
189
|
+
if (SHARING_ENTRIES.has(entry.customType)) entries.push(entry);
|
|
190
|
+
else if (active && NOTE_ENTRIES.has(entry.customType))
|
|
191
|
+
branch.push(entry);
|
|
192
|
+
else continue;
|
|
193
|
+
} else if (active && isHandoff(entry)) branch.push(entry);
|
|
194
|
+
else continue;
|
|
195
|
+
}
|
|
196
|
+
// Pruning replaces the path. An open descriptor alone still sees the old inode.
|
|
197
|
+
const after = await stat(path);
|
|
198
|
+
if (
|
|
199
|
+
after.dev !== before.dev ||
|
|
200
|
+
after.ino !== before.ino ||
|
|
201
|
+
after.size < before.size ||
|
|
202
|
+
(after.size === before.size &&
|
|
203
|
+
(after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs))
|
|
204
|
+
)
|
|
205
|
+
throw new Error("Saved notes changed during the read. Retry the lookup.");
|
|
206
|
+
if (after.size > before.size) {
|
|
207
|
+
// Flushed Pi sessions append. Keep the original leaf/byte boundary,
|
|
208
|
+
// but prove its prefix did not change, including abandoned identities.
|
|
209
|
+
// Hash the same reverse chunks, without retaining the whole JSONL.
|
|
210
|
+
const verified = createHash("sha256");
|
|
211
|
+
for await (const chunk of reverseChunks(file, before.size, signal))
|
|
212
|
+
verified.update(chunk);
|
|
213
|
+
if (hash.digest("hex") !== verified.digest("hex"))
|
|
214
|
+
throw new Error(
|
|
215
|
+
"Saved notes changed during the read. Retry the lookup.",
|
|
216
|
+
);
|
|
217
|
+
const current = await stat(path);
|
|
218
|
+
if (
|
|
219
|
+
current.dev !== before.dev ||
|
|
220
|
+
current.ino !== before.ino ||
|
|
221
|
+
current.size < after.size ||
|
|
222
|
+
(current.size === after.size &&
|
|
223
|
+
(current.mtimeMs !== after.mtimeMs ||
|
|
224
|
+
current.ctimeMs !== after.ctimeMs))
|
|
225
|
+
)
|
|
226
|
+
throw new Error(
|
|
227
|
+
"Saved notes changed during the read. Retry the lookup.",
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
if (!threadId || (target !== undefined && target !== null))
|
|
231
|
+
throw new Error("Saved notes have an incomplete session branch");
|
|
232
|
+
return {
|
|
233
|
+
threadId,
|
|
234
|
+
entries: entries.reverse(),
|
|
235
|
+
branch: branch.reverse(),
|
|
236
|
+
savedAt: before.mtimeMs,
|
|
237
|
+
};
|
|
238
|
+
} finally {
|
|
239
|
+
await file.close();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { Check } from "typebox/value";
|
|
4
|
+
|
|
5
|
+
export { readSavedNotesSession } from "./saved-session.mjs";
|
|
6
|
+
export interface SavedNotesSession {
|
|
7
|
+
threadId: string;
|
|
8
|
+
entries: readonly SessionEntry[];
|
|
9
|
+
branch: readonly SessionEntry[];
|
|
10
|
+
savedAt?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const SavedEntry = Type.Object({
|
|
14
|
+
type: Type.String(),
|
|
15
|
+
id: Type.String(),
|
|
16
|
+
parentId: Type.Union([Type.String(), Type.Null()]),
|
|
17
|
+
timestamp: Type.String(),
|
|
18
|
+
});
|
|
19
|
+
const SavedSession = Type.Object({
|
|
20
|
+
threadId: Type.String({ minLength: 1 }),
|
|
21
|
+
entries: Type.Array(SavedEntry),
|
|
22
|
+
branch: Type.Array(SavedEntry),
|
|
23
|
+
savedAt: Type.Optional(Type.Number()),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** Remote loaders carry data, not authority. Native identity is checked by the graph reader. */
|
|
27
|
+
export function validateSavedNotesSession(value: unknown): SavedNotesSession {
|
|
28
|
+
if (!Check(SavedSession, value))
|
|
29
|
+
throw new Error(
|
|
30
|
+
"Saved session response is invalid. Update Notes on the other machine and retry.",
|
|
31
|
+
);
|
|
32
|
+
for (const entry of [...value.entries, ...value.branch]) {
|
|
33
|
+
if (
|
|
34
|
+
entry.type === "custom" &&
|
|
35
|
+
(!("customType" in entry) ||
|
|
36
|
+
typeof entry.customType !== "string" ||
|
|
37
|
+
!("data" in entry))
|
|
38
|
+
)
|
|
39
|
+
throw new Error("Invalid saved session custom record");
|
|
40
|
+
if (
|
|
41
|
+
entry.type === "message" &&
|
|
42
|
+
(!("message" in entry) ||
|
|
43
|
+
!entry.message ||
|
|
44
|
+
typeof entry.message !== "object")
|
|
45
|
+
)
|
|
46
|
+
throw new Error("Invalid saved session message record");
|
|
47
|
+
}
|
|
48
|
+
// The same persisted entry envelope is accepted by the Node reader. Feature readers
|
|
49
|
+
// validate their own custom data, including ownership and note receipts.
|
|
50
|
+
return value as SavedNotesSession;
|
|
51
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { type Static, Type } from "typebox";
|
|
2
|
+
import { Check } from "typebox/value";
|
|
3
|
+
import {
|
|
4
|
+
CONTEXT_AGENT_PATTERN,
|
|
5
|
+
canonicalAgentName,
|
|
6
|
+
canonicalContextIdentity,
|
|
7
|
+
contextStorageAgentName,
|
|
8
|
+
pinnedContextIdentity,
|
|
9
|
+
} from "./agent-identity.js";
|
|
10
|
+
import type { SavedNotesSession } from "./saved-session.js";
|
|
11
|
+
|
|
12
|
+
const Agent = Type.String({ pattern: CONTEXT_AGENT_PATTERN });
|
|
13
|
+
export const Identity = Type.Object({
|
|
14
|
+
protocol: Type.Literal(1),
|
|
15
|
+
sessionId: Type.String(),
|
|
16
|
+
threadId: Type.String(),
|
|
17
|
+
agentName: Agent,
|
|
18
|
+
storageAgentName: Type.Optional(Agent),
|
|
19
|
+
storage: Type.Optional(
|
|
20
|
+
Type.Union([Type.Literal("session"), Type.Literal("remote")]),
|
|
21
|
+
),
|
|
22
|
+
routing: Type.Optional(Type.Unknown()),
|
|
23
|
+
});
|
|
24
|
+
export const Member = Type.Object({
|
|
25
|
+
threadId: Type.String(),
|
|
26
|
+
sessionId: Type.String(),
|
|
27
|
+
agentName: Agent,
|
|
28
|
+
machine: Type.String(),
|
|
29
|
+
sessionFile: Type.String(),
|
|
30
|
+
});
|
|
31
|
+
export const Plan = Type.Object({
|
|
32
|
+
controllerSessionId: Type.String(),
|
|
33
|
+
targetSessionId: Type.String(),
|
|
34
|
+
context: Type.Optional(
|
|
35
|
+
Type.Object({
|
|
36
|
+
controller: Identity,
|
|
37
|
+
target: Identity,
|
|
38
|
+
alias: Agent,
|
|
39
|
+
controllerAlias: Agent,
|
|
40
|
+
controllerFile: Type.Optional(Type.String()),
|
|
41
|
+
controllerMachine: Type.Optional(Type.String()),
|
|
42
|
+
controllerNotes: Type.Unknown(),
|
|
43
|
+
targetNotes: Type.Unknown(),
|
|
44
|
+
}),
|
|
45
|
+
),
|
|
46
|
+
});
|
|
47
|
+
export const Route = Type.Object({
|
|
48
|
+
plan: Plan,
|
|
49
|
+
machine: Type.String(),
|
|
50
|
+
sessionFile: Type.String(),
|
|
51
|
+
phase: Type.Union([Type.Literal("pending"), Type.Literal("ready")]),
|
|
52
|
+
detached: Type.Optional(
|
|
53
|
+
Type.Object({ context: Type.Optional(Type.Unknown()) }),
|
|
54
|
+
),
|
|
55
|
+
});
|
|
56
|
+
export const Detachment = Type.Object({
|
|
57
|
+
plan: Plan,
|
|
58
|
+
context: Type.Optional(Type.Unknown()),
|
|
59
|
+
});
|
|
60
|
+
export const Snapshot = Type.Object({
|
|
61
|
+
protocol: Type.Literal(1),
|
|
62
|
+
timestamp: Type.Number(),
|
|
63
|
+
files: Type.Array(
|
|
64
|
+
Type.Object({
|
|
65
|
+
path: Type.String(),
|
|
66
|
+
text: Type.String(),
|
|
67
|
+
createdAt: Type.Number(),
|
|
68
|
+
updatedAt: Type.Number(),
|
|
69
|
+
operation: Type.Union([
|
|
70
|
+
Type.Literal("local_append_overlay"),
|
|
71
|
+
Type.Literal("local_replacement"),
|
|
72
|
+
]),
|
|
73
|
+
}),
|
|
74
|
+
),
|
|
75
|
+
});
|
|
76
|
+
export const Parent = Type.Object({
|
|
77
|
+
transport: Type.Literal("shepherdr"),
|
|
78
|
+
parent: Type.String(),
|
|
79
|
+
savedParent: Type.Optional(
|
|
80
|
+
Type.Object({ machine: Type.String(), sessionFile: Type.String() }),
|
|
81
|
+
),
|
|
82
|
+
});
|
|
83
|
+
export type Identity = Static<typeof Identity>;
|
|
84
|
+
|
|
85
|
+
/** Ordinary family membership is immutable, explicit and native-session owned. */
|
|
86
|
+
export function savedFamilyIdentity(
|
|
87
|
+
session: Pick<SavedNotesSession, "threadId" | "entries">,
|
|
88
|
+
): Identity | undefined {
|
|
89
|
+
const identity = savedNotesIdentity(session);
|
|
90
|
+
if (
|
|
91
|
+
identity.storage === undefined ||
|
|
92
|
+
!session.entries.some(
|
|
93
|
+
(entry) =>
|
|
94
|
+
entry.type === "custom" &&
|
|
95
|
+
entry.customType === "codex-context-agent" &&
|
|
96
|
+
Check(Identity, entry.data) &&
|
|
97
|
+
entry.data.threadId === session.threadId,
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
return;
|
|
101
|
+
return identity;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Persisted sharing is session-scoped. Forks never inherit the source agent's address. */
|
|
105
|
+
export function savedNotesIdentity(
|
|
106
|
+
session: Pick<SavedNotesSession, "threadId" | "entries">,
|
|
107
|
+
): Identity {
|
|
108
|
+
let found: Identity | undefined;
|
|
109
|
+
for (const entry of session.entries) {
|
|
110
|
+
if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
|
|
111
|
+
continue;
|
|
112
|
+
if (!Check(Identity, entry.data))
|
|
113
|
+
throw new Error("Invalid saved notes identity");
|
|
114
|
+
if (entry.data.threadId !== session.threadId) continue;
|
|
115
|
+
if (found) throw new Error("Conflicting saved notes identities");
|
|
116
|
+
found = entry.data;
|
|
117
|
+
}
|
|
118
|
+
return canonicalContextIdentity(
|
|
119
|
+
found ??
|
|
120
|
+
pinnedContextIdentity(session.threadId, session.entries) ?? {
|
|
121
|
+
protocol: 1,
|
|
122
|
+
threadId: session.threadId,
|
|
123
|
+
sessionId: session.threadId,
|
|
124
|
+
agentName: canonicalAgentName(session.threadId),
|
|
125
|
+
},
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function sameOwner(a: Identity, b: Identity): boolean {
|
|
130
|
+
return (
|
|
131
|
+
a.threadId === b.threadId &&
|
|
132
|
+
a.sessionId === b.sessionId &&
|
|
133
|
+
contextStorageAgentName(a) === contextStorageAgentName(b)
|
|
134
|
+
);
|
|
135
|
+
}
|