@mmon-co/ncept-local 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,66 @@
1
+ import { type ChatContext, type ContentDigest, type ExactPatchRef, type NodeId, type Observation, type PatchContent, type PlatformEvent, type ProfileLogEntry, type Program, type SurfaceId, type Theory, type Transcript, type TranscriptSpan } from "@mmon-co/ncept-core";
2
+ import type { ProfileDirectory } from "./directory.js";
3
+ import type { HostSession, Model } from "./host.js";
4
+ import type { ValidatedProfile } from "./exchange.js";
5
+ export interface LocalSession extends HostSession {
6
+ readonly surface: SurfaceId;
7
+ readonly about: readonly NodeId[];
8
+ readonly closed: boolean;
9
+ readonly mission?: string;
10
+ readonly parent?: string;
11
+ }
12
+ export declare function platform(payload: unknown, surface?: SurfaceId): Observation;
13
+ export declare function localPayload(entry: ProfileLogEntry, kind: string): Record<string, unknown> | undefined;
14
+ export declare function localSettings(profile: ValidatedProfile): Record<string, unknown>;
15
+ export declare function sessionStates(profile: ValidatedProfile): readonly LocalSession[];
16
+ export declare function transcript(profile: ValidatedProfile, surface: SurfaceId, span?: TranscriptSpan): Transcript;
17
+ export declare class Runtime<S> {
18
+ readonly profile: ProfileDirectory;
19
+ readonly theories: readonly Theory<S>[];
20
+ readonly model: Model;
21
+ timezone: string;
22
+ constructor(profile: ProfileDirectory, theories: readonly Theory<S>[], model: Model, timezone: string);
23
+ snapshot(ref?: ExactPatchRef): Promise<{
24
+ profile: ValidatedProfile;
25
+ theory: Theory<S, Record<string, unknown>>;
26
+ graph: import("@mmon-co/ncept-core").ResolvedGraph;
27
+ now: string;
28
+ state: S;
29
+ observations: readonly Observation<unknown>[];
30
+ bundle: import("@mmon-co/ncept-core").ClosedPatchBundle;
31
+ }>;
32
+ observations(profile: ValidatedProfile, now: string): readonly Observation[];
33
+ prepare<T>(program: Program<T>, session?: LocalSession, snapshot?: Awaited<ReturnType<Runtime<S>["snapshot"]>>): Promise<{
34
+ value: T;
35
+ entries: Observation<unknown>[];
36
+ }>;
37
+ execute<T>(program: Program<T>, session?: LocalSession, view?: Awaited<ReturnType<Runtime<S>["snapshot"]>>): Promise<T>;
38
+ event(event: PlatformEvent, session?: LocalSession): Promise<{
39
+ value: void;
40
+ entries: Observation<unknown>[];
41
+ }>;
42
+ context(session: LocalSession): Promise<ChatContext<S>>;
43
+ prospective(content: PatchContent): Promise<{
44
+ profile: {
45
+ patches: import("@mmon-co/ncept-core").ClosedPatchBundle;
46
+ manifest: {
47
+ personal: ExactPatchRef;
48
+ format: 1;
49
+ log?: ContentDigest;
50
+ theory: import("@mmon-co/ncept-core").TheoryRequirement;
51
+ theories: readonly string[];
52
+ sessions: Readonly<Record<string, string>>;
53
+ };
54
+ blobs: ReadonlyMap<ContentDigest, Uint8Array>;
55
+ sessions: ReadonlyMap<string, string>;
56
+ log: readonly ProfileLogEntry[];
57
+ };
58
+ bundle: import("@mmon-co/ncept-core").ClosedPatchBundle;
59
+ graph: import("@mmon-co/ncept-core").ResolvedGraph;
60
+ observations: readonly Observation<unknown>[];
61
+ state: S;
62
+ theory: Theory<S, Record<string, unknown>>;
63
+ now: string;
64
+ }>;
65
+ content(): Promise<PatchContent>;
66
+ }
@@ -0,0 +1,338 @@
1
+ import { bundleForRevision, candidateRevision, effectiveObservations, isObservation, isContentDigest, readTheoryState, resolvePatchBundle, resolveTheory, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
2
+ import { object, parsePiSession, piActiveBranch } from "./sessions.js";
3
+ import { learnerDayAt } from "./days.js";
4
+ import { isMaterial, isObjectIdentity, isSurface, modeEntry, nodeIds, nonempty } from "./inputs.js";
5
+ export function platform(payload, surface) {
6
+ return {
7
+ id: `obs-${crypto.randomUUID()}`,
8
+ at: new Date().toISOString(),
9
+ by: "platform",
10
+ payload,
11
+ ...(surface === undefined ? {} : { surface }),
12
+ };
13
+ }
14
+ export function localPayload(entry, kind) {
15
+ return isObservation(entry) && entry.by === "platform" && object(entry.payload) && entry.payload.kind === kind
16
+ ? entry.payload
17
+ : undefined;
18
+ }
19
+ export function localSettings(profile) {
20
+ const settings = {};
21
+ for (const entry of profile.log)
22
+ Object.assign(settings, localPayload(entry, "local.config"));
23
+ return settings;
24
+ }
25
+ export function sessionStates(profile) {
26
+ const states = new Map();
27
+ for (const entry of profile.log) {
28
+ const payload = localPayload(entry, "local.session");
29
+ if (payload && object(payload.session)) {
30
+ const session = payload.session;
31
+ if (!nonempty(session.id) ||
32
+ !isSurface(session.surface) ||
33
+ typeof session.mode !== "string" ||
34
+ typeof session.closed !== "boolean")
35
+ throw new Error("Invalid local Session state");
36
+ states.set(session.id, {
37
+ id: session.id,
38
+ surface: session.surface,
39
+ mode: session.mode,
40
+ closed: session.closed,
41
+ about: nodeIds(session.about),
42
+ ...(session.entry === undefined ? {} : { entry: modeEntry(session.entry) }),
43
+ ...(typeof session.mission === "string" ? { mission: session.mission } : {}),
44
+ ...(typeof session.parent === "string" ? { parent: session.parent } : {}),
45
+ });
46
+ }
47
+ }
48
+ return [...states.values()];
49
+ }
50
+ export function transcript(profile, surface, span) {
51
+ const source = profile.sessions.get(surface);
52
+ if (source === undefined)
53
+ return { surface, span: span ?? { from: "", to: "" }, turns: [] };
54
+ const session = parsePiSession(source);
55
+ const selected = piActiveBranch(session.entries);
56
+ let turns = selected.flatMap((entry) => {
57
+ const message = entry.message;
58
+ if (!message || (message.role !== "user" && message.role !== "assistant"))
59
+ return [];
60
+ const content = message.content;
61
+ return [
62
+ {
63
+ id: entry.id,
64
+ at: entry.timestamp,
65
+ speaker: message.role === "user" ? { kind: "learner" } : { kind: "tutor" },
66
+ text: typeof content === "string"
67
+ ? content
68
+ : content
69
+ .filter((part) => part.type === "text")
70
+ .map((part) => part.text)
71
+ .join("\n"),
72
+ ...(message.role === "assistant"
73
+ ? {
74
+ toolNames: message.content.filter((part) => part.type === "toolCall").map((part) => part.name),
75
+ }
76
+ : {}),
77
+ },
78
+ ];
79
+ });
80
+ if (span && turns.length === 0 && span.from === "" && span.to === "")
81
+ return { surface, span, turns };
82
+ if (span) {
83
+ const from = turns.findIndex(({ id }) => id === span.from);
84
+ const to = turns.findIndex(({ id }) => id === span.to);
85
+ if (from < 0 || to < from)
86
+ throw new Error("Transcript span is not on the selected branch");
87
+ turns = turns.slice(from, to + 1);
88
+ }
89
+ return { surface, span: span ?? { from: turns[0]?.id ?? "", to: turns.at(-1)?.id ?? "" }, turns };
90
+ }
91
+ function matches(observation, select) {
92
+ return ((select.surface === undefined || observation.surface === select.surface) &&
93
+ (select.by === undefined ||
94
+ (select.by === "platform" || observation.by === "platform"
95
+ ? select.by === observation.by
96
+ : select.by.theory === observation.by.theory && select.by.version === observation.by.version)) &&
97
+ (select.about === undefined || select.about.some((node) => observation.about?.includes(node))) &&
98
+ (select.nodes === undefined || select.nodes.some((node) => observation.nodes?.includes(node))));
99
+ }
100
+ export class Runtime {
101
+ profile;
102
+ theories;
103
+ model;
104
+ timezone;
105
+ constructor(profile, theories, model, timezone) {
106
+ this.profile = profile;
107
+ this.theories = theories;
108
+ this.model = model;
109
+ this.timezone = timezone;
110
+ }
111
+ async snapshot(ref) {
112
+ const profile = await this.profile.read();
113
+ const theory = resolveTheory(profile.manifest.theory, this.theories);
114
+ let bundle = profile.patches;
115
+ if (ref && !sameExactPatchRef(ref, bundle.terminal)) {
116
+ const files = await this.profile.files();
117
+ const contents = new Map();
118
+ for (const [path, bytes] of files)
119
+ if (path.startsWith("patches/")) {
120
+ const digest = path.slice(8, -5);
121
+ if (!isContentDigest(digest))
122
+ throw new Error("Invalid revision filename");
123
+ contents.set(digest, JSON.parse(new TextDecoder().decode(bytes)));
124
+ }
125
+ bundle = bundleForRevision(ref, contents);
126
+ }
127
+ const graph = resolvePatchBundle(bundle, new Set(["local"]));
128
+ const now = new Date().toISOString();
129
+ const observations = this.observations(profile, now);
130
+ return {
131
+ profile,
132
+ theory,
133
+ graph,
134
+ now,
135
+ state: readTheoryState(theory, graph, observations, now),
136
+ observations,
137
+ bundle,
138
+ };
139
+ }
140
+ observations(profile, now) {
141
+ const standing = new Map();
142
+ for (const entry of profile.log) {
143
+ const receipt = localPayload(entry, "local.acceptance");
144
+ if (!receipt || typeof receipt.surface !== "string" || !Array.isArray(receipt.observations))
145
+ continue;
146
+ const source = profile.sessions.get(receipt.surface);
147
+ let selected = true;
148
+ if (source && typeof receipt.entry === "string") {
149
+ const session = parsePiSession(source);
150
+ selected = piActiveBranch(session.entries).some((entry) => entry.id === receipt.entry);
151
+ }
152
+ for (const id of receipt.observations)
153
+ if (typeof id === "string")
154
+ standing.set(id, selected ? "selected" : "abandoned");
155
+ }
156
+ return effectiveObservations(profile.log.filter(isObservation).map((observation) => ({
157
+ ...observation,
158
+ standing: standing.get(observation.id) ?? "unscoped",
159
+ learnerDay: learnerDayAt(observation.at, this.timezone),
160
+ ...(object(observation.payload) && object(observation.payload.material)
161
+ ? {
162
+ materialPresent: resolvePatchBundle(profile.patches).materials.some((material) => object(observation.payload) &&
163
+ object(observation.payload.material) &&
164
+ material.id === observation.payload.material.id &&
165
+ material.playground === observation.payload.material.playground),
166
+ }
167
+ : {}),
168
+ })), now);
169
+ }
170
+ async prepare(program, session, snapshot) {
171
+ const view = snapshot ?? (await this.snapshot());
172
+ const pending = [];
173
+ const materialObjects = view.profile.log.flatMap((entry) => {
174
+ const value = localPayload(entry, "local.material");
175
+ return value && value.surface === session?.surface && isObjectIdentity(value.object) && isMaterial(value.material)
176
+ ? [{ id: value.object, material: value.material }]
177
+ : [];
178
+ });
179
+ let sent;
180
+ for (;;) {
181
+ const step = program.next(sent);
182
+ if (step.done) {
183
+ const receipt = pending.length && session
184
+ ? [
185
+ platform({
186
+ kind: "local.acceptance",
187
+ surface: session.surface,
188
+ entry: view.profile.sessions.has(session.surface)
189
+ ? parsePiSession(view.profile.sessions.get(session.surface) ?? "").entries.at(-1)?.id
190
+ : undefined,
191
+ observations: pending.map(({ id }) => id),
192
+ }),
193
+ ]
194
+ : [];
195
+ return { value: step.value, entries: [...pending, ...receipt] };
196
+ }
197
+ const request = step.value;
198
+ if (request.kind === "write") {
199
+ const write = request.observation;
200
+ if (["standing", "materialPresent", "learnerDay"].some((key) => Object.hasOwn(write, key)))
201
+ throw new Error("Programs cannot author host-read observation context");
202
+ const observation = {
203
+ ...write,
204
+ id: `obs-${crypto.randomUUID()}`,
205
+ at: write.at ?? view.now,
206
+ by: { theory: view.theory.id, version: view.theory.version },
207
+ };
208
+ if (!isObservation(observation))
209
+ throw new Error("Invalid Theory observation");
210
+ pending.push(observation);
211
+ sent = observation.id;
212
+ }
213
+ else if (request.kind === "judge") {
214
+ sent = await this.model(request);
215
+ }
216
+ else if (request.kind === "assess") {
217
+ let response = typeof request.input.response === "string" ? request.input.response : "";
218
+ if (request.message !== undefined) {
219
+ if (!session)
220
+ throw new Error("Assessment requires a Session");
221
+ const original = transcript(view.profile, session.surface).turns.find(({ id }) => id === request.message);
222
+ if (original?.speaker.kind !== "learner")
223
+ throw new Error("Assessment source must be a selected learner message");
224
+ response = original.text;
225
+ }
226
+ const schema = {
227
+ type: "object",
228
+ additionalProperties: false,
229
+ required: Object.keys(request.criteria),
230
+ properties: Object.fromEntries(Object.keys(request.criteria).map((key) => [key, { type: "number", minimum: 0, maximum: 1 }])),
231
+ };
232
+ const probabilities = await this.model({ ...request, input: { ...request.input, response }, schema });
233
+ if (!object(probabilities) ||
234
+ Object.keys(request.criteria).some((key) => typeof probabilities[key] !== "number" || probabilities[key] < 0 || probabilities[key] > 1))
235
+ throw new Error("Invalid assessment probabilities");
236
+ sent = { response, probabilities };
237
+ }
238
+ else {
239
+ const select = request.select;
240
+ switch (select.kind) {
241
+ case "patch": {
242
+ const patch = select.ref ? await this.snapshot(select.ref) : view;
243
+ sent = { patch: patch.graph.terminal, graph: patch.graph };
244
+ break;
245
+ }
246
+ case "observations":
247
+ sent = [...view.observations, ...pending].filter((observation) => matches(observation, select));
248
+ break;
249
+ case "transcript":
250
+ sent = transcript(view.profile, select.surface, select.span);
251
+ break;
252
+ case "objects":
253
+ sent = materialObjects.map(({ id, material }) => ({
254
+ id,
255
+ name: typeof material.meta.filename === "string" ? material.meta.filename : material.id,
256
+ mime: material.content.mediaType,
257
+ bytes: view.profile.blobs.get(material.content.hash)?.length ?? 0,
258
+ }));
259
+ break;
260
+ case "object": {
261
+ const item = materialObjects.find(({ id }) => id === select.object);
262
+ const bytes = item && view.profile.blobs.get(item.material.content.hash);
263
+ if (!item || !bytes)
264
+ throw new Error("Unknown Session object");
265
+ sent =
266
+ item.material.content.mediaType.startsWith("text/") ||
267
+ item.material.content.mediaType === "application/json"
268
+ ? { kind: "text", text: new TextDecoder().decode(bytes) }
269
+ : { kind: "bytes", base64: Buffer.from(bytes).toString("base64") };
270
+ break;
271
+ }
272
+ }
273
+ }
274
+ }
275
+ }
276
+ async execute(program, session, view) {
277
+ const result = await this.prepare(program, session, view);
278
+ await this.profile.appendLog(result.entries);
279
+ return result.value;
280
+ }
281
+ async event(event, session) {
282
+ const view = await this.snapshot();
283
+ if (event.kind === "outcome") {
284
+ const payload = event.payload;
285
+ if (!object(payload) || typeof payload.kind !== "string" || !view.theory.outcomes[payload.kind]?.(payload))
286
+ throw new Error("Invalid Theory outcome");
287
+ }
288
+ return this.prepare(view.theory.event(event, view), session, view);
289
+ }
290
+ async context(session) {
291
+ const view = await this.snapshot();
292
+ return {
293
+ ...view,
294
+ surface: session.surface,
295
+ mode: session.mode,
296
+ about: session.about,
297
+ ...(session.entry === undefined ? {} : { entry: session.entry }),
298
+ tutorMessages: transcript(view.profile, session.surface)
299
+ .turns.filter(({ speaker }) => speaker.kind === "tutor")
300
+ .map(({ text }) => text),
301
+ sessionObservations: view.observations
302
+ .filter(({ surface, by }) => surface === session.surface && by !== "platform")
303
+ .map(({ id }) => id),
304
+ openSurfaces: sessionStates(view.profile)
305
+ .filter(({ closed }) => !closed)
306
+ .map(({ surface, about }) => ({ surface, about })),
307
+ };
308
+ }
309
+ async prospective(content) {
310
+ const view = await this.snapshot();
311
+ const revision = candidateRevision(view.graph.terminal.identity, content);
312
+ const contents = new Map(view.bundle.revisions.map((revision) => [revision.ref.digest, revisionContent(revision)]));
313
+ contents.set(revision.ref.digest, content);
314
+ const bundle = bundleForRevision(revision.ref, contents);
315
+ const graph = resolvePatchBundle(bundle, new Set(["local"]));
316
+ const profile = {
317
+ ...view.profile,
318
+ patches: bundle,
319
+ manifest: { ...view.profile.manifest, personal: revision.ref },
320
+ };
321
+ const observations = this.observations(profile, view.now);
322
+ return {
323
+ ...view,
324
+ profile,
325
+ bundle,
326
+ graph,
327
+ observations,
328
+ state: readTheoryState(view.theory, graph, observations, view.now),
329
+ };
330
+ }
331
+ async content() {
332
+ const view = await this.snapshot();
333
+ const revision = view.bundle.revisions.find(({ ref }) => sameExactPatchRef(ref, view.bundle.terminal));
334
+ if (!revision)
335
+ throw new Error("Missing personal revision");
336
+ return revisionContent(revision);
337
+ }
338
+ }
@@ -0,0 +1,80 @@
1
+ /** The exchange subset of pi 1.5's version-3 session format. Provider metadata is retained. */
2
+ export interface PiSessionHeader {
3
+ type: "session";
4
+ version: 3;
5
+ id: string;
6
+ timestamp: string;
7
+ cwd: string;
8
+ parentSession?: string;
9
+ [key: string]: unknown;
10
+ }
11
+ export type PiContent = {
12
+ type: "text";
13
+ text: string;
14
+ [key: string]: unknown;
15
+ } | {
16
+ type: "image";
17
+ data: string;
18
+ mimeType: string;
19
+ [key: string]: unknown;
20
+ } | {
21
+ type: "thinking";
22
+ thinking: string;
23
+ [key: string]: unknown;
24
+ } | {
25
+ type: "toolCall";
26
+ id: string;
27
+ name: string;
28
+ arguments: Record<string, unknown>;
29
+ [key: string]: unknown;
30
+ };
31
+ export type PiMessage = {
32
+ role: "user";
33
+ content: string | readonly PiContent[];
34
+ timestamp: number;
35
+ [key: string]: unknown;
36
+ } | {
37
+ role: "assistant";
38
+ content: readonly PiContent[];
39
+ api: string;
40
+ provider: string;
41
+ model: string;
42
+ usage: Readonly<Record<string, unknown>>;
43
+ stopReason: string;
44
+ timestamp: number;
45
+ [key: string]: unknown;
46
+ } | {
47
+ role: "toolResult";
48
+ toolCallId: string;
49
+ toolName: string;
50
+ content: readonly PiContent[];
51
+ isError: boolean;
52
+ timestamp: number;
53
+ [key: string]: unknown;
54
+ };
55
+ export interface PiSessionEntry {
56
+ type: string;
57
+ id: string;
58
+ parentId: string | null;
59
+ timestamp: string;
60
+ /** Present on message entries; other pi entries are kept opaque, not discarded. */
61
+ message?: PiMessage;
62
+ [key: string]: unknown;
63
+ }
64
+ export interface PiMessageEntry extends PiSessionEntry {
65
+ type: "message";
66
+ message: PiMessage;
67
+ }
68
+ export interface PiSession {
69
+ header: PiSessionHeader;
70
+ entries: readonly PiSessionEntry[];
71
+ }
72
+ export declare function object(value: unknown): value is Record<string, unknown>;
73
+ export declare function parsePiSession(source: string): PiSession;
74
+ /** pi resumes at the last appended entry, including metadata after branching back.
75
+ * Return its ancestors in conversation order; complete sessions must contain every parent. */
76
+ export declare function piActiveBranch<T extends Pick<PiSessionEntry, "id" | "parentId">>(entries: readonly T[]): T[];
77
+ export declare function serializePiSession(session: PiSession): string;
78
+ export declare function relocatePiSession(source: string, cwd: string): string;
79
+ /** pi, not the surface id, chooses this filename. Persist its association in profile.json. */
80
+ export declare function piSessionFilename(header: PiSessionHeader): string;
@@ -0,0 +1,125 @@
1
+ export function object(value) {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3
+ }
4
+ function text(value) {
5
+ return typeof value === "string" && value.length > 0;
6
+ }
7
+ function timestamp(value) {
8
+ return text(value) && Number.isFinite(Date.parse(value));
9
+ }
10
+ function content(value) {
11
+ if (!object(value))
12
+ return false;
13
+ switch (value.type) {
14
+ case "text":
15
+ return typeof value.text === "string";
16
+ case "image":
17
+ return typeof value.data === "string" && text(value.mimeType);
18
+ case "thinking":
19
+ return typeof value.thinking === "string";
20
+ case "toolCall":
21
+ return text(value.id) && text(value.name) && object(value.arguments);
22
+ default:
23
+ return false;
24
+ }
25
+ }
26
+ function exchangeMessage(value) {
27
+ return !object(value) || value.role === "user" || value.role === "assistant" || value.role === "toolResult";
28
+ }
29
+ function message(value) {
30
+ if (!object(value) || typeof value.timestamp !== "number" || !Number.isFinite(value.timestamp))
31
+ return false;
32
+ if (value.role === "user" && typeof value.content === "string")
33
+ return true;
34
+ if (!Array.isArray(value.content) || !value.content.every(content))
35
+ return false;
36
+ if (value.role === "user")
37
+ return true;
38
+ if (value.role === "assistant")
39
+ return (text(value.api) && text(value.provider) && text(value.model) && object(value.usage) && text(value.stopReason));
40
+ return (value.role === "toolResult" && text(value.toolCallId) && text(value.toolName) && typeof value.isError === "boolean");
41
+ }
42
+ export function parsePiSession(source) {
43
+ const lines = source.trimEnd().split("\n");
44
+ const values = lines.map((line, index) => {
45
+ try {
46
+ return JSON.parse(line);
47
+ }
48
+ catch {
49
+ throw new Error("Invalid pi session JSON at line " + (index + 1));
50
+ }
51
+ });
52
+ const header = values.shift();
53
+ if (!object(header) ||
54
+ header.type !== "session" ||
55
+ header.version !== 3 ||
56
+ !text(header.id) ||
57
+ !timestamp(header.timestamp) ||
58
+ !text(header.cwd))
59
+ throw new Error("Invalid pi session header (expected version 3)");
60
+ const entries = [];
61
+ const ids = new Set();
62
+ for (const value of values) {
63
+ if (!object(value) ||
64
+ !text(value.type) ||
65
+ value.type === "session" ||
66
+ !text(value.id) ||
67
+ !(value.parentId === null || text(value.parentId)) ||
68
+ !timestamp(value.timestamp))
69
+ throw new Error("Invalid pi session entry at line " + (entries.length + 2));
70
+ if (ids.has(value.id))
71
+ throw new Error("Duplicate pi session entry: " + value.id);
72
+ // pi also stores bashExecution and similar roles in message entries; only the exchange's roles are typed.
73
+ if (value.type === "message" && exchangeMessage(value.message) && !message(value.message))
74
+ throw new Error("Invalid pi message at line " + (entries.length + 2));
75
+ ids.add(value.id);
76
+ // Narrow through the same entry guard, without coercing provider-specific fields.
77
+ const entry = {
78
+ ...value,
79
+ type: value.type,
80
+ id: value.id,
81
+ parentId: value.parentId,
82
+ timestamp: value.timestamp,
83
+ ...(value.type === "message" && message(value.message) ? { message: value.message } : {}),
84
+ };
85
+ entries.push(entry);
86
+ }
87
+ return {
88
+ header: { ...header, type: "session", version: 3, id: header.id, timestamp: header.timestamp, cwd: header.cwd },
89
+ entries,
90
+ };
91
+ }
92
+ /** pi resumes at the last appended entry, including metadata after branching back.
93
+ * Return its ancestors in conversation order; complete sessions must contain every parent. */
94
+ export function piActiveBranch(entries) {
95
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
96
+ const chain = [];
97
+ const seen = new Set();
98
+ let id = entries.at(-1)?.id ?? null;
99
+ while (id !== null) {
100
+ if (seen.has(id))
101
+ throw new Error("Cyclic pi conversation");
102
+ seen.add(id);
103
+ const entry = byId.get(id);
104
+ if (!entry)
105
+ throw new Error("Incomplete pi conversation branch");
106
+ chain.push(entry);
107
+ id = entry.parentId;
108
+ }
109
+ return chain.reverse();
110
+ }
111
+ export function serializePiSession(session) {
112
+ const source = [session.header, ...session.entries].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
113
+ parsePiSession(source);
114
+ return source;
115
+ }
116
+ export function relocatePiSession(source, cwd) {
117
+ const session = parsePiSession(source);
118
+ return serializePiSession({ ...session, header: { ...session.header, cwd } });
119
+ }
120
+ /** pi, not the surface id, chooses this filename. Persist its association in profile.json. */
121
+ export function piSessionFilename(header) {
122
+ if (!/^[a-zA-Z0-9-]+$/.test(header.id) || !timestamp(header.timestamp))
123
+ throw new Error("Invalid pi session identity");
124
+ return header.timestamp.replace(/[:.]/g, "-") + "_" + header.id + ".jsonl";
125
+ }
package/dist/tar.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export type ProfileFiles = ReadonlyMap<string, Uint8Array>;
2
+ export declare function encodeTar(files: ProfileFiles): Uint8Array;
3
+ export declare function decodeTar(bytes: Uint8Array): Map<string, Uint8Array>;