@mmon-co/ncept-local 0.0.0-stage → 0.2.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,219 @@
1
+ import { attachmentDigest, notebookBundleForRevision, isContentDigest, isPatchId, isProfileLogEntry, mergeProfileLogs, migrateTheoryProfile, resolveTheory, revisionDigest, } from "@mmon-co/ncept-core";
2
+ import { object, parsePiSession, relocatePiSession } from "./sessions.js";
3
+ import { decodeTar, encodeTar } from "./tar.js";
4
+ export const DEFAULT_THEORY_PACKAGES = ["@mmon-co/ncept-default-theory"];
5
+ export const DEFAULT_THEORY_REQUIREMENT = { theory: "default", range: "~1.0" };
6
+ export const utf8 = new TextEncoder();
7
+ const decoder = new TextDecoder("utf-8", { fatal: true });
8
+ export function jsonBytes(value) {
9
+ return utf8.encode(JSON.stringify(value) + "\n");
10
+ }
11
+ function json(bytes, path) {
12
+ if (!bytes)
13
+ throw new Error("Missing Profile file: " + path);
14
+ try {
15
+ return JSON.parse(decoder.decode(bytes));
16
+ }
17
+ catch {
18
+ throw new Error("Invalid JSON in " + path);
19
+ }
20
+ }
21
+ function exact(value) {
22
+ return object(value) && isPatchId(value.identity) && isContentDigest(value.digest);
23
+ }
24
+ export function sessionFilename(value) {
25
+ return typeof value === "string" && /^[a-zA-Z0-9_.-]+\.jsonl$/.test(value) && !value.startsWith(".");
26
+ }
27
+ export function parseManifest(bytes) {
28
+ const value = json(bytes, "profile.json");
29
+ if (!object(value) ||
30
+ value.format !== 1 ||
31
+ !exact(value.personal) ||
32
+ (value.log !== undefined && !isContentDigest(value.log)) ||
33
+ !object(value.theory) ||
34
+ typeof value.theory.theory !== "string" ||
35
+ typeof value.theory.range !== "string" ||
36
+ !Array.isArray(value.theories) ||
37
+ !value.theories.length ||
38
+ !value.theories.every((name) => typeof name === "string" && name.length > 0) ||
39
+ !object(value.sessions) ||
40
+ !Object.entries(value.sessions).every(([surface, file]) => surface.length > 0 && sessionFilename(file)))
41
+ throw new Error("Invalid profile.json manifest");
42
+ const sessions = {};
43
+ for (const [surface, filename] of Object.entries(value.sessions)) {
44
+ if (!sessionFilename(filename))
45
+ throw new Error("Invalid Session filename");
46
+ Object.defineProperty(sessions, surface, { value: filename, enumerable: true, configurable: true, writable: true });
47
+ }
48
+ if (new Set(Object.values(sessions)).size !== Object.keys(sessions).length)
49
+ throw new Error("A pi session file cannot belong to two surfaces");
50
+ return {
51
+ format: 1,
52
+ personal: value.personal,
53
+ ...(value.log === undefined ? {} : { log: value.log }),
54
+ theory: { theory: value.theory.theory, range: value.theory.range },
55
+ theories: value.theories,
56
+ sessions,
57
+ };
58
+ }
59
+ function patchContent(value) {
60
+ return (object(value) &&
61
+ Array.isArray(value.bases) &&
62
+ value.bases.every(exact) &&
63
+ object(value.delta) &&
64
+ Array.isArray(value.delta.operations) &&
65
+ object(value.metadata) &&
66
+ object(value.metadata.properties) &&
67
+ Array.isArray(value.metadata.citations));
68
+ }
69
+ export function parseLog(bytes) {
70
+ if (!bytes)
71
+ throw new Error("Missing Profile file: log.jsonl");
72
+ const lines = decoder.decode(bytes).split("\n");
73
+ if (lines.at(-1) === "")
74
+ lines.pop();
75
+ const entries = lines.map((line, index) => {
76
+ let value;
77
+ try {
78
+ value = JSON.parse(line);
79
+ }
80
+ catch {
81
+ throw new Error("Malformed Profile log JSON at line " + (index + 1));
82
+ }
83
+ if (!isProfileLogEntry(value))
84
+ throw new Error("Invalid Profile log entry at line " + (index + 1));
85
+ return value;
86
+ });
87
+ return mergeProfileLogs([], entries);
88
+ }
89
+ export function logBytes(entries) {
90
+ const merged = mergeProfileLogs([], entries);
91
+ return utf8.encode(merged.length ? merged.map((entry) => JSON.stringify(entry)).join("\n") + "\n" : "");
92
+ }
93
+ function requireAttachments(value, blobs) {
94
+ if (!object(value) && !Array.isArray(value))
95
+ return;
96
+ if (object(value) && value.kind === "blob" && isContentDigest(value.hash) && !blobs.has(value.hash))
97
+ throw new Error("Missing Profile blob: " + value.hash);
98
+ for (const child of Object.values(value))
99
+ requireAttachments(child, blobs);
100
+ }
101
+ /** Pure validation; safe in a Convex action. No filesystem, package loading, or provider calls. */
102
+ export function validate(files, theories) {
103
+ const profile = validateStructure(files);
104
+ const { manifest } = profile;
105
+ try {
106
+ resolveTheory(manifest.theory, theories);
107
+ }
108
+ catch (error) {
109
+ throw new Error("Profile Theory " + manifest.theory.theory + " " + manifest.theory.range + ": " + String(error));
110
+ }
111
+ return profile;
112
+ }
113
+ export function liveLogPath(manifest) {
114
+ return manifest.log === undefined ? "log.jsonl" : "log-" + manifest.log + ".jsonl";
115
+ }
116
+ function validateStructure(files) {
117
+ const manifest = parseManifest(files.get("profile.json"));
118
+ const contents = new Map();
119
+ const blobs = new Map();
120
+ const sessionPaths = new Set(Object.values(manifest.sessions).map((filename) => "sessions/" + filename));
121
+ for (const [path, bytes] of files) {
122
+ if (path === "profile.json" || path === liveLogPath(manifest) || sessionPaths.has(path))
123
+ continue;
124
+ if (path.startsWith("patches/") && path.endsWith(".json")) {
125
+ const digest = path.slice(8, -5);
126
+ const content = json(bytes, path);
127
+ if (!isContentDigest(digest) || !patchContent(content))
128
+ throw new Error("Invalid Patch file: " + path);
129
+ if (revisionDigest(content) !== digest)
130
+ throw new Error("Patch content digest mismatch: " + path);
131
+ contents.set(digest, content);
132
+ }
133
+ else if (path.startsWith("blobs/")) {
134
+ const digest = path.slice(6);
135
+ if (!isContentDigest(digest) || attachmentDigest(bytes) !== digest)
136
+ throw new Error("Blob digest mismatch: " + path);
137
+ blobs.set(digest, bytes);
138
+ }
139
+ else
140
+ throw new Error("Unexpected Profile exchange file: " + path);
141
+ }
142
+ const patches = notebookBundleForRevision(manifest.personal, contents);
143
+ for (const content of contents.values())
144
+ requireAttachments(content, blobs);
145
+ const sessions = new Map();
146
+ for (const [surface, filename] of Object.entries(manifest.sessions)) {
147
+ const bytes = files.get("sessions/" + filename);
148
+ if (!bytes)
149
+ throw new Error("Missing pi session file: " + filename);
150
+ const source = decoder.decode(bytes);
151
+ parsePiSession(source);
152
+ sessions.set(surface, source);
153
+ }
154
+ const log = files.get(liveLogPath(manifest));
155
+ if (manifest.log !== undefined && (!log || attachmentDigest(log) !== manifest.log))
156
+ throw new Error("Profile log digest mismatch");
157
+ return { manifest, patches, log: parseLog(log), blobs, sessions };
158
+ }
159
+ /** Migrate structurally valid live data before ordinary strict Theory resolution. */
160
+ export function migrateProfileFiles(files, theories) {
161
+ const current = validateStructure(files);
162
+ const matches = theories.filter((theory) => theory.id === current.manifest.theory.theory);
163
+ const theory = matches[0];
164
+ if (matches.length !== 1 || theory === undefined)
165
+ throw new Error("Profile migration needs exactly one supplied Theory implementation");
166
+ const requirement = current.manifest.theory;
167
+ // Web exchanges have also used exact release pins. Extract their stored minor,
168
+ // not the installed minor; broad caller-supplied ranges remain ordinary strict reads.
169
+ const exact = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:[-+][0-9A-Za-z.+-]+)?$/.exec(requirement.range);
170
+ const pin = exact ? { ...requirement, range: "~" + exact[1] + "." + exact[2] } : requirement;
171
+ if (!/^~\d+\.\d+$/.test(pin.range)) {
172
+ validate(files, theories);
173
+ return new Map(files);
174
+ }
175
+ let result;
176
+ try {
177
+ result = migrateTheoryProfile(theory, pin, current);
178
+ }
179
+ catch (error) {
180
+ throw new Error("Profile Theory " + requirement.theory + " " + requirement.range + ": " + String(error));
181
+ }
182
+ const next = new Map(files);
183
+ if (result.requirement.range !== current.manifest.theory.range) {
184
+ for (const revision of result.profile.patches.revisions) {
185
+ const { ref, ...content } = revision;
186
+ const path = "patches/" + ref.digest + ".json";
187
+ next.set(path, jsonBytes(content));
188
+ }
189
+ const log = logBytes(result.profile.log);
190
+ const manifest = {
191
+ ...current.manifest,
192
+ personal: result.profile.patches.terminal,
193
+ theory: result.requirement,
194
+ log: attachmentDigest(log),
195
+ };
196
+ next.delete(liveLogPath(current.manifest));
197
+ next.set(liveLogPath(manifest), log);
198
+ next.set("profile.json", jsonBytes(manifest));
199
+ }
200
+ validate(next, theories);
201
+ return next;
202
+ }
203
+ /** Only exchange files belong in this map. The directory adapter excludes materials and untrusted sessions. */
204
+ export function pack(files, theories) {
205
+ validate(files, theories);
206
+ return encodeTar(files);
207
+ }
208
+ export function unpack(archive, theories, options = {}) {
209
+ const files = migrateProfileFiles(decodeTar(archive), theories);
210
+ const profile = validate(files, theories);
211
+ if (options.cwd !== undefined)
212
+ for (const filename of Object.values(profile.manifest.sessions)) {
213
+ const path = "sessions/" + filename;
214
+ const source = files.get(path);
215
+ if (source)
216
+ files.set(path, utf8.encode(relocatePiSession(decoder.decode(source), options.cwd)));
217
+ }
218
+ return files;
219
+ }
@@ -0,0 +1,5 @@
1
+ import { type HostCapability, type Skill } from "@mmon-co/ncept-core";
2
+ import type { HostTool } from "./host.js";
3
+ import type { LearningHost } from "./learning.js";
4
+ import { type LocalSession } from "./runtime.js";
5
+ export declare function hostTools<S>(host: LearningHost<S>, opened: LocalSession, capabilities: readonly HostCapability[], skills: readonly Skill[], metadataKeys: readonly string[]): readonly HostTool[];