@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,517 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { applyGraphDiff, attachmentDigest, compileGraphDiff, composePatch, isMaterialMeta, isMission, isNodeId, nodeCascadedProperty, parseGraphQuery, revisionContent, projectVisualGraph, sameExactPatchRef, selectGraph, tagIndex, } from "@mmon-co/ncept-core";
4
+ import { localPayload, platform, sessionStates, transcript } from "./runtime.js";
5
+ import { mechanics } from "./mechanics.js";
6
+ import { object } from "./sessions.js";
7
+ import { citations, exactRef, metadataProperties, modeEntry, operations, strings } from "./inputs.js";
8
+ function args(value) {
9
+ if (!object(value))
10
+ throw new Error("Expected an object");
11
+ return value;
12
+ }
13
+ function text(value, name) {
14
+ if (typeof value !== "string" || !value.trim())
15
+ throw new Error("Expected " + name);
16
+ return value;
17
+ }
18
+ function nodes(value) {
19
+ if (!Array.isArray(value) || !value.every(isNodeId))
20
+ throw new Error("Expected Node identities");
21
+ return value;
22
+ }
23
+ function safeName(value) {
24
+ const name = text(value, "filename");
25
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name))
26
+ throw new Error("Expected a plain filename or identity");
27
+ return name;
28
+ }
29
+ const string = { type: "string" };
30
+ const nodeList = { type: "array", items: { type: "string", pattern: "^node-" } };
31
+ const graphProperties = {
32
+ operations: {
33
+ type: "array",
34
+ description: 'Core operations use kind, not op. Create a Node with {"kind":"add-node","node":{"id":"node-example"}}; its label and criterion are separate: {"kind":"add-metadata-set","metadataSet":{"id":"metadata-example","subjects":[{"kind":"node","id":"node-example"}],"properties":{"display:label":"Example","pedagogy:criterion":"Observable success","pedagogy:knowledge-type":"conceptual"}}}. A prerequisite edge is {"kind":"add-edge","edge":{"id":"edge-example","from":"node-prerequisite","to":"node-example"}}. Other kinds: define-tag {tag:{name,nodes,edges,metadataSets}}, add-material/edit-material {material:{playground,type,id,about,content:{kind:"blob",hash,mediaType},meta}}, remove-material {playground,id}, mask-contribution {mask:{source:{identity,digest},operationIndex,entity:{kind,id},property?}}. Prefer the material tool for local files. Metadata properties belong to metadata sets, never directly on Nodes.',
35
+ items: { type: "object" },
36
+ },
37
+ targets: nodeList,
38
+ citations: { type: "array", items: { type: "object" } },
39
+ retractions: { type: "array", items: string },
40
+ };
41
+ function schema(properties, required = []) {
42
+ return { type: "object", properties, required, additionalProperties: false };
43
+ }
44
+ async function acceptContent(host, session, from, content, about = session.about) {
45
+ const view = await host.runtime.snapshot();
46
+ if (!sameExactPatchRef(view.graph.terminal, from))
47
+ throw new Error("Personal Patch changed; read and propose again");
48
+ const destination = await host.runtime.prospective(content);
49
+ const to = destination.graph.terminal;
50
+ const event = await host.runtime.prepare(destination.theory.event({ kind: "patch.changed", from, to }, destination), session, destination);
51
+ await host.runtime.profile.addRevision(from.identity, content);
52
+ await host.runtime.profile.setPersonal(to);
53
+ await host.runtime.profile.appendLog([
54
+ ...event.entries,
55
+ platform({ kind: "local.patch", from, to }, session.surface),
56
+ platform({
57
+ kind: "local.session",
58
+ session: { ...session, about: about.filter((id) => destination.graph.nodes.some((node) => node.id === id)) },
59
+ }, session.surface),
60
+ ]);
61
+ return to;
62
+ }
63
+ function graphDiff(host, input, session) {
64
+ return host.runtime.snapshot().then(async (view) => {
65
+ if (!Array.isArray(input.operations))
66
+ throw new Error("Expected graph operations");
67
+ const compiled = compileGraphDiff(view.bundle, operations(input.operations), input.targets === undefined ? session.about : nodes(input.targets), citations(input.citations), input.retractions === undefined ? [] : strings(input.retractions));
68
+ return { view, compiled, content: applyGraphDiff(await host.runtime.content(), compiled) };
69
+ });
70
+ }
71
+ function page(items, input) {
72
+ const start = input.cursor === undefined ? 0 : Number(input.cursor);
73
+ const limit = input.limit === undefined ? 20 : Number(input.limit);
74
+ if (!Number.isSafeInteger(start) || start < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100)
75
+ throw new Error("Invalid page cursor or limit (1–100)");
76
+ const next = start + limit;
77
+ return {
78
+ page: items.slice(start, next),
79
+ isDone: next >= items.length,
80
+ continueCursor: next >= items.length ? null : String(next),
81
+ };
82
+ }
83
+ export function hostTools(host, opened, capabilities, skills, metadataKeys) {
84
+ const tools = [];
85
+ function mount(name, description, definition, run) {
86
+ tools.push({
87
+ name,
88
+ description,
89
+ schema: definition,
90
+ run: (raw) => host.serial(async () => {
91
+ const session = await host.current(opened);
92
+ if (session.closed || session.mode !== opened.mode)
93
+ throw new Error("Tool belongs to an inactive Session mode");
94
+ const result = await run(args(raw), session);
95
+ if (!object(result.content) || result.content.status !== "refused") {
96
+ const feature = await host.runtime.event({
97
+ kind: "feature.used",
98
+ operation: name,
99
+ at: new Date().toISOString(),
100
+ about: session.about,
101
+ }, session);
102
+ await host.runtime.profile.appendLog(feature.entries);
103
+ }
104
+ return result;
105
+ }),
106
+ });
107
+ }
108
+ if (capabilities.includes("reads")) {
109
+ mount("query", "Find Profile nodes, Missions, Sessions, observations or Materials. Paginated lists use cursor and limit (1–100).", schema({
110
+ resource: { enum: ["profile", "session", "material"] },
111
+ op: { enum: ["search", "list", "find"] },
112
+ input: { type: "object", properties: { kind: string, query: string } },
113
+ cursor: string,
114
+ limit: { type: "integer" },
115
+ }, ["resource", "op"]), async (raw) => {
116
+ const view = await host.runtime.snapshot();
117
+ const input = raw.input === undefined ? {} : args(raw.input);
118
+ const resource = text(raw.resource, "resource");
119
+ let items;
120
+ if (resource === "session")
121
+ items = sessionStates(view.profile);
122
+ else if (resource === "material")
123
+ items = view.graph.materials;
124
+ else if (resource === "profile") {
125
+ switch (input.kind ?? "node") {
126
+ case "mission":
127
+ items = await host.missionReadings();
128
+ break;
129
+ case "observation":
130
+ items = view.observations;
131
+ break;
132
+ case "node":
133
+ items = projectVisualGraph({
134
+ graph: view.graph,
135
+ annotations: {},
136
+ tags: view.theory.project(view.graph, view.state),
137
+ }).nodes;
138
+ break;
139
+ default:
140
+ throw new Error("Profile kind accepts node, mission or observation");
141
+ }
142
+ }
143
+ else
144
+ throw new Error("Unsupported local resource");
145
+ if (typeof input.query === "string") {
146
+ const query = input.query.toLowerCase();
147
+ items = items.filter((item) => JSON.stringify(item).toLowerCase().includes(query));
148
+ }
149
+ return { content: page(items, raw) };
150
+ });
151
+ mount("read", "Read the current graph (including criteria and guidance), a Session transcript, a Patch revision, or a Material's saved bytes and working-copy path.", schema({ resource: { enum: ["graph", "session", "material", "patch"] }, input: { type: "object" } }), async (raw, session) => {
152
+ const input = raw.input === undefined ? {} : args(raw.input);
153
+ const view = await host.runtime.snapshot();
154
+ switch (raw.resource ?? "graph") {
155
+ case "graph": {
156
+ const graph = input.query === undefined
157
+ ? view.graph
158
+ : selectGraph(view.graph, parseGraphQuery(input.query), tagIndex(view.theory.project(view.graph, view.state)));
159
+ const selected = input.nodes === undefined ? undefined : nodes(input.nodes);
160
+ return {
161
+ content: {
162
+ ...graph,
163
+ nodes: graph.nodes
164
+ .filter(({ id }) => !selected || selected.includes(id))
165
+ .map(({ id }) => ({
166
+ id,
167
+ label: nodeCascadedProperty(graph, id, "display:label"),
168
+ criterion: nodeCascadedProperty(graph, id, "pedagogy:criterion"),
169
+ guidance: nodeCascadedProperty(graph, id, "pedagogy:guidance"),
170
+ assessment: nodeCascadedProperty(graph, id, "pedagogy:assessment"),
171
+ })),
172
+ projection: view.theory.project(graph, view.state),
173
+ },
174
+ };
175
+ }
176
+ case "patch": {
177
+ const patch = input.ref === undefined ? view : await host.runtime.snapshot(exactRef(input.ref));
178
+ return { content: patch.bundle };
179
+ }
180
+ case "session": {
181
+ const id = input.id === undefined ? session.id : text(input.id, "Session id");
182
+ const selected = sessionStates(view.profile).find((item) => item.id === id);
183
+ if (!selected)
184
+ throw new Error("Unknown Session");
185
+ return { content: { session: selected, transcript: transcript(view.profile, selected.surface) } };
186
+ }
187
+ case "material": {
188
+ const material = view.graph.materials.find((item) => item.id === input.id && (input.playground === undefined || item.playground === input.playground));
189
+ if (!material)
190
+ throw new Error("Unknown Material");
191
+ const bytes = view.profile.blobs.get(material.content.hash);
192
+ if (!bytes)
193
+ throw new Error("Missing Material bytes");
194
+ const path = material.playground === "local" ? workingPath(host.runtime.profile.dir, material) : undefined;
195
+ return {
196
+ content: {
197
+ material,
198
+ ...(path ? { path } : {}),
199
+ ...(material.content.mediaType.startsWith("text/") || material.content.mediaType === "application/json"
200
+ ? { text: new TextDecoder().decode(bytes) }
201
+ : { base64: Buffer.from(bytes).toString("base64") }),
202
+ ...(path
203
+ ? { workingCopy: await readFile(path, "utf8").catch(() => null) }
204
+ : { runner: "unavailable on this host" }),
205
+ },
206
+ };
207
+ }
208
+ default:
209
+ throw new Error("Unsupported local read resource");
210
+ }
211
+ });
212
+ }
213
+ if (capabilities.includes("graph-draft")) {
214
+ mount("edit_graph_draft", "Compile graph operations against the personal Patch. This replaces the unsaved draft, not the Profile. Propose graph-diff to ask the learner to accept it.", schema(graphProperties, ["operations"]), async (raw, session) => {
215
+ const prepared = await graphDiff(host, raw, session);
216
+ host.drafts.set(session.id, { base: prepared.view.graph.terminal.digest, content: prepared.content });
217
+ return { content: { status: "draft", report: prepared.compiled.report, graph: prepared.compiled.graph } };
218
+ });
219
+ }
220
+ mount("propose", 'Ask approval for a Mission, graph-diff/revision, or preferences. For mission, input.mission is {id,statement,targets:[{node,provenance:{identity,digest}}],priority}; the same id revises an existing Mission. A Mission may start with targets:[] before charting; after graph acceptance, use mission again to attach its targets with exact provenance from read graph. For graph-diff/revision, input:{} submits the current edit_graph_draft; input.targets optionally selects Node ids. For preferences, input.text is the new text. For mode, input is {mode,then,entry}; choose an allowed switch from context. Entry shapes: {kind:"goal",text}, {kind:"mission",id}, {kind:"target",node}, {kind:"review",nodes}, or {kind:"lesson",opening:{missionId,number}} (omit number for the next uncleared Lesson). Call mission without scope to include Missions not yet targeted; its path supplies Lesson numbers after targets are attached. No proposed Profile change is applied before confirm.', schema({
221
+ op: { enum: ["mission", "graph-diff", "revision", "preferences", "settings", "mode"] },
222
+ input: {
223
+ type: "object",
224
+ properties: {
225
+ mission: schema({
226
+ id: string,
227
+ statement: string,
228
+ targets: {
229
+ type: "array",
230
+ items: schema({
231
+ node: string,
232
+ provenance: schema({ identity: string, digest: string }, ["identity", "digest"]),
233
+ }, ["node", "provenance"]),
234
+ },
235
+ priority: { type: "number" },
236
+ guidance: { type: "array", items: { type: "object" } },
237
+ assessment: { type: "array", items: { type: "object" } },
238
+ }, ["id", "statement", "targets", "priority"]),
239
+ mode: string,
240
+ then: { enum: ["here", "next", "aside"] },
241
+ entry: {
242
+ type: "object",
243
+ properties: {
244
+ kind: { enum: ["goal", "mission", "target", "review", "lesson", "checkpoint"] },
245
+ text: string,
246
+ id: string,
247
+ node: string,
248
+ nodes: nodeList,
249
+ opening: schema({ missionId: string, number: { type: "integer", minimum: 1 } }, ["missionId"]),
250
+ },
251
+ description: "For a Lesson use {kind:'lesson',opening:{missionId,number}}; omit number for the next uncleared Lesson. The host resolves the complete snapshot.",
252
+ },
253
+ ...graphProperties,
254
+ text: string,
255
+ },
256
+ },
257
+ title: string,
258
+ description: string,
259
+ }, ["op", "input"]), async (raw, session) => {
260
+ const op = text(raw.op, "proposal operation");
261
+ const input = args(raw.input);
262
+ if (op === "mode") {
263
+ const view = await host.runtime.snapshot();
264
+ const mode = text(input.mode, "mode");
265
+ const selected = host.mode(view.theory, session.mode, session.entry);
266
+ const allowed = selected?.switches.find((item) => item.mode === mode && (input.then === undefined || item.then === input.then));
267
+ if (!allowed)
268
+ throw new Error("Mode switch is not allowed. Allowed: " + JSON.stringify(selected?.switches ?? []));
269
+ let entry;
270
+ if (object(input.entry) && input.entry.kind === "lesson" && object(input.entry.opening)) {
271
+ const { missionId, number } = input.entry.opening;
272
+ if (number !== undefined && (typeof number !== "number" || !Number.isSafeInteger(number)))
273
+ throw new Error("Lesson number must be an integer");
274
+ entry = await host.lessonEntry(text(missionId, "Mission id"), number);
275
+ }
276
+ else
277
+ entry = input.entry === undefined ? undefined : modeEntry(input.entry);
278
+ const to = { ...allowed, ...(entry === undefined ? {} : { entry }) };
279
+ await host.switchMode(session, to);
280
+ return { content: { status: "switching" }, switch: to };
281
+ }
282
+ let detail = input;
283
+ let apply;
284
+ if (op === "graph-diff" || op === "revision") {
285
+ if (!capabilities.includes("graph-draft"))
286
+ throw new Error("This mode cannot propose graph changes");
287
+ const view = await host.runtime.snapshot();
288
+ const draft = input.operations === undefined ? host.drafts.get(session.id) : undefined;
289
+ if (draft && draft.base !== view.graph.terminal.digest)
290
+ throw new Error("Draft is stale; compile again");
291
+ const content = draft?.content ?? (await graphDiff(host, input, session)).content;
292
+ detail = { from: view.graph.terminal, before: await host.runtime.content(), after: content };
293
+ apply = async () => {
294
+ const targets = input.targets === undefined ? session.about : nodes(input.targets);
295
+ const about = targets.length
296
+ ? targets
297
+ : content.delta.operations.flatMap((op) => (op.kind === "add-node" ? [op.node.id] : []));
298
+ const ref = await acceptContent(host, session, view.graph.terminal, content, about);
299
+ host.drafts.delete(session.id);
300
+ return ref;
301
+ };
302
+ }
303
+ else if (op === "mission") {
304
+ if (!isMission(input.mission))
305
+ throw new Error("input.mission must be a Core Mission (id, statement, targets:[{node,provenance:{identity,digest}}], priority:number)");
306
+ const mission = input.mission;
307
+ const existing = (await host.missionReadings()).some((reading) => reading.mission.id === mission.id);
308
+ apply = () => host.reviseMission(mission, !existing);
309
+ }
310
+ else if (op === "preferences") {
311
+ const preferences = text(input.text, "preferences text");
312
+ apply = async () => host.runtime.profile.appendLog([
313
+ platform({
314
+ kind: "local.config",
315
+ timezone: host.runtime.timezone,
316
+ preferences,
317
+ }),
318
+ ]);
319
+ }
320
+ else if (op === "settings") {
321
+ const current = await host.config();
322
+ const config = { ...current, ...input };
323
+ apply = () => host.configure(config);
324
+ }
325
+ else
326
+ throw new Error("Unsupported proposal operation");
327
+ const accepted = await host.confirm({
328
+ kind: op,
329
+ title: typeof raw.title === "string" ? raw.title : op,
330
+ description: typeof raw.description === "string" ? raw.description : "Apply this change to your Profile?",
331
+ detail,
332
+ });
333
+ if (!accepted)
334
+ return { content: { status: "refused" } };
335
+ const result = await apply();
336
+ return { content: { status: "accepted", result } };
337
+ });
338
+ if (capabilities.includes("materials")) {
339
+ mount("material", "Store or open a Material as a local file. add/edit input: id, about (Node ids), filename, mediaType, and text or base64 bytes, optional type and meta. Bytes and Material enter the Profile; the learner's working copy is under materials/<node>/. command records input.outcome through the Theory; bash and applet execution belong to the front end.", schema({ op: { enum: ["add", "edit", "open", "remove", "command"] }, input: { type: "object" } }, [
340
+ "op",
341
+ "input",
342
+ ]), async (raw, session) => {
343
+ const input = args(raw.input);
344
+ const id = safeName(input.id);
345
+ const view = await host.runtime.snapshot();
346
+ const previous = view.graph.materials.find((item) => item.id === id && item.playground === "local");
347
+ if (raw.op === "command") {
348
+ if (!previous)
349
+ throw new Error("Unknown local Material");
350
+ const event = await host.runtime.event({
351
+ kind: "outcome",
352
+ material: { playground: previous.playground, id },
353
+ surface: session.surface,
354
+ at: view.now,
355
+ about: previous.about,
356
+ payload: input.outcome,
357
+ }, session);
358
+ await host.runtime.profile.appendLog(event.entries);
359
+ return { content: { status: "recorded" } };
360
+ }
361
+ if (raw.op === "open") {
362
+ const material = previous ?? view.graph.materials.find((item) => item.id === id);
363
+ if (!material)
364
+ throw new Error("Unknown Material");
365
+ const bytes = view.profile.blobs.get(material.content.hash);
366
+ if (!bytes)
367
+ throw new Error("Missing Material bytes");
368
+ const path = material.playground === "local" ? await checkout(host.runtime.profile.dir, material, bytes) : undefined;
369
+ await host.runtime.profile.appendLog([
370
+ platform({
371
+ kind: "local.material",
372
+ surface: session.surface,
373
+ material,
374
+ object: "object-" + crypto.randomUUID(),
375
+ }),
376
+ ]);
377
+ return { content: { material, ...(path ? { path } : { runner: "unavailable on this host" }) } };
378
+ }
379
+ if (raw.op === "remove") {
380
+ if (!previous)
381
+ throw new Error("Unknown local Material");
382
+ const content = composePatch(await host.runtime.content(), [
383
+ { kind: "remove-material", playground: "local", id },
384
+ ]);
385
+ await acceptContent(host, session, view.graph.terminal, content);
386
+ return { content: { status: "removed", id } };
387
+ }
388
+ if (raw.op !== "add" && raw.op !== "edit")
389
+ throw new Error("Unsupported Material operation");
390
+ if ((raw.op === "add" && previous) || (raw.op === "edit" && !previous))
391
+ throw new Error("Material already exists or is missing");
392
+ const about = nodes(input.about);
393
+ for (const node of about)
394
+ if (!view.graph.nodes.some(({ id }) => id === node))
395
+ throw new Error("Missing Node " + node);
396
+ const filename = safeName(input.filename);
397
+ const mediaType = text(input.mediaType, "media type");
398
+ if ((typeof input.text === "string") === (typeof input.base64 === "string"))
399
+ throw new Error("Supply either text or base64 bytes");
400
+ const bytes = typeof input.text === "string"
401
+ ? new TextEncoder().encode(input.text)
402
+ : Buffer.from(text(input.base64, "base64"), "base64");
403
+ if (input.meta !== undefined && !isMaterialMeta(input.meta))
404
+ throw new Error("Invalid Material metadata");
405
+ const hash = await host.runtime.profile.addBlob(bytes);
406
+ const material = {
407
+ playground: "local",
408
+ type: typeof input.type === "string" ? input.type : "file",
409
+ id,
410
+ about,
411
+ content: { kind: "blob", hash, mediaType },
412
+ meta: { ...(isMaterialMeta(input.meta) ? input.meta : {}), filename },
413
+ };
414
+ const content = composePatch(await host.runtime.content(), [
415
+ { kind: raw.op === "add" ? "add-material" : "edit-material", material },
416
+ ]);
417
+ await acceptContent(host, session, view.graph.terminal, content);
418
+ const path = await checkout(host.runtime.profile.dir, material, bytes, previous);
419
+ await host.runtime.profile.appendLog([
420
+ platform({
421
+ kind: "local.material",
422
+ surface: session.surface,
423
+ material,
424
+ object: "object-" + crypto.randomUUID(),
425
+ }),
426
+ ]);
427
+ const event = await host.runtime.event({
428
+ kind: "object.put",
429
+ object: `object-${crypto.randomUUID()}`,
430
+ meta: { name: filename, mime: mediaType, bytes: bytes.length },
431
+ surface: session.surface,
432
+ }, session);
433
+ await host.runtime.profile.appendLog(event.entries);
434
+ return { content: { status: "available", material, path } };
435
+ });
436
+ }
437
+ if (metadataKeys.length) {
438
+ mount("edit_metadata", "Edit this mode's authorized metadata keys on existing Nodes: " +
439
+ metadataKeys.join(", ") +
440
+ ". Material completion queries use the created Material's identity; local file-item attempts, including card recalls, have playground local.", schema({ nodes: nodeList, properties: { type: "object" } }, ["nodes", "properties"]), async (raw, session) => {
441
+ const attached = nodes(raw.nodes);
442
+ const properties = metadataProperties(raw.properties);
443
+ if (Object.keys(properties).some((key) => !metadataKeys.includes(key)))
444
+ throw new Error("Metadata key is not editable in this mode");
445
+ const view = await host.runtime.snapshot();
446
+ for (const node of attached)
447
+ if (!view.graph.nodes.some(({ id }) => id === node))
448
+ throw new Error("Missing Node " + node);
449
+ const content = composePatch(await host.runtime.content(), [
450
+ {
451
+ kind: "add-metadata-set",
452
+ metadataSet: {
453
+ id: `metadata-${crypto.randomUUID()}`,
454
+ subjects: attached.map((id) => ({ kind: "node", id })),
455
+ properties,
456
+ },
457
+ },
458
+ ]);
459
+ return { content: { patch: await acceptContent(host, session, view.graph.terminal, content) } };
460
+ });
461
+ }
462
+ if (capabilities.includes("graph-draft") || capabilities.includes("materials")) {
463
+ mount("undo", "Discard this Session's draft, or restore the prior personal Patch for its most recent accepted edit. Evidence is immutable; correct it with the Theory's retraction tools.", schema({}), async (_raw, session) => {
464
+ if (host.drafts.delete(session.id))
465
+ return { content: { status: "draft-discarded" } };
466
+ const view = await host.runtime.snapshot();
467
+ const entry = view.profile.log
468
+ .filter((entry) => "surface" in entry && entry.surface === session.surface)
469
+ .map((entry) => localPayload(entry, "local.patch"))
470
+ .filter((entry) => entry !== undefined)
471
+ .at(-1);
472
+ if (!entry || !object(entry.from) || !object(entry.to) || entry.to.digest !== view.graph.terminal.digest)
473
+ throw new Error("No current Session edit to undo");
474
+ const before = await host.runtime.snapshot(exactRef(entry.from));
475
+ const revision = before.bundle.revisions.find(({ ref }) => sameExactPatchRef(ref, before.bundle.terminal));
476
+ if (!revision)
477
+ throw new Error("Undo revision is missing");
478
+ return {
479
+ content: {
480
+ status: "restored",
481
+ patch: await acceptContent(host, session, view.graph.terminal, revisionContent(revision)),
482
+ },
483
+ };
484
+ });
485
+ }
486
+ mount("skill", "Read a mounted pedagogy or local-host Skill, or one of its named relative resources.", schema({ name: string, resource: string }, ["name"]), async (raw) => {
487
+ const skill = [...skills, mechanics].find(({ name }) => name === raw.name);
488
+ if (!skill)
489
+ throw new Error("Unknown Skill");
490
+ if (raw.resource === undefined)
491
+ return {
492
+ content: { name: skill.name, body: skill.body, resources: skill.resources?.map(({ path }) => path) ?? [] },
493
+ };
494
+ const resource = skill.resources?.find(({ path }) => path === raw.resource);
495
+ if (!resource)
496
+ throw new Error("Unknown Skill resource");
497
+ return { content: resource.content };
498
+ });
499
+ return tools;
500
+ }
501
+ function workingPath(dir, material) {
502
+ return join(dir, "materials", safeName(material.about[0] ?? "unscoped"), safeName(material.id), safeName(material.meta.filename));
503
+ }
504
+ async function checkout(dir, material, bytes, previous) {
505
+ const path = workingPath(dir, material);
506
+ await mkdir(join(path, ".."), { recursive: true });
507
+ const existing = previous ? await readFile(path).catch(() => undefined) : undefined;
508
+ const unchanged = existing && previous && attachmentDigest(existing) === previous.content.hash;
509
+ try {
510
+ await writeFile(path, bytes, { flag: unchanged ? "w" : "wx" });
511
+ }
512
+ catch (error) {
513
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
514
+ throw error;
515
+ }
516
+ return path;
517
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,157 @@
1
+ import type { ChatSetup, HostCapability, ExactPatchRef, JsonSchema, LessonReading, MissionPathReading, Mission, MissionRunReading, ModeEntry, ModeSwitchDefault, NodeId, Request, SessionRef, Theory, TheoryRequirement } from "@mmon-co/ncept-core";
2
+ import type { ProfileDirectory } from "./directory.js";
3
+ /** The host supplies both judge and assess with the concrete JSON reply schema. */
4
+ export type ModelRequest = Extract<Request, {
5
+ kind: "judge" | "assess";
6
+ }> & Readonly<{
7
+ schema: JsonSchema;
8
+ }>;
9
+ export type Model = (request: ModelRequest) => Promise<unknown>;
10
+ export interface Proposal {
11
+ readonly kind: string;
12
+ readonly title: string;
13
+ readonly description: string;
14
+ readonly detail: unknown;
15
+ }
16
+ export type Confirm = (proposal: Proposal) => Promise<boolean>;
17
+ export type ModeSwitch = ModeSwitchDefault & Readonly<{
18
+ entry?: ModeEntry;
19
+ }>;
20
+ export interface HostToolResult {
21
+ readonly content: unknown;
22
+ /** The front end, not the host, changes its active conversation and applies carry. */
23
+ readonly switch?: ModeSwitch;
24
+ }
25
+ export interface HostTool {
26
+ readonly name: string;
27
+ readonly description: string;
28
+ readonly schema: JsonSchema;
29
+ run(args: unknown): Promise<HostToolResult>;
30
+ }
31
+ export type HostChatSetup = Omit<ChatSetup, "tools"> & Readonly<{
32
+ tools: readonly HostTool[];
33
+ capabilities: readonly HostCapability[];
34
+ }>;
35
+ export interface HostSession {
36
+ readonly id: SessionRef;
37
+ readonly surface: string;
38
+ readonly mode: string;
39
+ readonly entry?: ModeEntry;
40
+ }
41
+ export interface MissionReading {
42
+ readonly mission: Mission;
43
+ readonly run: MissionRunReading;
44
+ readonly next: readonly LessonReading[];
45
+ readonly path?: MissionPathReading;
46
+ }
47
+ export interface HostReading {
48
+ readonly missions: readonly MissionReading[];
49
+ readonly dueReview: readonly NodeId[];
50
+ }
51
+ export interface HubRelease {
52
+ readonly ref: ExactPatchRef;
53
+ readonly version: string;
54
+ readonly url: string;
55
+ }
56
+ export interface ImportResult {
57
+ readonly missions: readonly string[];
58
+ readonly sessions: readonly SessionRef[];
59
+ }
60
+ export interface HostConfig {
61
+ readonly theory: TheoryRequirement;
62
+ readonly theories: readonly string[];
63
+ /** IANA zone for learner-days; defaults to the local machine's configured zone. */
64
+ readonly timezone?: string;
65
+ /** Positive Session budget in minutes; defaults to 20. */
66
+ readonly sessionLength?: number;
67
+ }
68
+ export type SessionOpening = Readonly<{
69
+ mode: string;
70
+ entry?: ModeEntry;
71
+ resume?: SessionRef;
72
+ mission?: string;
73
+ }> & Readonly<{
74
+ skip?: {
75
+ mission: string;
76
+ kind: "skip-lesson";
77
+ } | {
78
+ mission: string;
79
+ kind: "skip-to";
80
+ stop: Pick<LessonReading, "kind" | "number" | "checkpoint">;
81
+ };
82
+ }>;
83
+ /** Learner entry controls; resolved against current Profile state by its writing tutor. */
84
+ export type SessionIntent = Readonly<{
85
+ kind: "skip-lesson";
86
+ missionId: string;
87
+ }> | Readonly<{
88
+ kind: "skip-to";
89
+ missionId: string;
90
+ stop: Pick<LessonReading, "kind" | "number" | "checkpoint">;
91
+ }> | Readonly<{
92
+ kind: "continue" | "revise-lesson" | "revise-route";
93
+ missionId: string;
94
+ }> | Readonly<{
95
+ kind: "tell-tutor";
96
+ missionId: string;
97
+ request: string;
98
+ }> | Readonly<{
99
+ kind: "new-mission" | "review";
100
+ }>;
101
+ export interface Host {
102
+ readonly profile: ProfileDirectory;
103
+ readonly sessions: {
104
+ open(input: SessionOpening): Promise<HostSession>;
105
+ begin(intent: SessionIntent): Promise<HostSession>;
106
+ turn(session: HostSession, input: Readonly<{
107
+ learnerMessage?: string;
108
+ }>): Promise<HostChatSetup>;
109
+ /** After the conversation stops, close a completed Lesson and return its next surface. */
110
+ settle(session: HostSession): Promise<ModeSwitch | undefined>;
111
+ close(session: HostSession): Promise<void>;
112
+ };
113
+ readonly missions: {
114
+ list(): Promise<readonly MissionReading[]>;
115
+ create(mission: Mission): Promise<void>;
116
+ revise(mission: Mission): Promise<void>;
117
+ retire(id: string, outcome: "achieved" | "abandoned"): Promise<void>;
118
+ };
119
+ reading(): Promise<HostReading>;
120
+ readonly hub: {
121
+ pull(address: string): Promise<ExactPatchRef>;
122
+ signIn(): Promise<void>;
123
+ publish(input: Readonly<{
124
+ patch: ExactPatchRef;
125
+ version: string;
126
+ title: string;
127
+ description?: string;
128
+ }>): Promise<HubRelease>;
129
+ exportTo(destination: "web"): Promise<void>;
130
+ importFrom(source: "web"): Promise<ImportResult>;
131
+ };
132
+ readonly config: {
133
+ read(): Promise<HostConfig>;
134
+ update(config: HostConfig): Promise<void>;
135
+ };
136
+ }
137
+ export interface HubOptions {
138
+ /** Product/version token for anonymous Hub reads; defaults to @mmon-co/ncept-local's installed version. */
139
+ readonly userAgent?: string;
140
+ /** Application base URL, including /ncept on the hosted product. Defaults to https://co.mmon.co/ncept. */
141
+ readonly url?: string;
142
+ /** Public native-client metadata document for issuers using CIMD instead of dynamic registration. */
143
+ readonly clientMetadataUrl?: string;
144
+ /** Outside the Profile; defaults to credentialsPath(). */
145
+ readonly credentialsFile?: string;
146
+ /** Front ends may present this URL themselves; otherwise the system browser is opened. */
147
+ readonly openUrl?: (url: string) => Promise<void>;
148
+ }
149
+ export interface OpenHostOptions<S> {
150
+ readonly hub?: HubOptions;
151
+ readonly profileDir: string;
152
+ /** Executable values supplied by the front end, resolved with Core's resolveTheory. */
153
+ readonly theories: readonly Theory<S>[];
154
+ readonly model: Model;
155
+ readonly confirm: Confirm;
156
+ }
157
+ export { openHost } from "./learning.js";