@mmon-co/ncept-pi 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,749 @@
1
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, join, relative } from "node:path";
3
+ import { createRequire } from "node:module";
4
+ import type {
5
+ ExtensionAPI,
6
+ ExtensionContext,
7
+ ExtensionCommandContext,
8
+ BuildSystemPromptOptions,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import type { Theory } from "@mmon-co/ncept-core";
11
+ import { defaultTheory } from "@mmon-co/ncept-default-theory";
12
+ import {
13
+ credentialsPath,
14
+ openHost,
15
+ parsePiSession,
16
+ type Host,
17
+ type HostSession,
18
+ type HostChatSetup,
19
+ type ModeSwitch,
20
+ type ModelRequest,
21
+ type SessionOpening,
22
+ } from "@mmon-co/ncept-local";
23
+ import { ADOPT_SESSION, BEGIN_SESSION, OPEN_SESSION, type BeginSession, type OpenSession } from "./events.js";
24
+
25
+ const { version }: { version: string } = createRequire(import.meta.url)("../package.json");
26
+ const STATE = "ncept.session";
27
+ type Selection = SessionOpening;
28
+
29
+ function storedSession(ctx: ExtensionContext): string | undefined {
30
+ const saved = ctx.sessionManager
31
+ .getBranch()
32
+ .findLast((entry) => entry.type === "custom" && entry.customType === STATE);
33
+ if (saved?.type !== "custom" || !saved.data || typeof saved.data !== "object") return undefined;
34
+ return "id" in saved.data && typeof saved.data.id === "string" ? saved.data.id : undefined;
35
+ }
36
+
37
+ function isBeginSession(value: unknown): value is BeginSession {
38
+ if (
39
+ !value ||
40
+ typeof value !== "object" ||
41
+ !("claim" in value) ||
42
+ typeof value.claim !== "function" ||
43
+ !("intent" in value)
44
+ )
45
+ return false;
46
+ const intent = value.intent;
47
+ if (!intent || typeof intent !== "object" || !("kind" in intent)) return false;
48
+ if (intent.kind === "new-mission" || intent.kind === "review") return true;
49
+ if (!("missionId" in intent) || typeof intent.missionId !== "string") return false;
50
+ return (
51
+ intent.kind === "continue" ||
52
+ intent.kind === "skip-lesson" ||
53
+ (intent.kind === "skip-to" &&
54
+ "stop" in intent &&
55
+ !!intent.stop &&
56
+ typeof intent.stop === "object" &&
57
+ "kind" in intent.stop &&
58
+ typeof intent.stop.kind === "string" &&
59
+ "number" in intent.stop &&
60
+ typeof intent.stop.number === "number") ||
61
+ intent.kind === "revise-lesson" ||
62
+ intent.kind === "revise-route" ||
63
+ (intent.kind === "tell-tutor" && "request" in intent && typeof intent.request === "string")
64
+ );
65
+ }
66
+
67
+ /** One extension instance belongs to one pi session, including after /resume. */
68
+ export default function ncept(pi: ExtensionAPI) {
69
+ let host: Host | undefined;
70
+ let active: HostSession | undefined;
71
+ let context: ExtensionContext;
72
+ let mounted: HostChatSetup | undefined;
73
+ let transition: ModeSwitch | undefined;
74
+ let pendingEnter: ((ctx: ExtensionCommandContext) => Promise<void>) | undefined;
75
+ const ownTools = new Set<string>();
76
+ const graded = new Set<string>();
77
+ let gradeReply = false;
78
+ let relayingContinuation = false;
79
+ let promptOptions: BuildSystemPromptOptions | undefined;
80
+ let importConfirmed = false;
81
+
82
+ async function model(request: ModelRequest): Promise<unknown> {
83
+ if (!context.model) throw new Error("Choose a pi model before learning.");
84
+ // Use pi's provider/auth runtime, including OAuth and custom model providers.
85
+ const response = await context.modelRegistry
86
+ .streamSimple(
87
+ context.model,
88
+ {
89
+ systemPrompt:
90
+ (request.kind === "judge"
91
+ ? request.instruction
92
+ : "Assess each criterion independently. Return its probability (0 to 1) that the learner demonstrated it, using the supplied evidence.") +
93
+ "\nCall reply with the structured judgment.",
94
+ messages: [
95
+ {
96
+ role: "user",
97
+ content: JSON.stringify(
98
+ request.kind === "judge" ? request.input : { input: request.input, criteria: request.criteria },
99
+ ),
100
+ timestamp: Date.now(),
101
+ },
102
+ ],
103
+ tools: [
104
+ {
105
+ name: "reply",
106
+ description: "Return the structured judgment.",
107
+ // Tool arguments are always objects; a Theory may ask for a scalar.
108
+ parameters: {
109
+ type: "object",
110
+ properties: { value: request.schema },
111
+ required: ["value"],
112
+ additionalProperties: false,
113
+ },
114
+ // Theory schemas use full JSON Schema (for example uniqueItems), not
115
+ // OpenAI's strict subset. The host validates the returned judgment.
116
+ constrainedSampling: false,
117
+ },
118
+ ],
119
+ },
120
+ { signal: context.signal },
121
+ )
122
+ .result();
123
+ if (response.stopReason === "error" || response.stopReason === "aborted")
124
+ throw new Error(response.errorMessage ?? "Judgment interrupted");
125
+ const reply = response.content.find((part) => part.type === "toolCall" && part.name === "reply");
126
+ if (!reply || reply.type !== "toolCall")
127
+ throw new Error("The selected model did not return a structured judgment.");
128
+ return reply.arguments.value;
129
+ }
130
+
131
+ function wasImportConfirmed(): boolean {
132
+ return importConfirmed;
133
+ }
134
+
135
+ async function getHost(ctx: ExtensionContext): Promise<Host> {
136
+ context = ctx;
137
+ if (!ctx.isProjectTrusted()) throw new Error("Trust the Profile project before learning.");
138
+ if (host) return host;
139
+ const manifest: unknown = JSON.parse(await readFile(join(ctx.cwd, "profile.json"), "utf8"));
140
+ if (!manifest || typeof manifest !== "object" || !("theories" in manifest) || !Array.isArray(manifest.theories))
141
+ throw new Error("Not an mmon Profile. Run npx @mmon-co/ncept-pi init <dir> first.");
142
+ const require = createRequire(join(ctx.cwd, "profile.json"));
143
+ const theories: Theory<unknown>[] = [];
144
+ for (const name of manifest.theories) {
145
+ if (typeof name !== "string") throw new Error("Invalid Theory package name");
146
+ const module = name === "@mmon-co/ncept-default-theory" ? { defaultTheory } : await import(require.resolve(name));
147
+ const theory: Theory<unknown> = module.defaultTheory ?? module.default ?? module.theory;
148
+ theories.push(theory);
149
+ }
150
+ host = await openHost({
151
+ profileDir: ctx.cwd,
152
+ hub: {
153
+ userAgent: "ncept-pi/" + version,
154
+ clientMetadataUrl: "https://pi.dev/oauth/client.json",
155
+ url: process.env.NCEPT_HUB_URL,
156
+ credentialsFile: process.env.NCEPT_CREDENTIALS_FILE,
157
+ },
158
+ theories,
159
+ model,
160
+ confirm: async (proposal) => {
161
+ const accepted = await context.ui.confirm(
162
+ proposal.title,
163
+ proposal.description + "\n\n" + JSON.stringify(proposal.detail, null, 2),
164
+ );
165
+ if (proposal.kind === "hub.import") importConfirmed = accepted;
166
+ return accepted;
167
+ },
168
+ });
169
+ return host;
170
+ }
171
+
172
+ async function session(ctx: ExtensionContext): Promise<HostSession> {
173
+ const h = await getHost(ctx);
174
+ if (active) return active;
175
+ let resume = storedSession(ctx);
176
+ if (!resume) {
177
+ const profile = await h.profile.read();
178
+ const filename = ctx.sessionManager.getSessionFile();
179
+ const surface = Object.entries(profile.manifest.sessions).find(
180
+ ([, file]) => file === basename(filename ?? ""),
181
+ )?.[0];
182
+ // Imported web Sessions have no extension entry; the host resolves their surface.
183
+ resume = surface;
184
+ }
185
+ active = await h.sessions.open({ mode: "empty", ...(resume ? { resume } : {}) });
186
+ pi.appendEntry(STATE, { id: active.id });
187
+ await sync(ctx);
188
+ return active;
189
+ }
190
+
191
+ async function sync(ctx: ExtensionContext) {
192
+ if (!host || !active) return;
193
+ const file = ctx.sessionManager.getSessionFile();
194
+ const header = ctx.sessionManager.getHeader();
195
+ if (!file || !header) throw new Error("Learning requires a persistent pi session.");
196
+ try {
197
+ await readFile(file);
198
+ } catch (error) {
199
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
200
+ throw error;
201
+ }
202
+ const entries = ctx.sessionManager.getEntries();
203
+ const leaf = ctx.sessionManager.getLeafEntry();
204
+ // The local host follows the last entry's branch, including after /tree.
205
+ const selected = leaf ? [...entries.filter((entry) => entry.id !== leaf.id), leaf] : entries;
206
+ const source = [header, ...selected].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
207
+ parsePiSession(source);
208
+ // Pi owns file creation. Refresh only a file it has persisted, preserving
209
+ // the selected /tree branch for the host without racing its exclusive create.
210
+ // A session pi keeps elsewhere (a --session-dir override, such as bb's pi
211
+ // bridge) is mirrored, since the Profile carries every transcript.
212
+ const sessions = join(ctx.cwd, "sessions");
213
+ await mkdir(sessions, { recursive: true });
214
+ await writeFile(relative(sessions, dirname(file)) === "" ? file : join(sessions, basename(file)), source);
215
+ await host.profile.registerSession(active.surface, basename(file), { trusted: ctx.isProjectTrusted() });
216
+ }
217
+
218
+ function permitted(name: string, description: string): boolean {
219
+ if (ownTools.has(name)) return !!mounted?.tools.some((tool) => tool.name === name);
220
+ if (
221
+ mounted?.capabilities.includes("bash") &&
222
+ ["bash", "powershell", "edit", "write", "grep", "find", "ls", "codemode"].includes(name)
223
+ )
224
+ return true;
225
+ return !!mounted?.capabilities.includes("web") && /web|search|browse|fetch/i.test(name + " " + description);
226
+ }
227
+
228
+ async function prepare(ctx: ExtensionContext, learnerMessage?: string): Promise<HostChatSetup> {
229
+ const current = await session(ctx);
230
+ const h = await getHost(ctx);
231
+ await sync(ctx);
232
+ const setup = await h.sessions.turn(current, { ...(learnerMessage ? { learnerMessage } : {}) });
233
+ mounted = {
234
+ ...setup,
235
+ tools: [
236
+ ...setup.tools,
237
+ {
238
+ name: "hub",
239
+ description:
240
+ "Pull a Hub release by address without an account. In authoring mode, publish the current personal Patch and its bases/Materials as a release after learner confirmation; /ncept login signs in first.",
241
+ schema: {
242
+ type: "object",
243
+ properties: {
244
+ op: { enum: ["pull", "publish"] },
245
+ address: { type: "string" },
246
+ version: { type: "string" },
247
+ title: { type: "string" },
248
+ description: { type: "string" },
249
+ },
250
+ required: ["op"],
251
+ additionalProperties: false,
252
+ },
253
+ run: async (raw) => {
254
+ if (!raw || typeof raw !== "object") throw new Error("Invalid Hub request");
255
+ const input = Object.fromEntries(Object.entries(raw));
256
+ if (input.op === "pull" && typeof input.address === "string")
257
+ return { content: await h.hub.pull(input.address) };
258
+ if (
259
+ input.op !== "publish" ||
260
+ current.mode !== "authoring" ||
261
+ typeof input.version !== "string" ||
262
+ typeof input.title !== "string"
263
+ )
264
+ throw new Error("Pull needs address; publish needs authoring mode, version and title.");
265
+ return {
266
+ content: await h.hub.publish({
267
+ patch: (await h.profile.read()).manifest.personal,
268
+ version: input.version,
269
+ title: input.title,
270
+ ...(typeof input.description === "string" ? { description: input.description } : {}),
271
+ }),
272
+ };
273
+ },
274
+ },
275
+ ],
276
+ };
277
+ for (const tool of mounted.tools) {
278
+ ownTools.add(tool.name);
279
+ pi.registerTool({
280
+ name: tool.name,
281
+ label: tool.name,
282
+ description: tool.description,
283
+ parameters: tool.schema,
284
+ async execute(_id, input, _signal, _onUpdate, toolCtx) {
285
+ context = toolCtx;
286
+ if (transition) throw new Error("A Session switch is pending.");
287
+ await sync(toolCtx);
288
+ if (!mounted) throw new Error("No active learning mode.");
289
+ const currentTool = mounted.tools.find((candidate) => candidate.name === tool.name);
290
+ if (!currentTool) throw new Error("Tool is not mounted in this mode.");
291
+ const result = await currentTool.run(input);
292
+ if (result.switch && result.switch.then === "here") {
293
+ active = {
294
+ ...current,
295
+ mode: result.switch.mode,
296
+ ...(result.switch.entry ? { entry: result.switch.entry } : {}),
297
+ };
298
+ await prepare(toolCtx);
299
+ } else if (result.switch) {
300
+ const to = result.switch;
301
+ const carry = await carryFor(toolCtx, to);
302
+ const continuation = await enter(toolCtx, to, "Continue.", carry, to.then === "aside");
303
+ return {
304
+ content: [{ type: "text", text: JSON.stringify({ status: "opened", continuation }) }],
305
+ details: result,
306
+ terminate: !!pendingEnter || !continuation,
307
+ };
308
+ }
309
+ return { content: [{ type: "text", text: JSON.stringify(result.content ?? null) }], details: result };
310
+ },
311
+ });
312
+ }
313
+ pi.setActiveTools(
314
+ pi
315
+ .getAllTools()
316
+ .filter((tool) => permitted(tool.name, tool.description))
317
+ .map(({ name }) => name),
318
+ );
319
+ return mounted;
320
+ }
321
+
322
+ function prompt(setup: HostChatSetup): string {
323
+ return (
324
+ setup.prompt +
325
+ "\n\n" +
326
+ setup.context +
327
+ "\n\nMounted Skills (read with skill):\n" +
328
+ setup.skills.map(({ name, description }) => "- " + name + ": " + description).join("\n")
329
+ );
330
+ }
331
+
332
+ async function dashboard(ctx: ExtensionContext) {
333
+ const reading = await (await getHost(ctx)).reading();
334
+ ctx.ui.setWidget(
335
+ "ncept",
336
+ [
337
+ "Me",
338
+ ...reading.missions
339
+ .filter(({ run }) => !run.retired)
340
+ .map(
341
+ ({ mission, next }) =>
342
+ mission.statement + " — " + (next[0]?.name ?? "chart the next stop") + " /learn " + mission.id,
343
+ ),
344
+ reading.missions.length ? "" : "No Missions yet. /learn <what I want to learn>",
345
+ reading.dueReview.length + " Nodes due for review. /review",
346
+ "/learn · /missions · /author · /hub pull <url>",
347
+ ].filter(Boolean),
348
+ );
349
+ }
350
+
351
+ async function enter(
352
+ ctx: ExtensionContext & Partial<Pick<ExtensionCommandContext, "newSession">>,
353
+ selection: Selection,
354
+ kickoff?: string,
355
+ carry?: string,
356
+ aside = false,
357
+ ) {
358
+ const h = await getHost(ctx);
359
+ const old = active;
360
+ const empty = !ctx.sessionManager.getBranch().some((entry) => entry.type === "message");
361
+ await sync(ctx);
362
+ // Skip admission needs the current stop; it closes the outgoing Mission Session itself.
363
+ if (old && !aside && !selection.skip) await h.sessions.close(old);
364
+ const opened = await h.sessions.open(selection);
365
+ if (empty) {
366
+ active = opened;
367
+ mounted = undefined;
368
+ pi.appendEntry(STATE, { id: opened.id });
369
+ if (carry) pi.sendMessage({ customType: "ncept.carry", content: carry, display: false });
370
+ if (kickoff) pi.sendUserMessage(kickoff);
371
+ return;
372
+ }
373
+ let claimed: (() => Promise<void | string>) | undefined;
374
+ const handoff: OpenSession = {
375
+ session: opened.id,
376
+ mode: opened.mode,
377
+ aside,
378
+ ...(kickoff
379
+ ? { kickoff, learnerKickoff: selection.entry?.kind === "goal" && selection.entry.text === kickoff }
380
+ : {}),
381
+ ...(carry ? { carry } : {}),
382
+ claim: (open) => {
383
+ claimed ??= open;
384
+ },
385
+ };
386
+ pi.events.emit(OPEN_SESSION, handoff);
387
+ if (claimed) {
388
+ try {
389
+ const continuation = await claimed();
390
+ // This pi session stays visible; its next message resumes the closed Session.
391
+ if (!aside) active = undefined;
392
+ if (continuation && ctx.newSession)
393
+ pi.sendMessage(
394
+ { customType: "ncept.continuation", content: continuation, display: false },
395
+ { triggerTurn: true },
396
+ );
397
+ return continuation;
398
+ } catch (error) {
399
+ await h.sessions.close(opened);
400
+ active = old ? await h.sessions.open({ mode: old.mode, resume: old.id }) : undefined;
401
+ throw error;
402
+ }
403
+ }
404
+ const finish = async (command: Pick<ExtensionCommandContext, "newSession">) => {
405
+ const parentSession = ctx.sessionManager.getSessionFile();
406
+ const result = await command.newSession({
407
+ ...(parentSession ? { parentSession } : {}),
408
+ setup: async (sm) => {
409
+ sm.appendCustomEntry(STATE, { id: opened.id });
410
+ if (carry) sm.appendCustomMessageEntry("ncept.carry", carry, false);
411
+ },
412
+ withSession: async (fresh) => {
413
+ if (kickoff) await fresh.sendUserMessage(kickoff);
414
+ },
415
+ });
416
+ if (result.cancelled) {
417
+ await h.sessions.close(opened);
418
+ active = old ? await h.sessions.open({ mode: old.mode, resume: old.id }) : undefined;
419
+ ctx.ui.notify("Session switch cancelled.", "info");
420
+ }
421
+ };
422
+ if (ctx.newSession) await finish({ newSession: ctx.newSession });
423
+ else pendingEnter = finish;
424
+ }
425
+
426
+ pi.events.on(BEGIN_SESSION, (data) => {
427
+ if (!isBeginSession(data)) return;
428
+ const request = data;
429
+ request.claim(async () => {
430
+ if (storedSession(context)) return session(context);
431
+ active = await (await getHost(context)).sessions.begin(request.intent);
432
+ mounted = undefined;
433
+ pi.appendEntry(STATE, { id: active.id });
434
+ await sync(context);
435
+ return active;
436
+ });
437
+ });
438
+ pi.events.on(ADOPT_SESSION, (data) => {
439
+ if (!data || typeof data !== "object" || !("session" in data) || typeof data.session !== "string") return;
440
+ pi.appendEntry(STATE, { id: data.session });
441
+ if ("carry" in data && typeof data.carry === "string" && data.carry)
442
+ pi.sendMessage({ customType: "ncept.carry", content: data.carry, display: false });
443
+ });
444
+ pi.on("session_start", async (_event, ctx) => {
445
+ await dashboard(ctx);
446
+ const path = join(ctx.cwd, ".pi/settings.json");
447
+ const settings = JSON.parse(await readFile(path, "utf8"));
448
+ if (settings.codemode?.mode === undefined) {
449
+ // Project settings keep native tools declared under an agent-directory "only" loadout.
450
+ // Existing Profiles pick this up on their next pi start.
451
+ settings.codemode = { ...settings.codemode, mode: "on" };
452
+ await writeFile(path, JSON.stringify(settings, null, 2) + "\n");
453
+ }
454
+ });
455
+ pi.on("before_agent_start", async (event, ctx) => {
456
+ ctx.ui.setWidget("ncept", undefined);
457
+ relayingContinuation = event.messageType === "custom" && event.message.customType === "ncept.continuation";
458
+ gradeReply = event.messageType === "user";
459
+ const setup = relayingContinuation ? undefined : await prepare(ctx);
460
+ if (relayingContinuation) pi.setActiveTools([]);
461
+ event.systemPromptOptions.contextFiles = [];
462
+ event.systemPromptOptions.skills = [];
463
+ event.systemPromptOptions.appendSystemPrompt = "";
464
+ promptOptions = event.systemPromptOptions;
465
+ event.systemPromptOptions.customPrompt = setup ? prompt(setup) : "Return the host's continuation to the learner.";
466
+ event.systemPromptOptions.sections = {};
467
+ });
468
+ pi.on("agent_start", () => {
469
+ // Global prompt renderers can run after before_agent_start; discard their
470
+ // forced projection once every renderer has seen the tutor-owned options.
471
+ if (promptOptions) promptOptions.forceSystemPrompt = undefined;
472
+ });
473
+ pi.on("context_with_system", async (event, ctx) => {
474
+ if (relayingContinuation)
475
+ return {
476
+ messages: [
477
+ {
478
+ role: "system",
479
+ content: "Return the host's continuation to the learner.",
480
+ toolsAdded: [],
481
+ timestamp: Date.now(),
482
+ },
483
+ ...event.messages.filter((message) => message.role !== "system"),
484
+ ],
485
+ };
486
+ // before_agent_start precedes persistence of the starting user message. Grade
487
+ // only once pi has assigned its real entry id, before the provider sees it.
488
+ const learner = ctx.sessionManager
489
+ .getBranch()
490
+ .findLast((entry) => entry.type === "message" && entry.message.role === "user");
491
+ if (gradeReply && learner && !graded.has(learner.id)) {
492
+ await prepare(ctx, learner.id);
493
+ graded.add(learner.id);
494
+ gradeReply = false;
495
+ }
496
+ if (!mounted) return;
497
+ const selected = new Set(pi.getActiveTools());
498
+ return {
499
+ messages: [
500
+ {
501
+ role: "system",
502
+ content: prompt(mounted),
503
+ toolsAdded: pi
504
+ .getAllTools()
505
+ .filter(({ name }) => selected.has(name))
506
+ .map(({ name, description, parameters }) => ({ name, description, parameters })),
507
+ timestamp: Date.now(),
508
+ },
509
+ ...event.messages.filter((message) => message.role !== "system"),
510
+ ],
511
+ };
512
+ });
513
+ pi.on("tool_call", (event) => {
514
+ const tool = pi.getAllTools().find(({ name }) => name === event.toolName);
515
+ if (!tool || !permitted(tool.name, tool.description))
516
+ return { block: true, reason: "This tool is not mounted in the current learning mode." };
517
+ });
518
+ pi.on("turn_end", async (_event, ctx) => {
519
+ await sync(ctx);
520
+ });
521
+ pi.on("session_shutdown", async (event, ctx) => {
522
+ if (!active || !host) return;
523
+ await sync(ctx);
524
+ if (event.reason === "quit") await host.sessions.close(active);
525
+ });
526
+ pi.on("agent_settled", async (_event, ctx) => {
527
+ await sync(ctx);
528
+ if (!pendingEnter && !transition && active && host) transition = await host.sessions.settle(active);
529
+ if (pendingEnter || transition) pi.sendUserMessage("/ncept-next", { expandPromptTemplates: true });
530
+ else if (active) ctx.ui.setStatus("ncept", active.mode);
531
+ });
532
+
533
+ async function carryFor(ctx: ExtensionContext, to: Exclude<ModeSwitch, { then: "here" }>): Promise<string> {
534
+ let carry: string;
535
+ if (to.carry.kind === "brief") {
536
+ const recent = ctx.sessionManager
537
+ .getBranch()
538
+ .flatMap((entry) => {
539
+ if (entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "assistant"))
540
+ return [];
541
+ const content = entry.message.content;
542
+ const text =
543
+ typeof content === "string"
544
+ ? content
545
+ : content
546
+ .filter((part) => part.type === "text")
547
+ .map((part) => part.text)
548
+ .join("\n");
549
+ return text ? [{ role: entry.message.role, text: text.slice(-2000) }] : [];
550
+ })
551
+ .slice(-6);
552
+ carry =
553
+ to.carry.text ??
554
+ "Previous Session (recent conversation):\n" +
555
+ JSON.stringify(recent) +
556
+ "\nNext entry:\n" +
557
+ JSON.stringify(to.entry ?? {});
558
+ } else {
559
+ const messages = ctx.sessionManager
560
+ .getBranch()
561
+ .flatMap((entry) =>
562
+ entry.type === "message" && ["user", "assistant"].includes(entry.message.role) ? [entry.message] : [],
563
+ );
564
+ if (to.carry.kind === "full") carry = JSON.stringify(messages);
565
+ else {
566
+ if (!ctx.model) throw new Error("Choose a pi model before carrying a Session.");
567
+ const response = await ctx.modelRegistry
568
+ .streamSimple(
569
+ ctx.model,
570
+ {
571
+ systemPrompt: "Summarize the learning conversation for the next tutor. Focus: " + to.carry.focus,
572
+ messages: [{ role: "user", content: JSON.stringify(messages), timestamp: Date.now() }],
573
+ },
574
+ { signal: ctx.signal },
575
+ )
576
+ .result();
577
+ if (response.stopReason === "error" || response.stopReason === "aborted")
578
+ throw new Error(response.errorMessage ?? "Carry interrupted");
579
+ carry = response.content
580
+ .filter((part) => part.type === "text")
581
+ .map((part) => part.text)
582
+ .join("\n");
583
+ }
584
+ }
585
+ return carry;
586
+ }
587
+ pi.registerCommand("ncept-next", {
588
+ description: "Continue a tutor-requested Session switch",
589
+ handler: async (_args, ctx) => {
590
+ if (pendingEnter) {
591
+ const finish = pendingEnter;
592
+ pendingEnter = undefined;
593
+ await finish(ctx);
594
+ return;
595
+ }
596
+ if (!transition || transition.then === "here") return;
597
+ const to = transition;
598
+ transition = undefined;
599
+ await enter(ctx, to, "Continue.", await carryFor(ctx, to), to.then === "aside");
600
+ },
601
+ });
602
+ pi.registerCommand("learn", {
603
+ description: "Learn a goal, or choose a Mission and its next stop",
604
+ handler: async (args, ctx) => {
605
+ const missions = await (await getHost(ctx)).missions.list();
606
+ let mission = missions.find(({ mission }) => mission.id === args.trim());
607
+ if (!args.trim()) {
608
+ const choices = missions.filter(({ run }) => !run.retired);
609
+ const options = choices.map(
610
+ ({ mission, next }) => mission.statement + " — " + (next[0]?.name ?? "chart the next stop"),
611
+ );
612
+ const selected = await ctx.ui.select("Learn", [...options, "New goal…"]);
613
+ if (!selected) return;
614
+ if (selected === "New goal…") {
615
+ const goal = await ctx.ui.input("What do you want to learn?");
616
+ if (goal?.trim()) await enter(ctx, { mode: "charting", entry: { kind: "goal", text: goal } }, goal);
617
+ return;
618
+ }
619
+ mission = choices[options.indexOf(selected)];
620
+ }
621
+ if (mission)
622
+ await enter(
623
+ ctx,
624
+ { mode: "charting", entry: { kind: "mission", id: mission.mission.id } },
625
+ "Let's continue this Mission.",
626
+ );
627
+ else await enter(ctx, { mode: "charting", entry: { kind: "goal", text: args.trim() } }, args.trim());
628
+ },
629
+ });
630
+ pi.registerCommand("skip", {
631
+ description: "Skip this Lesson or go to a later planned stop",
632
+ handler: async (_args, ctx) => {
633
+ const h = await getHost(ctx);
634
+ const current = await session(ctx);
635
+ if (current.mode !== "lesson" || current.entry?.kind !== "lesson") {
636
+ ctx.ui.notify("Open a Mission Lesson to skip.", "info");
637
+ return;
638
+ }
639
+ const lesson = current.entry.lesson;
640
+ const missionId = lesson.mission.id;
641
+ const reading = (await h.missions.list()).find(({ mission }) => mission.id === missionId);
642
+ const index =
643
+ reading?.next.findIndex(
644
+ (stop) =>
645
+ stop.kind === "lesson" &&
646
+ stop.nodes.length === lesson.nodes.length &&
647
+ stop.nodes.every((node) => lesson.nodes.includes(node)),
648
+ ) ?? -1;
649
+ const later = reading?.next.slice(index >= 0 ? index + 1 : 0) ?? [];
650
+ const options = later.map((stop) => stop.kind + " " + stop.number + " — " + (stop.name ?? stop.nodes.join(", ")));
651
+ const selected = await ctx.ui.select("Skip… Lessons in between are marked probably known.", [
652
+ "Just this lesson",
653
+ ...options,
654
+ ]);
655
+ if (!selected) return;
656
+ const stop = later[options.indexOf(selected)];
657
+ const skip =
658
+ selected === "Just this lesson"
659
+ ? { mission: missionId, kind: "skip-lesson" as const }
660
+ : stop
661
+ ? { mission: missionId, kind: "skip-to" as const, stop }
662
+ : undefined;
663
+ if (!skip) return;
664
+ await enter(ctx, { mode: "lesson", skip }, "Let's continue this Mission.");
665
+ },
666
+ });
667
+ pi.registerCommand("review", {
668
+ description: "Review what is due",
669
+ handler: async (_args, ctx) => {
670
+ const { dueReview } = await (await getHost(ctx)).reading();
671
+ if (!dueReview.length) {
672
+ ctx.ui.notify("No review due.", "info");
673
+ return;
674
+ }
675
+ await enter(ctx, { mode: "lesson", entry: { kind: "review", nodes: dueReview } }, "Let's review.");
676
+ },
677
+ });
678
+ pi.registerCommand("author", {
679
+ description: "Author a learning map and Materials",
680
+ handler: async (args, ctx) => {
681
+ await enter(
682
+ ctx,
683
+ { mode: "authoring", ...(args.trim() ? { entry: { kind: "goal", text: args.trim() } as const } : {}) },
684
+ args.trim() || "Let's author a learning map.",
685
+ );
686
+ },
687
+ });
688
+ pi.registerCommand("missions", {
689
+ description: "Show Missions and next stops",
690
+ handler: async (_args, ctx) => {
691
+ await dashboard(ctx);
692
+ },
693
+ });
694
+ pi.registerCommand("hub", {
695
+ description: "Pull a Hub release: /hub pull <url or patch@version>",
696
+ handler: async (args, ctx) => {
697
+ const match = /^pull\s+(.+)$/.exec(args.trim());
698
+ if (!match?.[1]) {
699
+ ctx.ui.notify("Usage: /hub pull <url or patch@version>", "info");
700
+ return;
701
+ }
702
+ const ref = await (await getHost(ctx)).hub.pull(match[1]);
703
+ ctx.ui.notify("Adopted " + ref.identity + "@" + ref.digest, "info");
704
+ await dashboard(ctx);
705
+ },
706
+ });
707
+ pi.registerCommand("ncept", {
708
+ description: "ncept login | logout | export-to-web | import-from-web",
709
+ handler: async (args, ctx) => {
710
+ const h = await getHost(ctx);
711
+ await sync(ctx);
712
+ switch (args.trim()) {
713
+ case "login":
714
+ await h.hub.signIn();
715
+ ctx.ui.notify("Signed in to Common Concept.", "info");
716
+ break;
717
+ case "logout":
718
+ await rm(process.env.NCEPT_CREDENTIALS_FILE ?? credentialsPath(), { force: true });
719
+ host = undefined;
720
+ ctx.ui.notify("Signed out of Common Concept.", "info");
721
+ break;
722
+ case "export-to-web":
723
+ await h.hub.exportTo("web");
724
+ break;
725
+ case "import-from-web": {
726
+ // Exchange archives deliberately contain Profile data, not pi project configuration.
727
+ const settings = await readFile(join(ctx.cwd, ".pi/settings.json"));
728
+ const system = await readFile(join(ctx.cwd, ".pi/SYSTEM.md"));
729
+ importConfirmed = false;
730
+ const imported = await h.hub.importFrom("web");
731
+ if (!wasImportConfirmed()) {
732
+ ctx.ui.notify("Import cancelled.", "info");
733
+ return;
734
+ }
735
+ await mkdir(join(ctx.cwd, ".pi"), { recursive: true });
736
+ await writeFile(join(ctx.cwd, ".pi/settings.json"), settings);
737
+ await writeFile(join(ctx.cwd, ".pi/SYSTEM.md"), system);
738
+ host = undefined;
739
+ active = undefined;
740
+ ctx.ui.notify("Imported " + imported.sessions.length + " Sessions. Use /resume to continue one.", "info");
741
+ await ctx.newSession();
742
+ break;
743
+ }
744
+ default:
745
+ ctx.ui.notify("Usage: /ncept login | logout | export-to-web | import-from-web", "info");
746
+ }
747
+ },
748
+ });
749
+ }