@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,834 @@
1
+ import { isMission, isMissionRevision, isRunActiveChange, isRunPastEntry, isRunRetirement, nodeCascadedProperty, readMissionPath, readMissionRun, retire, selectGraph, setActive, tagIndex, } from "@mmon-co/ncept-core";
2
+ import { openProfile } from "./directory.js";
3
+ import { connectHub } from "./hub.js";
4
+ import { checkedTimezone, learnerDayAt } from "./days.js";
5
+ import { localPayload, localSettings, platform, Runtime, sessionStates, transcript, } from "./runtime.js";
6
+ import { hostTools } from "./host-tools.js";
7
+ import { mechanics } from "./mechanics.js";
8
+ import { isSurface, modeEntry } from "./inputs.js";
9
+ import { object, parsePiSession } from "./sessions.js";
10
+ import { reviewStop, sessionLength } from "./session-policy.js";
11
+ function readMissions(view, complete = false) {
12
+ const projection = view.theory.project(view.graph, view.state);
13
+ const sessions = runs(sessionStates(view.profile));
14
+ return missions(view.profile).map((mission) => {
15
+ const run = missionRun(view.profile, mission.id);
16
+ const context = { graph: view.graph, projection, observations: view.observations, activities: [] };
17
+ const path = view.theory.path?.({
18
+ ...context,
19
+ targets: mission.targets.map(({ node }) => node),
20
+ past: run.past,
21
+ now: view.now,
22
+ minutes: sessionLength(localSettings(view.profile)),
23
+ ...(run.retired ? { retired: run.retired } : {}),
24
+ });
25
+ const itinerary = path ? readMissionPath(path, view.theory, context) : undefined;
26
+ const structured = itinerary?.sections.flatMap(({ lessons }) => lessons) ?? [];
27
+ return {
28
+ mission,
29
+ run: readMissionRun(run, sessions, complete ? run.past.length : 20),
30
+ path: itinerary,
31
+ next: (path?.future ?? [])
32
+ .filter((stop) => {
33
+ if (!stop.checkpoint || stop.checkpoint.required)
34
+ return true;
35
+ const progress = view.theory.progress(view.graph, projection, stop.nodes);
36
+ return stop.nodes.some((node) => !progress[node] || progress[node].status === "open");
37
+ })
38
+ .map((lesson, index) => ({
39
+ ...(structured.find((item) => item.kind === lesson.kind &&
40
+ item.tag === lesson.tag &&
41
+ JSON.stringify(item.nodes) === JSON.stringify(lesson.nodes)) ?? { ...lesson, number: index + 1, cleared: false }),
42
+ name: lesson.name ??
43
+ lesson.nodes.map((node) => stringProperty(view.graph, node, "display:label", node)).join(", "),
44
+ })),
45
+ };
46
+ });
47
+ }
48
+ /** Read current learning state without day processing, receipts, configuration writes or model calls. */
49
+ export async function openLearningReader(profileDir, theories) {
50
+ const profile = await openProfile(profileDir, theories, { readOnly: true });
51
+ const settings = localSettings(await profile.read());
52
+ const timezone = checkedTimezone(typeof settings.timezone === "string" ? settings.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
53
+ const runtime = new Runtime(profile, theories, async () => {
54
+ throw new Error("A learning read cannot request a model");
55
+ }, timezone);
56
+ return {
57
+ async reading() {
58
+ const view = await runtime.snapshot();
59
+ const projection = view.theory.project(view.graph, view.state);
60
+ const progress = view.theory.progress(view.graph, projection, view.graph.nodes.map(({ id }) => id));
61
+ const dueReview = [...tagIndex(projection)("review:due")];
62
+ const label = (id) => stringProperty(view.graph, id, "display:label", id);
63
+ return {
64
+ missions: readMissions(view, true),
65
+ nodes: view.graph.nodes.map(({ id }) => ({ id, label: label(id), status: progress[id]?.status ?? "open" })),
66
+ dueReview: dueReview.map((id) => ({ id, label: label(id) })),
67
+ sessions: sessionStates(view.profile).map((session) => ({
68
+ ...session,
69
+ title: sessionTitle(session, view.profile, label),
70
+ missionLabel: missions(view.profile).find((mission) => mission.id === session.mission)?.statement,
71
+ nodes: session.about.map((id) => ({ id, label: label(id) })),
72
+ })),
73
+ };
74
+ },
75
+ };
76
+ }
77
+ function sessionTitle(session, profile, label) {
78
+ const entry = session.entry;
79
+ const mode = session.mode.charAt(0).toUpperCase() + session.mode.slice(1);
80
+ let title = mode;
81
+ if (entry?.kind === "review")
82
+ title = "Review · " + entry.nodes.length + " due";
83
+ else {
84
+ const name = entry?.kind === "lesson"
85
+ ? entry.lesson.name
86
+ : entry?.kind === "mission"
87
+ ? missions(profile).find((mission) => mission.id === entry.id)?.statement
88
+ : entry?.kind === "target"
89
+ ? label(entry.node)
90
+ : entry?.kind === "goal"
91
+ ? entry.text
92
+ : undefined;
93
+ if (name)
94
+ title += " · " + name;
95
+ }
96
+ return title.slice(0, 200);
97
+ }
98
+ function identity() {
99
+ return crypto.randomUUID();
100
+ }
101
+ function stringProperty(graph, id, key, fallback) {
102
+ const value = nodeCascadedProperty(graph, id, key);
103
+ return typeof value === "string" ? value : fallback;
104
+ }
105
+ function missionRun(profile, mission) {
106
+ let active = null;
107
+ let retired;
108
+ const past = new Map();
109
+ for (const entry of profile.log) {
110
+ if (isRunPastEntry(entry) && entry.mission === mission)
111
+ past.set(entry.sequence, entry.entry);
112
+ if (isRunActiveChange(entry) && entry.mission === mission)
113
+ active = entry.active;
114
+ if (isRunRetirement(entry) && entry.mission === mission)
115
+ retired = { outcome: entry.outcome, at: entry.at };
116
+ }
117
+ return {
118
+ mission,
119
+ active,
120
+ past: [...past].sort(([a], [b]) => a - b).map(([, entry]) => entry),
121
+ ...(retired ? { retired } : {}),
122
+ };
123
+ }
124
+ function missions(profile) {
125
+ const revisions = new Map();
126
+ for (const entry of profile.log)
127
+ if (isMissionRevision(entry))
128
+ revisions.set(entry.mission.id, entry.mission);
129
+ return [...revisions.values()].sort((a, b) => b.priority - a.priority);
130
+ }
131
+ function runs(sessions) {
132
+ return sessions.map((session) => ({
133
+ ref: session.id,
134
+ open: !session.closed,
135
+ ...(session.parent === undefined ? {} : { parent: session.parent }),
136
+ }));
137
+ }
138
+ function runEntries(before, after, at) {
139
+ return [
140
+ ...after.past.slice(before.past.length).map((entry, index) => ({
141
+ kind: "run.past",
142
+ id: identity(),
143
+ at: entry.at,
144
+ mission: after.mission,
145
+ sequence: before.past.length + index,
146
+ entry,
147
+ })),
148
+ ...(before.active !== after.active
149
+ ? [
150
+ {
151
+ kind: "run.active",
152
+ id: identity(),
153
+ at,
154
+ mission: after.mission,
155
+ active: after.active,
156
+ },
157
+ ]
158
+ : []),
159
+ ...(!before.retired && after.retired
160
+ ? [
161
+ {
162
+ kind: "run.retired",
163
+ id: identity(),
164
+ at,
165
+ mission: after.mission,
166
+ outcome: after.retired.outcome,
167
+ },
168
+ ]
169
+ : []),
170
+ ];
171
+ }
172
+ /** Owns execution serialization; the front end owns pi's conversation and transcript writer. */
173
+ export class LearningHost {
174
+ runtime;
175
+ confirm;
176
+ tail = Promise.resolve();
177
+ pendingSwitch;
178
+ drafts = new Map();
179
+ constructor(runtime, confirm) {
180
+ this.runtime = runtime;
181
+ this.confirm = confirm;
182
+ }
183
+ serial(operation) {
184
+ const result = this.tail.then(operation);
185
+ this.tail = result.catch(() => { });
186
+ return result;
187
+ }
188
+ async reload() {
189
+ this.pendingSwitch = undefined;
190
+ this.drafts.clear();
191
+ const { timezone } = localSettings(await this.runtime.profile.read());
192
+ this.runtime.timezone = checkedTimezone(typeof timezone === "string" ? timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
193
+ await this.start();
194
+ }
195
+ async current(session) {
196
+ const state = sessionStates(await this.runtime.profile.read()).find(({ id }) => id === session.id);
197
+ if (!state)
198
+ throw new Error("Unknown Session");
199
+ return state;
200
+ }
201
+ mode(theory, mode, entry) {
202
+ if (entry)
203
+ modeEntry(entry);
204
+ const selected = theory.modes?.[mode];
205
+ if (theory.modes && !selected)
206
+ throw new Error("Unknown Theory mode: " + mode);
207
+ if (selected && ((selected.entry.required && !entry) || (entry && !selected.entry.kinds.includes(entry.kind))))
208
+ throw new Error("Invalid entry for " + mode + "; expected " + selected.entry.kinds.join(", "));
209
+ return selected;
210
+ }
211
+ async missionReadings() {
212
+ return readMissions(await this.runtime.snapshot());
213
+ }
214
+ async lessonEntry(missionId, number) {
215
+ const view = await this.runtime.snapshot();
216
+ const reading = (await this.missionReadings()).find(({ mission }) => mission.id === missionId);
217
+ if (!reading)
218
+ throw new Error("Unknown Mission");
219
+ const context = {
220
+ graph: view.graph,
221
+ projection: view.theory.project(view.graph, view.state),
222
+ observations: view.observations,
223
+ activities: [],
224
+ };
225
+ const future = view.theory.path?.({
226
+ ...context,
227
+ targets: reading.mission.targets.map(({ node }) => node),
228
+ past: reading.run.past,
229
+ now: view.now,
230
+ minutes: sessionLength(localSettings(view.profile)),
231
+ });
232
+ if (!future)
233
+ throw new Error("Theory provides no Mission path");
234
+ const path = readMissionPath(future, view.theory, context);
235
+ const section = path.sections.find(({ lessons }) => lessons.some((lesson) => lesson.kind === "lesson" && (number === undefined ? !lesson.cleared : lesson.number === number)));
236
+ const lesson = section?.lessons.find((lesson) => lesson.kind === "lesson" && (number === undefined ? !lesson.cleared : lesson.number === number));
237
+ if (!section || !lesson)
238
+ throw new Error("No matching Lesson in this Mission");
239
+ return {
240
+ kind: "lesson",
241
+ lesson: {
242
+ mission: { id: reading.mission.id, statement: reading.mission.statement },
243
+ number: lesson.number,
244
+ of: path.lessonCount,
245
+ name: lesson.name ?? lesson.nodes.map((id) => stringProperty(view.graph, id, "display:label", id)).join(", "),
246
+ section: {
247
+ number: section.number,
248
+ milestone: section.milestone,
249
+ name: stringProperty(view.graph, section.milestone, "display:label", section.milestone),
250
+ },
251
+ nodes: lesson.nodes,
252
+ },
253
+ };
254
+ }
255
+ async reading() {
256
+ const view = await this.runtime.snapshot();
257
+ return {
258
+ missions: await this.missionReadings(),
259
+ dueReview: [...tagIndex(view.theory.project(view.graph, view.state))("review:due")],
260
+ };
261
+ }
262
+ async reviseMission(mission, create) {
263
+ if (!isMission(mission))
264
+ throw new Error("Invalid Mission");
265
+ const view = await this.runtime.snapshot();
266
+ const exists = missions(view.profile).some(({ id }) => id === mission.id);
267
+ if (exists === create)
268
+ throw new Error(create ? "Mission already exists" : "Unknown Mission");
269
+ for (const target of mission.targets) {
270
+ if (!view.graph.nodes.some(({ id }) => id === target.node))
271
+ throw new Error("Mission target is not in the graph");
272
+ const source = await this.runtime.snapshot(target.provenance);
273
+ if (!source.graph.nodes.some(({ id }) => id === target.node))
274
+ throw new Error("Invalid Mission target provenance");
275
+ }
276
+ const event = await this.runtime.event({ kind: "mission", text: mission.statement });
277
+ await this.runtime.profile.appendLog([
278
+ { kind: "mission.revised", id: identity(), at: view.now, mission },
279
+ ...event.entries,
280
+ ]);
281
+ }
282
+ async closing(session) {
283
+ if (session.closed)
284
+ return [];
285
+ const view = await this.runtime.snapshot();
286
+ const conversation = transcript(view.profile, session.surface);
287
+ const event = await this.runtime.event({
288
+ kind: "surface.close",
289
+ surface: session.surface,
290
+ about: session.about,
291
+ span: conversation.span,
292
+ }, session);
293
+ return [
294
+ ...event.entries,
295
+ platform({ kind: "local.session", session: { ...session, closed: true } }, session.surface),
296
+ ];
297
+ }
298
+ async closingRun(current, profile) {
299
+ const known = sessionStates(profile);
300
+ const closing = new Set([current.id]);
301
+ for (const id of closing)
302
+ for (const child of known)
303
+ if (!child.closed && child.parent === id)
304
+ closing.add(child.id);
305
+ const entries = [];
306
+ if (current.mission) {
307
+ const before = missionRun(profile, current.mission);
308
+ if (before.active === current.id) {
309
+ const at = new Date().toISOString();
310
+ const result = setActive(before, { kind: "none" }, at, runs(known));
311
+ for (const id of result.close)
312
+ closing.add(id);
313
+ entries.push(...runEntries(before, result.run, at));
314
+ }
315
+ }
316
+ for (const session of known)
317
+ if (closing.has(session.id))
318
+ entries.push(...(await this.closing(session)));
319
+ return entries;
320
+ }
321
+ async close(session) {
322
+ const current = await this.current(session);
323
+ await this.runtime.profile.appendLog(await this.closingRun(current, await this.runtime.profile.read()));
324
+ }
325
+ async settle(session) {
326
+ const current = await this.current(session);
327
+ if (current.closed || current.mode !== "lesson" || current.entry?.kind !== "lesson")
328
+ return;
329
+ if (!(await this.context(current)).lesson?.complete)
330
+ return;
331
+ await this.close(current);
332
+ return {
333
+ mode: "charting",
334
+ then: "next",
335
+ carry: { kind: "brief" },
336
+ entry: { kind: "mission", id: current.entry.lesson.mission.id },
337
+ };
338
+ }
339
+ async retireMission(id, outcome) {
340
+ const view = await this.runtime.snapshot();
341
+ if (!missions(view.profile).some((mission) => mission.id === id))
342
+ throw new Error("Unknown Mission");
343
+ const before = missionRun(view.profile, id);
344
+ const cleared = setActive(before, { kind: "none" }, view.now, runs(sessionStates(view.profile)));
345
+ const after = retire(cleared.run, outcome, view.now);
346
+ // Retirement changes the Mission run. Its conversations may still be mid-turn;
347
+ // their processes own Session closure and can finish recording that turn.
348
+ await this.runtime.profile.appendLog(runEntries(before, after, view.now));
349
+ }
350
+ async begin(intent) {
351
+ if (intent.kind === "new-mission")
352
+ return this.open({ mode: "charting" });
353
+ if (intent.kind === "review") {
354
+ const view = await this.runtime.snapshot();
355
+ const stop = reviewStop(view.theory, {
356
+ graph: view.graph,
357
+ projection: view.theory.project(view.graph, view.state),
358
+ observations: view.observations,
359
+ activities: [],
360
+ past: [],
361
+ now: view.now,
362
+ minutes: sessionLength(localSettings(view.profile)),
363
+ });
364
+ if (!stop?.nodes.length)
365
+ throw new Error("No review due");
366
+ return this.open({ mode: "lesson", entry: { kind: "review", nodes: stop.nodes } });
367
+ }
368
+ if (!("missionId" in intent))
369
+ throw new Error("Expected a Mission entry");
370
+ const reading = (await this.missionReadings()).find(({ mission }) => mission.id === intent.missionId);
371
+ if (!reading || reading.run.retired?.outcome === "abandoned")
372
+ throw new Error("Mission is not available");
373
+ const { mission, run, next } = reading;
374
+ if (intent.kind === "continue" && run.active)
375
+ return this.open({ mode: "empty", resume: run.active });
376
+ if (run.retired && intent.kind !== "continue")
377
+ throw new Error("A finished Mission can only continue or resume a Session");
378
+ if (intent.kind === "skip-lesson" || intent.kind === "skip-to")
379
+ return this.open({ mode: "lesson", skip: { ...intent, mission: mission.id } });
380
+ if (intent.kind === "tell-tutor" && !intent.request.trim())
381
+ throw new Error("Tell the tutor what you want to change");
382
+ if (intent.kind === "revise-lesson") {
383
+ const view = await this.runtime.snapshot();
384
+ const active = sessionStates(view.profile).find(({ id }) => id === run.active);
385
+ if (active?.entry?.kind !== "lesson")
386
+ throw new Error("There is no active Lesson to revise");
387
+ return this.open({ mode: "lesson", entry: active.entry });
388
+ }
389
+ if (intent.kind === "tell-tutor" || intent.kind === "revise-route" || !mission.targets.length)
390
+ return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
391
+ const stop = next[0];
392
+ if (stop?.kind === "review")
393
+ return this.open({ mode: "lesson", entry: { kind: "review", nodes: stop.nodes }, mission: mission.id });
394
+ if (run.retired)
395
+ throw new Error("No review is due for this finished Mission");
396
+ if (!stop)
397
+ throw new Error("This Mission has no following stop; revise the route or finish it");
398
+ if (stop.checkpoint)
399
+ return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
400
+ return this.open({ mode: "lesson", entry: await this.lessonEntry(mission.id, stop.number) });
401
+ }
402
+ async open(input) {
403
+ const skipMission = input.skip?.mission;
404
+ let skipped = [];
405
+ if (input.skip) {
406
+ if (input.resume || input.entry)
407
+ throw new Error("A skip cannot resume or supply an entry");
408
+ const reading = (await this.missionReadings()).find(({ mission }) => mission.id === input.skip?.mission);
409
+ if (!reading)
410
+ throw new Error("Unknown Mission");
411
+ if (reading.run.retired)
412
+ throw new Error("A finished Mission can only continue or resume a Session");
413
+ const view = await this.runtime.snapshot();
414
+ const context = {
415
+ graph: view.graph,
416
+ projection: view.theory.project(view.graph, view.state),
417
+ observations: view.observations,
418
+ activities: [],
419
+ };
420
+ const future = view.theory.path?.({
421
+ ...context,
422
+ targets: reading.mission.targets.map(({ node }) => node),
423
+ past: reading.run.past,
424
+ now: view.now,
425
+ minutes: sessionLength(localSettings(view.profile)),
426
+ });
427
+ if (!future)
428
+ throw new Error("Theory provides no Mission path");
429
+ const stops = readMissionPath(future, view.theory, context).sections.flatMap(({ lessons }) => lessons);
430
+ const frozen = reading.run.past.find((entry) => entry.kind === "session" && entry.session === reading.run.active);
431
+ const frozenStop = frozen?.kind === "session" ? frozen.stop : undefined;
432
+ const activeIndex = frozenStop
433
+ ? stops.findIndex((stop) => stop.kind === frozenStop.kind &&
434
+ stop.nodes.length === frozenStop.nodes?.length &&
435
+ stop.nodes.every((node) => frozenStop.nodes?.includes(node)))
436
+ : -1;
437
+ const now = activeIndex >= 0 ? activeIndex : stops.findIndex((stop) => !stop.cleared);
438
+ const skip = input.skip;
439
+ const index = skip.kind === "skip-lesson"
440
+ ? now + 1
441
+ : stops.findIndex((stop) => stop.kind === skip.stop.kind &&
442
+ stop.number === skip.stop.number &&
443
+ stop.checkpoint?.milestone === skip.stop.checkpoint?.milestone);
444
+ if (index < 0 || !stops[index])
445
+ throw new Error("This Mission has no following stop; revise the route or finish it");
446
+ if (skip.kind === "skip-to") {
447
+ if (now < 0 || index <= now)
448
+ throw new Error("Choose a stop after the current stop");
449
+ skipped = stops.slice(now, index);
450
+ }
451
+ const stop = stops[index];
452
+ const entry = stop.kind === "review"
453
+ ? { kind: "review", nodes: stop.nodes }
454
+ : stop.checkpoint
455
+ ? { kind: "mission", id: reading.mission.id }
456
+ : await this.lessonEntry(reading.mission.id, stop.number);
457
+ input = { mode: stop.checkpoint ? "charting" : "lesson", entry };
458
+ }
459
+ const view = await this.runtime.snapshot();
460
+ const known = sessionStates(view.profile);
461
+ let resumed = input.resume ? known.find(({ id }) => id === input.resume) : undefined;
462
+ if (input.resume && !resumed) {
463
+ for (const [surface, source] of view.profile.sessions) {
464
+ const imported = parsePiSession(source);
465
+ if (isSurface(surface) && (imported.header.id === input.resume || surface === input.resume)) {
466
+ resumed = {
467
+ id: imported.header.id,
468
+ surface,
469
+ mode: input.mode,
470
+ about: input.entry?.kind === "review"
471
+ ? input.entry.nodes
472
+ : input.entry?.kind === "lesson"
473
+ ? input.entry.lesson.nodes
474
+ : input.entry?.kind === "target"
475
+ ? [input.entry.node]
476
+ : [
477
+ ...new Set(view.observations
478
+ .filter((observation) => observation.surface === surface)
479
+ .flatMap((observation) => observation.nodes ?? observation.about ?? [])),
480
+ ],
481
+ closed: true,
482
+ ...(input.entry === undefined ? {} : { entry: input.entry }),
483
+ };
484
+ break;
485
+ }
486
+ }
487
+ if (!resumed)
488
+ throw new Error("Unknown trusted Session to resume");
489
+ }
490
+ const mode = resumed?.mode ?? input.mode;
491
+ const entry = resumed?.entry ?? input.entry;
492
+ this.mode(view.theory, mode, entry);
493
+ const pending = !resumed &&
494
+ this.pendingSwitch?.to.mode === mode &&
495
+ JSON.stringify(this.pendingSwitch.to.entry) === JSON.stringify(entry)
496
+ ? this.pendingSwitch
497
+ : undefined;
498
+ const missionId = resumed?.mission ??
499
+ (entry?.kind === "mission"
500
+ ? entry.id
501
+ : entry?.kind === "lesson"
502
+ ? entry.lesson.mission.id
503
+ : entry?.kind === "checkpoint"
504
+ ? entry.missionId
505
+ : (input.mission ?? skipMission ?? pending?.from.mission));
506
+ const mission = missionId ? missions(view.profile).find(({ id }) => id === missionId) : undefined;
507
+ if (missionId && !mission)
508
+ throw new Error("Unknown Mission");
509
+ const about = resumed?.about ??
510
+ (entry?.kind === "target"
511
+ ? [entry.node]
512
+ : entry?.kind === "review"
513
+ ? entry.nodes
514
+ : entry?.kind === "lesson"
515
+ ? entry.lesson.nodes
516
+ : mission
517
+ ? selectGraph(view.graph, { cone: { targets: mission.targets.map(({ node }) => node) } }).nodes.map(({ id }) => id)
518
+ : []);
519
+ for (const node of about)
520
+ if (!view.graph.nodes.some(({ id }) => id === node))
521
+ throw new Error("Missing Node " + node);
522
+ const id = resumed?.id ?? identity();
523
+ const session = {
524
+ id,
525
+ surface: resumed?.surface ?? `surface-${id}`,
526
+ mode,
527
+ about,
528
+ closed: false,
529
+ ...(entry === undefined ? {} : { entry }),
530
+ ...(missionId === undefined ? {} : { mission: missionId }),
531
+ ...(pending?.to.then === "aside"
532
+ ? { parent: pending.from.id }
533
+ : resumed?.parent
534
+ ? { parent: resumed.parent }
535
+ : {}),
536
+ };
537
+ const entries = [];
538
+ if (missionId) {
539
+ const before = missionRun(view.profile, missionId);
540
+ const stop = {
541
+ kind: entry?.kind ?? mode,
542
+ name: entry?.kind === "lesson" ? entry.lesson.name : mode,
543
+ nodes: about,
544
+ };
545
+ const target = resumed && before.past.some((entry) => entry.kind === "session" && entry.session === id)
546
+ ? { kind: "resume", session: id }
547
+ : pending?.to.then === "aside"
548
+ ? { kind: "aside", session: id }
549
+ : { kind: "new", session: id, stop };
550
+ // A fresh front end adopting an open aside keeps it beside its parent.
551
+ const result = resumed?.parent === before.active && !resumed.closed
552
+ ? { run: before, close: [] }
553
+ : setActive(before, target, view.now, runs(known));
554
+ entries.push(...runEntries(before, result.run, view.now));
555
+ for (const ref of result.close) {
556
+ const outgoing = known.find(({ id }) => id === ref);
557
+ if (outgoing)
558
+ entries.push(...(await this.closing(outgoing)));
559
+ }
560
+ }
561
+ if (pending?.to.then === "next" && (!missionId || pending.from.mission !== missionId))
562
+ entries.push(...(await this.closingRun(pending.from, view.profile)));
563
+ const event = await this.runtime.event({ kind: "surface.open", surface: session.surface, format: "local", about }, session);
564
+ entries.push(...event.entries, platform({ kind: "local.session", session }, session.surface));
565
+ if (skipped.length) {
566
+ const nodes = [...new Set(skipped.flatMap((stop) => stop.nodes))];
567
+ const ctx = { ...(await this.runtime.context(session)), about: nodes };
568
+ const selected = view.theory.modes?.lesson;
569
+ const setup = selected ? await this.runtime.execute(selected.setup(ctx), session) : undefined;
570
+ const flatten = (tools) => tools.flatMap((tool) => (tool.members ? flatten(tool.members) : [tool]));
571
+ const tools = flatten(setup?.tools ?? []);
572
+ const record = tools.find((tool) => tool.name === "record_claim");
573
+ const attach = tools.find((tool) => tool.name === "attach_claim");
574
+ if (!record || !attach)
575
+ throw new Error("The theory needs claim recording and attachment");
576
+ const recordClaim = record.run;
577
+ const attachClaim = attach.run;
578
+ function* claims() {
579
+ for (const node of nodes) {
580
+ const result = yield* recordClaim({
581
+ statement: "I already know " + stringProperty(view.graph, node, "display:label", node) + ".",
582
+ prompt: "Skip to a later stop, marking the intervening stops as known",
583
+ stance: "knows",
584
+ }, ctx);
585
+ if (!object(result) || !object(result.observation) || typeof result.observation.id !== "string")
586
+ throw new Error("Claim recording returned no observation identity");
587
+ const id = result.observation.id;
588
+ yield* attachClaim({ record: id, nodes: [node] }, ctx);
589
+ }
590
+ }
591
+ entries.push(...(await this.runtime.prepare(claims(), session)).entries);
592
+ }
593
+ await this.runtime.profile.appendLog(entries);
594
+ if (pending)
595
+ this.pendingSwitch = undefined;
596
+ return session;
597
+ }
598
+ async switchMode(session, to) {
599
+ const view = await this.runtime.snapshot();
600
+ const selected = this.mode(view.theory, session.mode, session.entry);
601
+ if (!selected?.switches.some((allowed) => allowed.mode === to.mode && allowed.then === to.then))
602
+ throw new Error("This mode does not allow that switch");
603
+ this.mode(view.theory, to.mode, to.entry);
604
+ if (to.then === "here") {
605
+ const missionId = to.entry?.kind === "lesson"
606
+ ? to.entry.lesson.mission.id
607
+ : to.entry?.kind === "mission"
608
+ ? to.entry.id
609
+ : to.entry?.kind === "checkpoint"
610
+ ? to.entry.missionId
611
+ : session.mission;
612
+ const mission = missions(view.profile).find(({ id }) => id === missionId);
613
+ if (missionId && !mission)
614
+ throw new Error("Unknown Mission");
615
+ const about = to.entry?.kind === "review"
616
+ ? to.entry.nodes
617
+ : to.entry?.kind === "lesson"
618
+ ? to.entry.lesson.nodes
619
+ : to.entry?.kind === "target"
620
+ ? [to.entry.node]
621
+ : mission
622
+ ? selectGraph(view.graph, { cone: { targets: mission.targets.map(({ node }) => node) } }).nodes.map(({ id }) => id)
623
+ : session.about;
624
+ for (const node of about)
625
+ if (!view.graph.nodes.some(({ id }) => id === node))
626
+ throw new Error("Missing Node " + node);
627
+ const updated = {
628
+ ...session,
629
+ mode: to.mode,
630
+ entry: to.entry,
631
+ about,
632
+ ...(missionId ? { mission: missionId } : {}),
633
+ };
634
+ const entries = [];
635
+ if (missionId) {
636
+ const before = missionRun(view.profile, missionId);
637
+ const attached = before.past.some((entry) => entry.kind === "session" && entry.session === session.id);
638
+ const result = setActive(before, { kind: attached ? "resume" : "attach", session: session.id }, view.now, runs(sessionStates(view.profile)));
639
+ entries.push(...runEntries(before, result.run, view.now));
640
+ for (const id of result.close) {
641
+ const outgoing = sessionStates(view.profile).find((item) => item.id === id);
642
+ if (outgoing)
643
+ entries.push(...(await this.closing(outgoing)));
644
+ }
645
+ }
646
+ entries.push(platform({ kind: "local.session", session: updated }, session.surface));
647
+ await this.runtime.profile.appendLog(entries);
648
+ }
649
+ else
650
+ this.pendingSwitch = { from: session, to };
651
+ }
652
+ async context(session) {
653
+ const view = await this.runtime.snapshot();
654
+ const ctx = await this.runtime.context(session);
655
+ const readings = await this.missionReadings();
656
+ let lesson;
657
+ if (session.entry?.kind === "lesson") {
658
+ const snapshot = session.entry.lesson;
659
+ const projection = view.theory.project(ctx.graph, ctx.state);
660
+ const progress = view.theory.progress(ctx.graph, projection, snapshot.nodes);
661
+ const nodes = snapshot.nodes.map((id) => ({
662
+ id,
663
+ label: stringProperty(ctx.graph, id, "display:label", id),
664
+ criterion: stringProperty(ctx.graph, id, "pedagogy:criterion", ""),
665
+ status: progress[id]?.status ?? "open",
666
+ ...(progress[id]?.unavailable ? { unavailable: true } : {}),
667
+ ...(progress[id]?.display ? { score: progress[id].display } : {}),
668
+ }));
669
+ const estimate = view.theory.estimate({
670
+ graph: ctx.graph,
671
+ projection,
672
+ observations: view.observations,
673
+ activities: [],
674
+ }, [{ kind: "lesson", nodes: snapshot.nodes, numbered: true }]);
675
+ lesson = {
676
+ lesson: snapshot,
677
+ nodes,
678
+ edges: ctx.graph.edges.filter(({ from, to }) => snapshot.nodes.includes(from) && snapshot.nodes.includes(to)),
679
+ alsoShown: [],
680
+ doneCount: nodes.filter(({ status }) => status === "done").length,
681
+ complete: nodes.every(({ status }) => status === "done"),
682
+ minutesLeft: estimate.minutes,
683
+ rough: estimate.rough,
684
+ };
685
+ }
686
+ return {
687
+ ...ctx,
688
+ ...(lesson ? { lesson } : {}),
689
+ missions: readings.map(({ mission, run, next }) => ({
690
+ id: mission.id,
691
+ statement: mission.statement,
692
+ change: view.profile.log.filter(isMissionRevision).findLast((entry) => entry.mission.id === mission.id)?.id ??
693
+ mission.id,
694
+ nodes: selectGraph(view.graph, { cone: { targets: mission.targets.map(({ node }) => node) } }).nodes.map(({ id }) => id),
695
+ targets: mission.targets.map(({ node }) => node),
696
+ priority: mission.priority,
697
+ run: { ...run, next },
698
+ })),
699
+ };
700
+ }
701
+ async turn(input, learnerMessage) {
702
+ const session = await this.current(input);
703
+ if (session.closed)
704
+ throw new Error("Session is closed; resume it first");
705
+ let view = await this.runtime.snapshot();
706
+ let ctx = await this.context(session);
707
+ if (learnerMessage !== undefined && view.theory.chat?.reply) {
708
+ await this.runtime.execute(view.theory.chat.reply(ctx, learnerMessage), session);
709
+ view = await this.runtime.snapshot();
710
+ ctx = await this.context(session);
711
+ }
712
+ if (learnerMessage === undefined && transcript(view.profile, session.surface).turns.length === 0) {
713
+ const latest = sessionStates(view.profile)
714
+ .flatMap(({ surface }) => transcript(view.profile, surface).turns)
715
+ .filter(({ speaker, text }) => speaker.kind === "learner" && text.trim() !== "")
716
+ .sort((a, b) => b.at.localeCompare(a.at))[0];
717
+ ctx = {
718
+ ...ctx,
719
+ opening: { latestLearnerMessage: latest ? Array.from(latest.text).slice(0, 400).join("") : undefined },
720
+ };
721
+ }
722
+ const selected = this.mode(view.theory, session.mode, session.entry);
723
+ const program = selected ? selected.setup(ctx) : view.theory.chat?.turn(ctx);
724
+ if (!program)
725
+ throw new Error("Theory does not provide a tutor setup");
726
+ const setup = await this.runtime.execute(program, session);
727
+ const native = (tools) => tools.flatMap((tool) => (tool.members ? native(tool.members) : [tool]));
728
+ const capabilities = selected?.capabilities ?? [];
729
+ const tools = native(setup.tools).map((tool) => ({
730
+ name: tool.name,
731
+ description: tool.description,
732
+ schema: tool.schema,
733
+ run: (args) => this.serial(async () => {
734
+ const current = await this.current(session);
735
+ if (current.closed || current.mode !== session.mode)
736
+ throw new Error("Tool belongs to an inactive Session mode");
737
+ const result = await this.runtime.prepare(tool.run(args, await this.context(current)), current);
738
+ const feature = await this.runtime.event({ kind: "feature.used", operation: tool.name, at: new Date().toISOString(), about: current.about }, current);
739
+ await this.runtime.profile.appendLog([...result.entries, ...feature.entries]);
740
+ return { content: result.value };
741
+ }),
742
+ }));
743
+ const settings = localSettings(view.profile);
744
+ return {
745
+ ...setup,
746
+ prompt: setup.prompt +
747
+ (typeof settings.preferences === "string" ? "\n\nLearner preferences:\n" + settings.preferences : ""),
748
+ capabilities,
749
+ context: [
750
+ setup.context,
751
+ "Local host (native tools, not catalog envelopes):\n" +
752
+ JSON.stringify({
753
+ mode: session.mode,
754
+ capabilities,
755
+ switches: selected?.switches ?? [],
756
+ entries: Object.fromEntries(Object.entries(view.theory.modes ?? {}).map(([name, mode]) => [name, mode.entry])),
757
+ }),
758
+ ]
759
+ .filter(Boolean)
760
+ .join("\n\n"),
761
+ tools: [...tools, ...hostTools(this, session, capabilities, setup.skills, selected?.metadataKeys ?? [])],
762
+ skills: [...setup.skills, mechanics],
763
+ };
764
+ }
765
+ async config() {
766
+ const profile = await this.runtime.profile.read();
767
+ return {
768
+ theory: profile.manifest.theory,
769
+ theories: profile.manifest.theories,
770
+ timezone: this.runtime.timezone,
771
+ sessionLength: sessionLength(localSettings(profile)),
772
+ };
773
+ }
774
+ async configure(config) {
775
+ const timezone = checkedTimezone(config.timezone ?? this.runtime.timezone);
776
+ const minutes = sessionLength(config);
777
+ await this.runtime.profile.configure({ theory: config.theory, theories: config.theories });
778
+ await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone, sessionLength: minutes })]);
779
+ this.runtime.timezone = timezone;
780
+ }
781
+ async start() {
782
+ const view = await this.runtime.snapshot();
783
+ const lastDay = view.profile.log
784
+ .map((entry) => localPayload(entry, "day.ended"))
785
+ .filter((entry) => entry !== undefined)
786
+ .at(-1);
787
+ const end = lastDay && typeof lastDay.end === "string" ? lastDay.end : undefined;
788
+ let day = learnerDayAt(end ?? view.profile.log[0]?.at ?? view.now, this.runtime.timezone);
789
+ while (Date.parse(day.end) <= Date.parse(view.now)) {
790
+ const event = await this.runtime.event({ kind: "day.ended", day, about: view.graph.nodes.map(({ id }) => id) });
791
+ await this.runtime.profile.appendLog([...event.entries, platform({ kind: "day.ended", ...day })]);
792
+ day = learnerDayAt(day.end, this.runtime.timezone);
793
+ }
794
+ if (typeof localSettings(view.profile).timezone !== "string")
795
+ await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone: this.runtime.timezone })]);
796
+ }
797
+ }
798
+ export async function openHost(options) {
799
+ const profile = await openProfile(options.profileDir, options.theories);
800
+ const config = localSettings(await profile.read());
801
+ const timezone = checkedTimezone(typeof config.timezone === "string" ? config.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
802
+ const learning = new LearningHost(new Runtime(profile, options.theories, options.model, timezone), options.confirm);
803
+ await learning.start();
804
+ const hub = connectHub(profile, options.theories, options.confirm, options.hub);
805
+ return {
806
+ profile,
807
+ sessions: {
808
+ open: (input) => learning.serial(() => learning.open(input)),
809
+ begin: (intent) => learning.serial(() => learning.begin(intent)),
810
+ turn: (session, input) => learning.serial(() => learning.turn(session, input.learnerMessage)),
811
+ settle: (session) => learning.serial(() => learning.settle(session)),
812
+ close: (session) => learning.serial(() => learning.close(session)),
813
+ },
814
+ missions: {
815
+ list: () => learning.missionReadings(),
816
+ create: (mission) => learning.serial(() => learning.reviseMission(mission, true)),
817
+ revise: (mission) => learning.serial(() => learning.reviseMission(mission, false)),
818
+ retire: (id, outcome) => learning.serial(() => learning.retireMission(id, outcome)),
819
+ },
820
+ reading: () => learning.reading(),
821
+ config: { read: () => learning.config(), update: (config) => learning.serial(() => learning.configure(config)) },
822
+ hub: {
823
+ pull: (address) => learning.serial(() => hub.pull(address)),
824
+ signIn: () => learning.serial(() => hub.signIn()),
825
+ publish: (input) => learning.serial(() => hub.publish(input)),
826
+ exportTo: (destination) => learning.serial(() => hub.exportTo(destination)),
827
+ importFrom: (source) => learning.serial(async () => {
828
+ const result = await hub.importFrom(source);
829
+ await learning.reload();
830
+ return result;
831
+ }),
832
+ },
833
+ };
834
+ }