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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mmon-co
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @mmon-co/ncept-pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official pi learning front end over the MIT-licensed [local Profile host](../local/README.md). Your Profile is an ordinary directory; pi's accounts, models, theme, keybindings and global extensions stay yours. Coding projects do not load this package.
4
+
5
+ ## Start learning
6
+
7
+ Install [pi](https://pi.dev), then:
8
+
9
+ ```sh
10
+ npx @mmon-co/ncept-pi init ~/learn
11
+ cd ~/learn
12
+ pi
13
+ ```
14
+
15
+ Accept pi's one-time project trust prompt. The dashboard above the editor shows Missions, next stops and due review, and clears when you speak. A fresh conversation is a chat Session.
16
+
17
+ - `/learn <goal>` charts what you want to learn. `/learn` offers Missions and their next stops; `/learn <mission-id>` opens a particular Mission.
18
+ - `/review` opens the due review batch; `/author [goal]` opens an authoring Session.
19
+ - `/missions` shows the dashboard again.
20
+ - `/hub pull <release-url or patch@version>` adopts a release without an account. You can also paste an address and ask the tutor to pull it.
21
+ - `/ncept login` signs in once through the browser; `/ncept logout` removes the saved Common Concept credential. These are separate from pi's model accounts.
22
+ - In authoring, ask the tutor to publish: its `hub` tool packages the current personal Patch, bases and Materials and confirms public publication. Publishing needs a free Common Concept account, not a subscription.
23
+ - `/ncept export-to-web` replaces web Main with this Profile after confirmation (and, if needed, choosing the Missions that fit the web allowance).
24
+ - `/ncept import-from-web` replaces this Profile after confirmation, preserving the old project in the host's backup directory. pi project settings are restored; `/resume` can continue imported Sessions.
25
+
26
+ Every conversation is pi's own JSONL under `sessions/`. `/resume` continues one, `/tree` selects its branch, and `/new` starts a fresh chat. Host mode switches open next or aside pi Sessions with the Theory's declared carry. Observations, Mission progress, saved Materials and trusted Session associations live in the Profile and travel with its exchange archive. Keep `sessionDir: "sessions"`; do not override it with pi's CLI or environment.
27
+
28
+ The mode's native tools, context and Skills replace pi's coding prompt every turn. Global `AGENTS.md` and coding Skills are excluded. Existing web/search tools remain available in modes mounting `web`, and shell/file-writing tools in modes mounting `bash`. Tool selection is a tutor capability boundary, not an operating-system sandbox: pi and its extensions still have your OS permissions.
29
+
30
+ Models and grading use the model currently selected in pi, through pi's provider/auth runtime. The selected model must support tool calls and structured judgments. No Common Concept account, token limit, hosted deployment or subscription is needed for local learning.
31
+
32
+ ## Development first use
33
+
34
+ From a repository checkout:
35
+
36
+ ```sh
37
+ bun install
38
+ bun run --cwd packages/pi build
39
+ bun packages/pi/scripts/first-use.ts /tmp/my-ncept-profile
40
+ cd /tmp/my-ncept-profile && pi
41
+ ```
42
+
43
+ The setup script requires an unused directory and points the project package at this checkout instead of the unpublished npm package. It creates an empty Profile, no account or seed; pi uses your existing model authentication. It does not change your global pi settings or deploy a service.
44
+
45
+ ```sh
46
+ bun test packages/pi/test/pi-wiring.test.ts
47
+ ```
48
+
49
+ The SDK wiring smoke uses a scripted model with real host tools and pi Session files; it makes no paid or network requests.
50
+
51
+ For a checkout-owned hosted endpoint, set `NCEPT_HUB_URL` to its Application base URL (including `/ncept`) before starting pi. `NCEPT_CREDENTIALS_FILE` selects an isolated credential file outside the Profile; login and logout use the same file. Omit both for the public product. OAuth uses pi's public CIMD identity, PKCE and the `patches publish learn` scopes; it does not require the issuer to enable dynamic registration.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import { initProject } from "./init.js";
3
+ const [command, directory, ...extra] = process.argv.slice(2);
4
+ if (command !== "init" || !directory || extra.length) {
5
+ console.error("Usage: npx @mmon-co/ncept-pi init <dir>");
6
+ process.exitCode = 1;
7
+ }
8
+ else {
9
+ try {
10
+ const dir = await initProject(directory);
11
+ console.log("Profile ready: " +
12
+ dir +
13
+ "\nRun: cd " +
14
+ JSON.stringify(dir) +
15
+ " && pi\nTrust this learning project when pi asks.");
16
+ }
17
+ catch (error) {
18
+ console.error(error instanceof Error ? error.message : String(error));
19
+ process.exitCode = 1;
20
+ }
21
+ }
@@ -0,0 +1,3 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ /** One extension instance belongs to one pi session, including after /resume. */
3
+ export default function ncept(pi: ExtensionAPI): void;
@@ -0,0 +1,530 @@
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 { defaultTheory } from "@mmon-co/ncept-default-theory";
5
+ import { credentialsPath, openHost, parsePiSession, } from "@mmon-co/ncept-local";
6
+ const { version } = createRequire(import.meta.url)("../package.json");
7
+ const STATE = "ncept.session";
8
+ function storedSession(ctx) {
9
+ const saved = ctx.sessionManager
10
+ .getBranch()
11
+ .findLast((entry) => entry.type === "custom" && entry.customType === STATE);
12
+ if (saved?.type !== "custom" || !saved.data || typeof saved.data !== "object")
13
+ return undefined;
14
+ return "id" in saved.data && typeof saved.data.id === "string" ? saved.data.id : undefined;
15
+ }
16
+ /** One extension instance belongs to one pi session, including after /resume. */
17
+ export default function ncept(pi) {
18
+ let host;
19
+ let active;
20
+ let context;
21
+ let mounted;
22
+ let transition;
23
+ const ownTools = new Set();
24
+ const graded = new Set();
25
+ let gradeReply = false;
26
+ let importConfirmed = false;
27
+ async function model(request) {
28
+ if (!context.model)
29
+ throw new Error("Choose a pi model before learning.");
30
+ // Use pi's provider/auth runtime, including OAuth and custom model providers.
31
+ const response = await context.modelRegistry
32
+ .streamSimple(context.model, {
33
+ systemPrompt: (request.kind === "judge"
34
+ ? request.instruction
35
+ : "Assess each criterion independently. Return its probability (0 to 1) that the learner demonstrated it, using the supplied evidence.") +
36
+ "\nCall reply with the structured judgment.",
37
+ messages: [
38
+ {
39
+ role: "user",
40
+ content: JSON.stringify(request.kind === "judge" ? request.input : { input: request.input, criteria: request.criteria }),
41
+ timestamp: Date.now(),
42
+ },
43
+ ],
44
+ tools: [
45
+ {
46
+ name: "reply",
47
+ description: "Return the structured judgment.",
48
+ // Tool arguments are always objects; a Theory may ask for a scalar.
49
+ parameters: {
50
+ type: "object",
51
+ properties: { value: request.schema },
52
+ required: ["value"],
53
+ additionalProperties: false,
54
+ },
55
+ // Theory schemas use full JSON Schema (for example uniqueItems), not
56
+ // OpenAI's strict subset. The host validates the returned judgment.
57
+ constrainedSampling: false,
58
+ },
59
+ ],
60
+ }, { signal: context.signal })
61
+ .result();
62
+ if (response.stopReason === "error" || response.stopReason === "aborted")
63
+ throw new Error(response.errorMessage ?? "Judgment interrupted");
64
+ const reply = response.content.find((part) => part.type === "toolCall" && part.name === "reply");
65
+ if (!reply || reply.type !== "toolCall")
66
+ throw new Error("The selected model did not return a structured judgment.");
67
+ return reply.arguments.value;
68
+ }
69
+ function wasImportConfirmed() {
70
+ return importConfirmed;
71
+ }
72
+ async function getHost(ctx) {
73
+ context = ctx;
74
+ if (!ctx.isProjectTrusted())
75
+ throw new Error("Trust the Profile project before learning.");
76
+ if (host)
77
+ return host;
78
+ const manifest = JSON.parse(await readFile(join(ctx.cwd, "profile.json"), "utf8"));
79
+ if (!manifest || typeof manifest !== "object" || !("theories" in manifest) || !Array.isArray(manifest.theories))
80
+ throw new Error("Not an mmon Profile. Run npx @mmon-co/ncept-pi init <dir> first.");
81
+ const require = createRequire(join(ctx.cwd, "profile.json"));
82
+ const theories = [];
83
+ for (const name of manifest.theories) {
84
+ if (typeof name !== "string")
85
+ throw new Error("Invalid Theory package name");
86
+ const module = name === "@mmon-co/ncept-default-theory" ? { defaultTheory } : await import(require.resolve(name));
87
+ const theory = module.defaultTheory ?? module.default ?? module.theory;
88
+ theories.push(theory);
89
+ }
90
+ host = await openHost({
91
+ profileDir: ctx.cwd,
92
+ hub: {
93
+ userAgent: "ncept-pi/" + version,
94
+ clientMetadataUrl: "https://pi.dev/oauth/client.json",
95
+ url: process.env.NCEPT_HUB_URL,
96
+ credentialsFile: process.env.NCEPT_CREDENTIALS_FILE,
97
+ },
98
+ theories,
99
+ model,
100
+ confirm: async (proposal) => {
101
+ const accepted = await context.ui.confirm(proposal.title, proposal.description + "\n\n" + JSON.stringify(proposal.detail, null, 2));
102
+ if (proposal.kind === "hub.import")
103
+ importConfirmed = accepted;
104
+ return accepted;
105
+ },
106
+ });
107
+ return host;
108
+ }
109
+ async function session(ctx) {
110
+ const h = await getHost(ctx);
111
+ if (active)
112
+ return active;
113
+ let resume = storedSession(ctx);
114
+ if (!resume) {
115
+ const profile = await h.profile.read();
116
+ const filename = ctx.sessionManager.getSessionFile();
117
+ const surface = Object.entries(profile.manifest.sessions).find(([, file]) => file === basename(filename ?? ""))?.[0];
118
+ // Imported web Sessions have no extension entry; the host resolves their surface.
119
+ resume = surface;
120
+ }
121
+ active = await h.sessions.open({ mode: "empty", ...(resume ? { resume } : {}) });
122
+ pi.appendEntry(STATE, { id: active.id });
123
+ await sync(ctx);
124
+ return active;
125
+ }
126
+ async function sync(ctx) {
127
+ if (!host || !active)
128
+ return;
129
+ const file = ctx.sessionManager.getSessionFile();
130
+ const header = ctx.sessionManager.getHeader();
131
+ if (!file || !header)
132
+ throw new Error("Learning requires a persistent pi session.");
133
+ try {
134
+ await readFile(file);
135
+ }
136
+ catch (error) {
137
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
138
+ return;
139
+ throw error;
140
+ }
141
+ if (relative(join(ctx.cwd, "sessions"), dirname(file)) !== "")
142
+ throw new Error("pi sessions must be stored in this Profile's sessions directory. Remove --session-dir or PI_CODING_AGENT_SESSION_DIR overrides.");
143
+ const entries = ctx.sessionManager.getEntries();
144
+ const leaf = ctx.sessionManager.getLeafEntry();
145
+ // The local host follows the last entry's branch, including after /tree.
146
+ const selected = leaf ? [...entries.filter((entry) => entry.id !== leaf.id), leaf] : entries;
147
+ const source = [header, ...selected].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
148
+ parsePiSession(source);
149
+ await mkdir(dirname(file), { recursive: true });
150
+ // Pi owns file creation. Refresh only a file it has persisted, preserving
151
+ // the selected /tree branch for the host without racing its exclusive create.
152
+ await writeFile(file, source);
153
+ await host.profile.registerSession(active.surface, basename(file), { trusted: ctx.isProjectTrusted() });
154
+ }
155
+ function permitted(name, description) {
156
+ if (ownTools.has(name))
157
+ return !!mounted?.tools.some((tool) => tool.name === name);
158
+ if (mounted?.capabilities.includes("bash") &&
159
+ ["bash", "powershell", "edit", "write", "grep", "find", "ls"].includes(name))
160
+ return true;
161
+ return !!mounted?.capabilities.includes("web") && /web|search|browse|fetch/i.test(name + " " + description);
162
+ }
163
+ async function prepare(ctx, learnerMessage) {
164
+ const current = await session(ctx);
165
+ const h = await getHost(ctx);
166
+ await sync(ctx);
167
+ const setup = await h.sessions.turn(current, { ...(learnerMessage ? { learnerMessage } : {}) });
168
+ mounted = {
169
+ ...setup,
170
+ tools: [
171
+ ...setup.tools,
172
+ {
173
+ name: "hub",
174
+ description: "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.",
175
+ schema: {
176
+ type: "object",
177
+ properties: {
178
+ op: { enum: ["pull", "publish"] },
179
+ address: { type: "string" },
180
+ version: { type: "string" },
181
+ title: { type: "string" },
182
+ description: { type: "string" },
183
+ },
184
+ required: ["op"],
185
+ additionalProperties: false,
186
+ },
187
+ run: async (raw) => {
188
+ if (!raw || typeof raw !== "object")
189
+ throw new Error("Invalid Hub request");
190
+ const input = Object.fromEntries(Object.entries(raw));
191
+ if (input.op === "pull" && typeof input.address === "string")
192
+ return { content: await h.hub.pull(input.address) };
193
+ if (input.op !== "publish" ||
194
+ current.mode !== "authoring" ||
195
+ typeof input.version !== "string" ||
196
+ typeof input.title !== "string")
197
+ throw new Error("Pull needs address; publish needs authoring mode, version and title.");
198
+ return {
199
+ content: await h.hub.publish({
200
+ patch: (await h.profile.read()).manifest.personal,
201
+ version: input.version,
202
+ title: input.title,
203
+ ...(typeof input.description === "string" ? { description: input.description } : {}),
204
+ }),
205
+ };
206
+ },
207
+ },
208
+ ],
209
+ };
210
+ for (const tool of mounted.tools) {
211
+ ownTools.add(tool.name);
212
+ pi.registerTool({
213
+ name: tool.name,
214
+ label: tool.name,
215
+ description: tool.description,
216
+ parameters: tool.schema,
217
+ async execute(_id, input, _signal, _onUpdate, toolCtx) {
218
+ context = toolCtx;
219
+ if (transition)
220
+ throw new Error("A Session switch is pending.");
221
+ await sync(toolCtx);
222
+ if (!mounted)
223
+ throw new Error("No active learning mode.");
224
+ const currentTool = mounted.tools.find((candidate) => candidate.name === tool.name);
225
+ if (!currentTool)
226
+ throw new Error("Tool is not mounted in this mode.");
227
+ const result = await currentTool.run(input);
228
+ if (result.switch && result.switch.then === "here") {
229
+ active = {
230
+ ...current,
231
+ mode: result.switch.mode,
232
+ ...(result.switch.entry ? { entry: result.switch.entry } : {}),
233
+ };
234
+ await prepare(toolCtx);
235
+ }
236
+ else if (result.switch) {
237
+ transition = result.switch;
238
+ toolCtx.abort();
239
+ }
240
+ return { content: [{ type: "text", text: JSON.stringify(result.content ?? null) }], details: result };
241
+ },
242
+ });
243
+ }
244
+ pi.setActiveTools(pi
245
+ .getAllTools()
246
+ .filter((tool) => permitted(tool.name, tool.description))
247
+ .map(({ name }) => name));
248
+ return mounted;
249
+ }
250
+ function prompt(setup) {
251
+ return (setup.prompt +
252
+ "\n\n" +
253
+ setup.context +
254
+ "\n\nMounted Skills (read with skill):\n" +
255
+ setup.skills.map(({ name, description }) => "- " + name + ": " + description).join("\n"));
256
+ }
257
+ async function dashboard(ctx) {
258
+ const reading = await (await getHost(ctx)).reading();
259
+ ctx.ui.setWidget("ncept", [
260
+ "Me",
261
+ ...reading.missions
262
+ .filter(({ run }) => !run.retired)
263
+ .map(({ mission, next }) => mission.statement + " — " + (next[0]?.name ?? "chart the next stop") + " /learn " + mission.id),
264
+ reading.missions.length ? "" : "No Missions yet. /learn <what I want to learn>",
265
+ reading.dueReview.length + " Nodes due for review. /review",
266
+ "/learn · /missions · /author · /hub pull <url>",
267
+ ].filter(Boolean));
268
+ }
269
+ async function enter(ctx, selection, kickoff, carry, aside = false) {
270
+ const h = await getHost(ctx);
271
+ const old = active;
272
+ const empty = !ctx.sessionManager.getBranch().some((entry) => entry.type === "message");
273
+ await sync(ctx);
274
+ // Closing records the old conversation; /resume reopens it.
275
+ if (old && !aside)
276
+ await h.sessions.close(old);
277
+ const opened = await h.sessions.open(selection);
278
+ if (empty) {
279
+ active = opened;
280
+ mounted = undefined;
281
+ pi.appendEntry(STATE, { id: opened.id });
282
+ if (carry)
283
+ pi.sendMessage({ customType: "ncept.carry", content: carry, display: false });
284
+ if (kickoff)
285
+ pi.sendUserMessage(kickoff);
286
+ return;
287
+ }
288
+ const parentSession = ctx.sessionManager.getSessionFile();
289
+ const result = await ctx.newSession({
290
+ ...(parentSession ? { parentSession } : {}),
291
+ setup: async (sm) => {
292
+ sm.appendCustomEntry(STATE, { id: opened.id });
293
+ if (carry)
294
+ sm.appendCustomMessageEntry("ncept.carry", carry, false);
295
+ },
296
+ withSession: async (fresh) => {
297
+ if (kickoff)
298
+ await fresh.sendUserMessage(kickoff);
299
+ },
300
+ });
301
+ if (result.cancelled) {
302
+ await h.sessions.close(opened);
303
+ active = old ? await h.sessions.open({ mode: old.mode, resume: old.id }) : undefined;
304
+ ctx.ui.notify("Session switch cancelled.", "info");
305
+ }
306
+ }
307
+ pi.on("session_start", async (_event, ctx) => {
308
+ await dashboard(ctx);
309
+ });
310
+ pi.on("before_agent_start", async (event, ctx) => {
311
+ ctx.ui.setWidget("ncept", undefined);
312
+ gradeReply = event.messageType === "user";
313
+ const setup = await prepare(ctx);
314
+ event.systemPromptOptions.contextFiles = [];
315
+ event.systemPromptOptions.skills = [];
316
+ event.systemPromptOptions.appendSystemPrompt = "";
317
+ event.systemPromptOptions.customPrompt = prompt(setup);
318
+ event.systemPromptOptions.sections = {};
319
+ });
320
+ pi.on("context_with_system", async (event, ctx) => {
321
+ // before_agent_start precedes persistence of the starting user message. Grade
322
+ // only once pi has assigned its real entry id, before the provider sees it.
323
+ const learner = ctx.sessionManager
324
+ .getBranch()
325
+ .findLast((entry) => entry.type === "message" && entry.message.role === "user");
326
+ if (gradeReply && learner && !graded.has(learner.id)) {
327
+ await prepare(ctx, learner.id);
328
+ graded.add(learner.id);
329
+ gradeReply = false;
330
+ }
331
+ if (!mounted)
332
+ return;
333
+ const selected = new Set(pi.getActiveTools());
334
+ return {
335
+ messages: [
336
+ {
337
+ role: "system",
338
+ content: prompt(mounted),
339
+ toolsAdded: pi
340
+ .getAllTools()
341
+ .filter(({ name }) => selected.has(name))
342
+ .map(({ name, description, parameters }) => ({ name, description, parameters })),
343
+ timestamp: Date.now(),
344
+ },
345
+ ...event.messages.filter((message) => message.role !== "system"),
346
+ ],
347
+ };
348
+ });
349
+ pi.on("tool_call", (event) => {
350
+ const tool = pi.getAllTools().find(({ name }) => name === event.toolName);
351
+ if (!tool || !permitted(tool.name, tool.description))
352
+ return { block: true, reason: "This tool is not mounted in the current learning mode." };
353
+ });
354
+ pi.on("turn_end", async (_event, ctx) => {
355
+ await sync(ctx);
356
+ });
357
+ pi.on("session_shutdown", async (event, ctx) => {
358
+ if (!active || !host)
359
+ return;
360
+ await sync(ctx);
361
+ if (event.reason === "quit")
362
+ await host.sessions.close(active);
363
+ });
364
+ pi.on("agent_settled", (_event, ctx) => {
365
+ if (transition)
366
+ pi.sendUserMessage("/ncept-next", { expandPromptTemplates: true });
367
+ else if (active)
368
+ ctx.ui.setStatus("ncept", active.mode);
369
+ });
370
+ pi.registerCommand("ncept-next", {
371
+ description: "Continue a tutor-requested Session switch",
372
+ handler: async (_args, ctx) => {
373
+ if (!transition)
374
+ return;
375
+ const to = transition;
376
+ transition = undefined;
377
+ let carry;
378
+ if (to.then === "here")
379
+ return;
380
+ if (to.carry.kind === "brief") {
381
+ const recent = ctx.sessionManager
382
+ .getBranch()
383
+ .flatMap((entry) => {
384
+ if (entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "assistant"))
385
+ return [];
386
+ const content = entry.message.content;
387
+ const text = typeof content === "string"
388
+ ? content
389
+ : content
390
+ .filter((part) => part.type === "text")
391
+ .map((part) => part.text)
392
+ .join("\n");
393
+ return text ? [{ role: entry.message.role, text: text.slice(-2000) }] : [];
394
+ })
395
+ .slice(-6);
396
+ carry =
397
+ to.carry.text ??
398
+ "Previous Session (recent conversation):\n" +
399
+ JSON.stringify(recent) +
400
+ "\nNext entry:\n" +
401
+ JSON.stringify(to.entry ?? {});
402
+ }
403
+ else {
404
+ const messages = ctx.sessionManager
405
+ .getBranch()
406
+ .flatMap((entry) => entry.type === "message" && ["user", "assistant"].includes(entry.message.role) ? [entry.message] : []);
407
+ if (to.carry.kind === "full")
408
+ carry = JSON.stringify(messages);
409
+ else {
410
+ if (!ctx.model)
411
+ throw new Error("Choose a pi model before carrying a Session.");
412
+ const response = await ctx.modelRegistry
413
+ .streamSimple(ctx.model, {
414
+ systemPrompt: "Summarize the learning conversation for the next tutor. Focus: " + to.carry.focus,
415
+ messages: [{ role: "user", content: JSON.stringify(messages), timestamp: Date.now() }],
416
+ }, { signal: ctx.signal })
417
+ .result();
418
+ if (response.stopReason === "error" || response.stopReason === "aborted")
419
+ throw new Error(response.errorMessage ?? "Carry interrupted");
420
+ carry = response.content
421
+ .filter((part) => part.type === "text")
422
+ .map((part) => part.text)
423
+ .join("\n");
424
+ }
425
+ }
426
+ await enter(ctx, to, "Continue.", carry, to.then === "aside");
427
+ },
428
+ });
429
+ pi.registerCommand("learn", {
430
+ description: "Learn a goal, or choose a Mission and its next stop",
431
+ handler: async (args, ctx) => {
432
+ const missions = await (await getHost(ctx)).missions.list();
433
+ let mission = missions.find(({ mission }) => mission.id === args.trim());
434
+ if (!args.trim()) {
435
+ const choices = missions.filter(({ run }) => !run.retired);
436
+ const options = choices.map(({ mission, next }) => mission.statement + " — " + (next[0]?.name ?? "chart the next stop"));
437
+ const selected = await ctx.ui.select("Learn", [...options, "New goal…"]);
438
+ if (!selected)
439
+ return;
440
+ if (selected === "New goal…") {
441
+ const goal = await ctx.ui.input("What do you want to learn?");
442
+ if (goal?.trim())
443
+ await enter(ctx, { mode: "charting", entry: { kind: "goal", text: goal } }, goal);
444
+ return;
445
+ }
446
+ mission = choices[options.indexOf(selected)];
447
+ }
448
+ if (mission)
449
+ await enter(ctx, { mode: "charting", entry: { kind: "mission", id: mission.mission.id } }, "Let's continue this Mission.");
450
+ else
451
+ await enter(ctx, { mode: "charting", entry: { kind: "goal", text: args.trim() } }, args.trim());
452
+ },
453
+ });
454
+ pi.registerCommand("review", {
455
+ description: "Review what is due",
456
+ handler: async (_args, ctx) => {
457
+ const { dueReview } = await (await getHost(ctx)).reading();
458
+ if (!dueReview.length) {
459
+ ctx.ui.notify("No review due.", "info");
460
+ return;
461
+ }
462
+ await enter(ctx, { mode: "lesson", entry: { kind: "review", nodes: dueReview } }, "Let's review.");
463
+ },
464
+ });
465
+ pi.registerCommand("author", {
466
+ description: "Author a learning map and Materials",
467
+ handler: async (args, ctx) => enter(ctx, { mode: "authoring", ...(args.trim() ? { entry: { kind: "goal", text: args.trim() } } : {}) }, args.trim() || "Let's author a learning map."),
468
+ });
469
+ pi.registerCommand("missions", {
470
+ description: "Show Missions and next stops",
471
+ handler: async (_args, ctx) => {
472
+ await dashboard(ctx);
473
+ },
474
+ });
475
+ pi.registerCommand("hub", {
476
+ description: "Pull a Hub release: /hub pull <url or patch@version>",
477
+ handler: async (args, ctx) => {
478
+ const match = /^pull\s+(.+)$/.exec(args.trim());
479
+ if (!match?.[1]) {
480
+ ctx.ui.notify("Usage: /hub pull <url or patch@version>", "info");
481
+ return;
482
+ }
483
+ const ref = await (await getHost(ctx)).hub.pull(match[1]);
484
+ ctx.ui.notify("Adopted " + ref.identity + "@" + ref.digest, "info");
485
+ await dashboard(ctx);
486
+ },
487
+ });
488
+ pi.registerCommand("ncept", {
489
+ description: "ncept login | logout | export-to-web | import-from-web",
490
+ handler: async (args, ctx) => {
491
+ const h = await getHost(ctx);
492
+ await sync(ctx);
493
+ switch (args.trim()) {
494
+ case "login":
495
+ await h.hub.signIn();
496
+ ctx.ui.notify("Signed in to Common Concept.", "info");
497
+ break;
498
+ case "logout":
499
+ await rm(process.env.NCEPT_CREDENTIALS_FILE ?? credentialsPath(), { force: true });
500
+ host = undefined;
501
+ ctx.ui.notify("Signed out of Common Concept.", "info");
502
+ break;
503
+ case "export-to-web":
504
+ await h.hub.exportTo("web");
505
+ break;
506
+ case "import-from-web": {
507
+ // Exchange archives deliberately contain Profile data, not pi project configuration.
508
+ const settings = await readFile(join(ctx.cwd, ".pi/settings.json"));
509
+ const system = await readFile(join(ctx.cwd, ".pi/SYSTEM.md"));
510
+ importConfirmed = false;
511
+ const imported = await h.hub.importFrom("web");
512
+ if (!wasImportConfirmed()) {
513
+ ctx.ui.notify("Import cancelled.", "info");
514
+ return;
515
+ }
516
+ await mkdir(join(ctx.cwd, ".pi"), { recursive: true });
517
+ await writeFile(join(ctx.cwd, ".pi/settings.json"), settings);
518
+ await writeFile(join(ctx.cwd, ".pi/SYSTEM.md"), system);
519
+ host = undefined;
520
+ active = undefined;
521
+ ctx.ui.notify("Imported " + imported.sessions.length + " Sessions. Use /resume to continue one.", "info");
522
+ await ctx.newSession();
523
+ break;
524
+ }
525
+ default:
526
+ ctx.ui.notify("Usage: /ncept login | logout | export-to-web | import-from-web", "info");
527
+ }
528
+ },
529
+ });
530
+ }
package/dist/init.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Create a learning project without changing the user's pi agent directory. */
2
+ export declare function initProject(directory: string): Promise<string>;
package/dist/init.js ADDED
@@ -0,0 +1,13 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { init } from "@mmon-co/ncept-local";
4
+ import { tutorSystemPrompt } from "@mmon-co/ncept-default-theory";
5
+ /** Create a learning project without changing the user's pi agent directory. */
6
+ export async function initProject(directory) {
7
+ const dir = resolve(directory);
8
+ await init(dir);
9
+ await mkdir(join(dir, ".pi"), { recursive: true });
10
+ await writeFile(join(dir, ".pi/settings.json"), JSON.stringify({ packages: ["npm:@mmon-co/ncept-pi"], sessionDir: "sessions" }, null, 2) + "\n", { flag: "wx" });
11
+ await writeFile(join(dir, ".pi/SYSTEM.md"), tutorSystemPrompt("empty") + "\n", { flag: "wx" });
12
+ return dir;
13
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@mmon-co/ncept-pi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Learn in pi from a Profile directory you own",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/mmon-co/ncept.git",
12
+ "directory": "packages/pi"
13
+ },
14
+ "bin": {
15
+ "ncept-pi": "dist/cli.js"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "src",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/init.d.ts",
27
+ "default": "./dist/init.js"
28
+ }
29
+ },
30
+ "scripts": {
31
+ "build": "bun run --cwd ../local build && bun run --cwd ../default-theory build && tsc -p tsconfig.build.json",
32
+ "prepack": "bun run build"
33
+ },
34
+ "dependencies": {
35
+ "@mmon-co/ncept-core": "^0.1.0",
36
+ "@mmon-co/ncept-default-theory": "^1.0.0",
37
+ "@mmon-co/ncept-local": "^0.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "@earendil-works/pi-ai": "1.5.0",
41
+ "@earendil-works/pi-coding-agent": "1.5.0",
42
+ "bun-types": "^1.3.14",
43
+ "typescript": "5.9.3"
44
+ },
45
+ "peerDependencies": {
46
+ "@earendil-works/pi-coding-agent": "*"
47
+ },
48
+ "engines": {
49
+ "node": ">=22.19.0"
50
+ },
51
+ "pi": {
52
+ "extensions": [
53
+ "./src/extension.ts"
54
+ ]
55
+ }
56
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ import { initProject } from "./init.js";
3
+
4
+ const [command, directory, ...extra] = process.argv.slice(2);
5
+ if (command !== "init" || !directory || extra.length) {
6
+ console.error("Usage: npx @mmon-co/ncept-pi init <dir>");
7
+ process.exitCode = 1;
8
+ } else {
9
+ try {
10
+ const dir = await initProject(directory);
11
+ console.log(
12
+ "Profile ready: " +
13
+ dir +
14
+ "\nRun: cd " +
15
+ JSON.stringify(dir) +
16
+ " && pi\nTrust this learning project when pi asks.",
17
+ );
18
+ } catch (error) {
19
+ console.error(error instanceof Error ? error.message : String(error));
20
+ process.exitCode = 1;
21
+ }
22
+ }
@@ -0,0 +1,575 @@
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 { ExtensionAPI, ExtensionContext, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
5
+ import type { ModeEntry, Theory } from "@mmon-co/ncept-core";
6
+ import { defaultTheory } from "@mmon-co/ncept-default-theory";
7
+ import {
8
+ credentialsPath,
9
+ openHost,
10
+ parsePiSession,
11
+ type Host,
12
+ type HostSession,
13
+ type HostChatSetup,
14
+ type ModeSwitch,
15
+ type ModelRequest,
16
+ } from "@mmon-co/ncept-local";
17
+
18
+ const { version }: { version: string } = createRequire(import.meta.url)("../package.json");
19
+ const STATE = "ncept.session";
20
+ type Selection = { mode: string; entry?: ModeEntry; resume?: string };
21
+
22
+ function storedSession(ctx: ExtensionContext): string | undefined {
23
+ const saved = ctx.sessionManager
24
+ .getBranch()
25
+ .findLast((entry) => entry.type === "custom" && entry.customType === STATE);
26
+ if (saved?.type !== "custom" || !saved.data || typeof saved.data !== "object") return undefined;
27
+ return "id" in saved.data && typeof saved.data.id === "string" ? saved.data.id : undefined;
28
+ }
29
+
30
+ /** One extension instance belongs to one pi session, including after /resume. */
31
+ export default function ncept(pi: ExtensionAPI) {
32
+ let host: Host | undefined;
33
+ let active: HostSession | undefined;
34
+ let context: ExtensionContext;
35
+ let mounted: HostChatSetup | undefined;
36
+ let transition: ModeSwitch | undefined;
37
+ const ownTools = new Set<string>();
38
+ const graded = new Set<string>();
39
+ let gradeReply = false;
40
+ let importConfirmed = false;
41
+
42
+ async function model(request: ModelRequest): Promise<unknown> {
43
+ if (!context.model) throw new Error("Choose a pi model before learning.");
44
+ // Use pi's provider/auth runtime, including OAuth and custom model providers.
45
+ const response = await context.modelRegistry
46
+ .streamSimple(
47
+ context.model,
48
+ {
49
+ systemPrompt:
50
+ (request.kind === "judge"
51
+ ? request.instruction
52
+ : "Assess each criterion independently. Return its probability (0 to 1) that the learner demonstrated it, using the supplied evidence.") +
53
+ "\nCall reply with the structured judgment.",
54
+ messages: [
55
+ {
56
+ role: "user",
57
+ content: JSON.stringify(
58
+ request.kind === "judge" ? request.input : { input: request.input, criteria: request.criteria },
59
+ ),
60
+ timestamp: Date.now(),
61
+ },
62
+ ],
63
+ tools: [
64
+ {
65
+ name: "reply",
66
+ description: "Return the structured judgment.",
67
+ // Tool arguments are always objects; a Theory may ask for a scalar.
68
+ parameters: {
69
+ type: "object",
70
+ properties: { value: request.schema },
71
+ required: ["value"],
72
+ additionalProperties: false,
73
+ },
74
+ // Theory schemas use full JSON Schema (for example uniqueItems), not
75
+ // OpenAI's strict subset. The host validates the returned judgment.
76
+ constrainedSampling: false,
77
+ },
78
+ ],
79
+ },
80
+ { signal: context.signal },
81
+ )
82
+ .result();
83
+ if (response.stopReason === "error" || response.stopReason === "aborted")
84
+ throw new Error(response.errorMessage ?? "Judgment interrupted");
85
+ const reply = response.content.find((part) => part.type === "toolCall" && part.name === "reply");
86
+ if (!reply || reply.type !== "toolCall")
87
+ throw new Error("The selected model did not return a structured judgment.");
88
+ return reply.arguments.value;
89
+ }
90
+
91
+ function wasImportConfirmed(): boolean {
92
+ return importConfirmed;
93
+ }
94
+
95
+ async function getHost(ctx: ExtensionContext): Promise<Host> {
96
+ context = ctx;
97
+ if (!ctx.isProjectTrusted()) throw new Error("Trust the Profile project before learning.");
98
+ if (host) return host;
99
+ const manifest: unknown = JSON.parse(await readFile(join(ctx.cwd, "profile.json"), "utf8"));
100
+ if (!manifest || typeof manifest !== "object" || !("theories" in manifest) || !Array.isArray(manifest.theories))
101
+ throw new Error("Not an mmon Profile. Run npx @mmon-co/ncept-pi init <dir> first.");
102
+ const require = createRequire(join(ctx.cwd, "profile.json"));
103
+ const theories: Theory<unknown>[] = [];
104
+ for (const name of manifest.theories) {
105
+ if (typeof name !== "string") throw new Error("Invalid Theory package name");
106
+ const module = name === "@mmon-co/ncept-default-theory" ? { defaultTheory } : await import(require.resolve(name));
107
+ const theory: Theory<unknown> = module.defaultTheory ?? module.default ?? module.theory;
108
+ theories.push(theory);
109
+ }
110
+ host = await openHost({
111
+ profileDir: ctx.cwd,
112
+ hub: {
113
+ userAgent: "ncept-pi/" + version,
114
+ clientMetadataUrl: "https://pi.dev/oauth/client.json",
115
+ url: process.env.NCEPT_HUB_URL,
116
+ credentialsFile: process.env.NCEPT_CREDENTIALS_FILE,
117
+ },
118
+ theories,
119
+ model,
120
+ confirm: async (proposal) => {
121
+ const accepted = await context.ui.confirm(
122
+ proposal.title,
123
+ proposal.description + "\n\n" + JSON.stringify(proposal.detail, null, 2),
124
+ );
125
+ if (proposal.kind === "hub.import") importConfirmed = accepted;
126
+ return accepted;
127
+ },
128
+ });
129
+ return host;
130
+ }
131
+
132
+ async function session(ctx: ExtensionContext): Promise<HostSession> {
133
+ const h = await getHost(ctx);
134
+ if (active) return active;
135
+ let resume = storedSession(ctx);
136
+ if (!resume) {
137
+ const profile = await h.profile.read();
138
+ const filename = ctx.sessionManager.getSessionFile();
139
+ const surface = Object.entries(profile.manifest.sessions).find(
140
+ ([, file]) => file === basename(filename ?? ""),
141
+ )?.[0];
142
+ // Imported web Sessions have no extension entry; the host resolves their surface.
143
+ resume = surface;
144
+ }
145
+ active = await h.sessions.open({ mode: "empty", ...(resume ? { resume } : {}) });
146
+ pi.appendEntry(STATE, { id: active.id });
147
+ await sync(ctx);
148
+ return active;
149
+ }
150
+
151
+ async function sync(ctx: ExtensionContext) {
152
+ if (!host || !active) return;
153
+ const file = ctx.sessionManager.getSessionFile();
154
+ const header = ctx.sessionManager.getHeader();
155
+ if (!file || !header) throw new Error("Learning requires a persistent pi session.");
156
+ try {
157
+ await readFile(file);
158
+ } catch (error) {
159
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
160
+ throw error;
161
+ }
162
+ if (relative(join(ctx.cwd, "sessions"), dirname(file)) !== "")
163
+ throw new Error(
164
+ "pi sessions must be stored in this Profile's sessions directory. Remove --session-dir or PI_CODING_AGENT_SESSION_DIR overrides.",
165
+ );
166
+ const entries = ctx.sessionManager.getEntries();
167
+ const leaf = ctx.sessionManager.getLeafEntry();
168
+ // The local host follows the last entry's branch, including after /tree.
169
+ const selected = leaf ? [...entries.filter((entry) => entry.id !== leaf.id), leaf] : entries;
170
+ const source = [header, ...selected].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
171
+ parsePiSession(source);
172
+ await mkdir(dirname(file), { recursive: true });
173
+ // Pi owns file creation. Refresh only a file it has persisted, preserving
174
+ // the selected /tree branch for the host without racing its exclusive create.
175
+ await writeFile(file, source);
176
+ await host.profile.registerSession(active.surface, basename(file), { trusted: ctx.isProjectTrusted() });
177
+ }
178
+
179
+ function permitted(name: string, description: string): boolean {
180
+ if (ownTools.has(name)) return !!mounted?.tools.some((tool) => tool.name === name);
181
+ if (
182
+ mounted?.capabilities.includes("bash") &&
183
+ ["bash", "powershell", "edit", "write", "grep", "find", "ls"].includes(name)
184
+ )
185
+ return true;
186
+ return !!mounted?.capabilities.includes("web") && /web|search|browse|fetch/i.test(name + " " + description);
187
+ }
188
+
189
+ async function prepare(ctx: ExtensionContext, learnerMessage?: string): Promise<HostChatSetup> {
190
+ const current = await session(ctx);
191
+ const h = await getHost(ctx);
192
+ await sync(ctx);
193
+ const setup = await h.sessions.turn(current, { ...(learnerMessage ? { learnerMessage } : {}) });
194
+ mounted = {
195
+ ...setup,
196
+ tools: [
197
+ ...setup.tools,
198
+ {
199
+ name: "hub",
200
+ description:
201
+ "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.",
202
+ schema: {
203
+ type: "object",
204
+ properties: {
205
+ op: { enum: ["pull", "publish"] },
206
+ address: { type: "string" },
207
+ version: { type: "string" },
208
+ title: { type: "string" },
209
+ description: { type: "string" },
210
+ },
211
+ required: ["op"],
212
+ additionalProperties: false,
213
+ },
214
+ run: async (raw) => {
215
+ if (!raw || typeof raw !== "object") throw new Error("Invalid Hub request");
216
+ const input = Object.fromEntries(Object.entries(raw));
217
+ if (input.op === "pull" && typeof input.address === "string")
218
+ return { content: await h.hub.pull(input.address) };
219
+ if (
220
+ input.op !== "publish" ||
221
+ current.mode !== "authoring" ||
222
+ typeof input.version !== "string" ||
223
+ typeof input.title !== "string"
224
+ )
225
+ throw new Error("Pull needs address; publish needs authoring mode, version and title.");
226
+ return {
227
+ content: await h.hub.publish({
228
+ patch: (await h.profile.read()).manifest.personal,
229
+ version: input.version,
230
+ title: input.title,
231
+ ...(typeof input.description === "string" ? { description: input.description } : {}),
232
+ }),
233
+ };
234
+ },
235
+ },
236
+ ],
237
+ };
238
+ for (const tool of mounted.tools) {
239
+ ownTools.add(tool.name);
240
+ pi.registerTool({
241
+ name: tool.name,
242
+ label: tool.name,
243
+ description: tool.description,
244
+ parameters: tool.schema,
245
+ async execute(_id, input, _signal, _onUpdate, toolCtx) {
246
+ context = toolCtx;
247
+ if (transition) throw new Error("A Session switch is pending.");
248
+ await sync(toolCtx);
249
+ if (!mounted) throw new Error("No active learning mode.");
250
+ const currentTool = mounted.tools.find((candidate) => candidate.name === tool.name);
251
+ if (!currentTool) throw new Error("Tool is not mounted in this mode.");
252
+ const result = await currentTool.run(input);
253
+ if (result.switch && result.switch.then === "here") {
254
+ active = {
255
+ ...current,
256
+ mode: result.switch.mode,
257
+ ...(result.switch.entry ? { entry: result.switch.entry } : {}),
258
+ };
259
+ await prepare(toolCtx);
260
+ } else if (result.switch) {
261
+ transition = result.switch;
262
+ toolCtx.abort();
263
+ }
264
+ return { content: [{ type: "text", text: JSON.stringify(result.content ?? null) }], details: result };
265
+ },
266
+ });
267
+ }
268
+ pi.setActiveTools(
269
+ pi
270
+ .getAllTools()
271
+ .filter((tool) => permitted(tool.name, tool.description))
272
+ .map(({ name }) => name),
273
+ );
274
+ return mounted;
275
+ }
276
+
277
+ function prompt(setup: HostChatSetup): string {
278
+ return (
279
+ setup.prompt +
280
+ "\n\n" +
281
+ setup.context +
282
+ "\n\nMounted Skills (read with skill):\n" +
283
+ setup.skills.map(({ name, description }) => "- " + name + ": " + description).join("\n")
284
+ );
285
+ }
286
+
287
+ async function dashboard(ctx: ExtensionContext) {
288
+ const reading = await (await getHost(ctx)).reading();
289
+ ctx.ui.setWidget(
290
+ "ncept",
291
+ [
292
+ "Me",
293
+ ...reading.missions
294
+ .filter(({ run }) => !run.retired)
295
+ .map(
296
+ ({ mission, next }) =>
297
+ mission.statement + " — " + (next[0]?.name ?? "chart the next stop") + " /learn " + mission.id,
298
+ ),
299
+ reading.missions.length ? "" : "No Missions yet. /learn <what I want to learn>",
300
+ reading.dueReview.length + " Nodes due for review. /review",
301
+ "/learn · /missions · /author · /hub pull <url>",
302
+ ].filter(Boolean),
303
+ );
304
+ }
305
+
306
+ async function enter(
307
+ ctx: ExtensionCommandContext,
308
+ selection: Selection,
309
+ kickoff?: string,
310
+ carry?: string,
311
+ aside = false,
312
+ ) {
313
+ const h = await getHost(ctx);
314
+ const old = active;
315
+ const empty = !ctx.sessionManager.getBranch().some((entry) => entry.type === "message");
316
+ await sync(ctx);
317
+ // Closing records the old conversation; /resume reopens it.
318
+ if (old && !aside) await h.sessions.close(old);
319
+ const opened = await h.sessions.open(selection);
320
+ if (empty) {
321
+ active = opened;
322
+ mounted = undefined;
323
+ pi.appendEntry(STATE, { id: opened.id });
324
+ if (carry) pi.sendMessage({ customType: "ncept.carry", content: carry, display: false });
325
+ if (kickoff) pi.sendUserMessage(kickoff);
326
+ return;
327
+ }
328
+ const parentSession = ctx.sessionManager.getSessionFile();
329
+ const result = await ctx.newSession({
330
+ ...(parentSession ? { parentSession } : {}),
331
+ setup: async (sm) => {
332
+ sm.appendCustomEntry(STATE, { id: opened.id });
333
+ if (carry) sm.appendCustomMessageEntry("ncept.carry", carry, false);
334
+ },
335
+ withSession: async (fresh) => {
336
+ if (kickoff) await fresh.sendUserMessage(kickoff);
337
+ },
338
+ });
339
+ if (result.cancelled) {
340
+ await h.sessions.close(opened);
341
+ active = old ? await h.sessions.open({ mode: old.mode, resume: old.id }) : undefined;
342
+ ctx.ui.notify("Session switch cancelled.", "info");
343
+ }
344
+ }
345
+
346
+ pi.on("session_start", async (_event, ctx) => {
347
+ await dashboard(ctx);
348
+ });
349
+ pi.on("before_agent_start", async (event, ctx) => {
350
+ ctx.ui.setWidget("ncept", undefined);
351
+ gradeReply = event.messageType === "user";
352
+ const setup = await prepare(ctx);
353
+ event.systemPromptOptions.contextFiles = [];
354
+ event.systemPromptOptions.skills = [];
355
+ event.systemPromptOptions.appendSystemPrompt = "";
356
+ event.systemPromptOptions.customPrompt = prompt(setup);
357
+ event.systemPromptOptions.sections = {};
358
+ });
359
+ pi.on("context_with_system", async (event, ctx) => {
360
+ // before_agent_start precedes persistence of the starting user message. Grade
361
+ // only once pi has assigned its real entry id, before the provider sees it.
362
+ const learner = ctx.sessionManager
363
+ .getBranch()
364
+ .findLast((entry) => entry.type === "message" && entry.message.role === "user");
365
+ if (gradeReply && learner && !graded.has(learner.id)) {
366
+ await prepare(ctx, learner.id);
367
+ graded.add(learner.id);
368
+ gradeReply = false;
369
+ }
370
+ if (!mounted) return;
371
+ const selected = new Set(pi.getActiveTools());
372
+ return {
373
+ messages: [
374
+ {
375
+ role: "system",
376
+ content: prompt(mounted),
377
+ toolsAdded: pi
378
+ .getAllTools()
379
+ .filter(({ name }) => selected.has(name))
380
+ .map(({ name, description, parameters }) => ({ name, description, parameters })),
381
+ timestamp: Date.now(),
382
+ },
383
+ ...event.messages.filter((message) => message.role !== "system"),
384
+ ],
385
+ };
386
+ });
387
+ pi.on("tool_call", (event) => {
388
+ const tool = pi.getAllTools().find(({ name }) => name === event.toolName);
389
+ if (!tool || !permitted(tool.name, tool.description))
390
+ return { block: true, reason: "This tool is not mounted in the current learning mode." };
391
+ });
392
+ pi.on("turn_end", async (_event, ctx) => {
393
+ await sync(ctx);
394
+ });
395
+ pi.on("session_shutdown", async (event, ctx) => {
396
+ if (!active || !host) return;
397
+ await sync(ctx);
398
+ if (event.reason === "quit") await host.sessions.close(active);
399
+ });
400
+ pi.on("agent_settled", (_event, ctx) => {
401
+ if (transition) pi.sendUserMessage("/ncept-next", { expandPromptTemplates: true });
402
+ else if (active) ctx.ui.setStatus("ncept", active.mode);
403
+ });
404
+
405
+ pi.registerCommand("ncept-next", {
406
+ description: "Continue a tutor-requested Session switch",
407
+ handler: async (_args, ctx) => {
408
+ if (!transition) return;
409
+ const to = transition;
410
+ transition = undefined;
411
+ let carry: string;
412
+ if (to.then === "here") return;
413
+ if (to.carry.kind === "brief") {
414
+ const recent = ctx.sessionManager
415
+ .getBranch()
416
+ .flatMap((entry) => {
417
+ if (entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "assistant"))
418
+ return [];
419
+ const content = entry.message.content;
420
+ const text =
421
+ typeof content === "string"
422
+ ? content
423
+ : content
424
+ .filter((part) => part.type === "text")
425
+ .map((part) => part.text)
426
+ .join("\n");
427
+ return text ? [{ role: entry.message.role, text: text.slice(-2000) }] : [];
428
+ })
429
+ .slice(-6);
430
+ carry =
431
+ to.carry.text ??
432
+ "Previous Session (recent conversation):\n" +
433
+ JSON.stringify(recent) +
434
+ "\nNext entry:\n" +
435
+ JSON.stringify(to.entry ?? {});
436
+ } else {
437
+ const messages = ctx.sessionManager
438
+ .getBranch()
439
+ .flatMap((entry) =>
440
+ entry.type === "message" && ["user", "assistant"].includes(entry.message.role) ? [entry.message] : [],
441
+ );
442
+ if (to.carry.kind === "full") carry = JSON.stringify(messages);
443
+ else {
444
+ if (!ctx.model) throw new Error("Choose a pi model before carrying a Session.");
445
+ const response = await ctx.modelRegistry
446
+ .streamSimple(
447
+ ctx.model,
448
+ {
449
+ systemPrompt: "Summarize the learning conversation for the next tutor. Focus: " + to.carry.focus,
450
+ messages: [{ role: "user", content: JSON.stringify(messages), timestamp: Date.now() }],
451
+ },
452
+ { signal: ctx.signal },
453
+ )
454
+ .result();
455
+ if (response.stopReason === "error" || response.stopReason === "aborted")
456
+ throw new Error(response.errorMessage ?? "Carry interrupted");
457
+ carry = response.content
458
+ .filter((part) => part.type === "text")
459
+ .map((part) => part.text)
460
+ .join("\n");
461
+ }
462
+ }
463
+ await enter(ctx, to, "Continue.", carry, to.then === "aside");
464
+ },
465
+ });
466
+ pi.registerCommand("learn", {
467
+ description: "Learn a goal, or choose a Mission and its next stop",
468
+ handler: async (args, ctx) => {
469
+ const missions = await (await getHost(ctx)).missions.list();
470
+ let mission = missions.find(({ mission }) => mission.id === args.trim());
471
+ if (!args.trim()) {
472
+ const choices = missions.filter(({ run }) => !run.retired);
473
+ const options = choices.map(
474
+ ({ mission, next }) => mission.statement + " — " + (next[0]?.name ?? "chart the next stop"),
475
+ );
476
+ const selected = await ctx.ui.select("Learn", [...options, "New goal…"]);
477
+ if (!selected) return;
478
+ if (selected === "New goal…") {
479
+ const goal = await ctx.ui.input("What do you want to learn?");
480
+ if (goal?.trim()) await enter(ctx, { mode: "charting", entry: { kind: "goal", text: goal } }, goal);
481
+ return;
482
+ }
483
+ mission = choices[options.indexOf(selected)];
484
+ }
485
+ if (mission)
486
+ await enter(
487
+ ctx,
488
+ { mode: "charting", entry: { kind: "mission", id: mission.mission.id } },
489
+ "Let's continue this Mission.",
490
+ );
491
+ else await enter(ctx, { mode: "charting", entry: { kind: "goal", text: args.trim() } }, args.trim());
492
+ },
493
+ });
494
+ pi.registerCommand("review", {
495
+ description: "Review what is due",
496
+ handler: async (_args, ctx) => {
497
+ const { dueReview } = await (await getHost(ctx)).reading();
498
+ if (!dueReview.length) {
499
+ ctx.ui.notify("No review due.", "info");
500
+ return;
501
+ }
502
+ await enter(ctx, { mode: "lesson", entry: { kind: "review", nodes: dueReview } }, "Let's review.");
503
+ },
504
+ });
505
+ pi.registerCommand("author", {
506
+ description: "Author a learning map and Materials",
507
+ handler: async (args, ctx) =>
508
+ enter(
509
+ ctx,
510
+ { mode: "authoring", ...(args.trim() ? { entry: { kind: "goal", text: args.trim() } as const } : {}) },
511
+ args.trim() || "Let's author a learning map.",
512
+ ),
513
+ });
514
+ pi.registerCommand("missions", {
515
+ description: "Show Missions and next stops",
516
+ handler: async (_args, ctx) => {
517
+ await dashboard(ctx);
518
+ },
519
+ });
520
+ pi.registerCommand("hub", {
521
+ description: "Pull a Hub release: /hub pull <url or patch@version>",
522
+ handler: async (args, ctx) => {
523
+ const match = /^pull\s+(.+)$/.exec(args.trim());
524
+ if (!match?.[1]) {
525
+ ctx.ui.notify("Usage: /hub pull <url or patch@version>", "info");
526
+ return;
527
+ }
528
+ const ref = await (await getHost(ctx)).hub.pull(match[1]);
529
+ ctx.ui.notify("Adopted " + ref.identity + "@" + ref.digest, "info");
530
+ await dashboard(ctx);
531
+ },
532
+ });
533
+ pi.registerCommand("ncept", {
534
+ description: "ncept login | logout | export-to-web | import-from-web",
535
+ handler: async (args, ctx) => {
536
+ const h = await getHost(ctx);
537
+ await sync(ctx);
538
+ switch (args.trim()) {
539
+ case "login":
540
+ await h.hub.signIn();
541
+ ctx.ui.notify("Signed in to Common Concept.", "info");
542
+ break;
543
+ case "logout":
544
+ await rm(process.env.NCEPT_CREDENTIALS_FILE ?? credentialsPath(), { force: true });
545
+ host = undefined;
546
+ ctx.ui.notify("Signed out of Common Concept.", "info");
547
+ break;
548
+ case "export-to-web":
549
+ await h.hub.exportTo("web");
550
+ break;
551
+ case "import-from-web": {
552
+ // Exchange archives deliberately contain Profile data, not pi project configuration.
553
+ const settings = await readFile(join(ctx.cwd, ".pi/settings.json"));
554
+ const system = await readFile(join(ctx.cwd, ".pi/SYSTEM.md"));
555
+ importConfirmed = false;
556
+ const imported = await h.hub.importFrom("web");
557
+ if (!wasImportConfirmed()) {
558
+ ctx.ui.notify("Import cancelled.", "info");
559
+ return;
560
+ }
561
+ await mkdir(join(ctx.cwd, ".pi"), { recursive: true });
562
+ await writeFile(join(ctx.cwd, ".pi/settings.json"), settings);
563
+ await writeFile(join(ctx.cwd, ".pi/SYSTEM.md"), system);
564
+ host = undefined;
565
+ active = undefined;
566
+ ctx.ui.notify("Imported " + imported.sessions.length + " Sessions. Use /resume to continue one.", "info");
567
+ await ctx.newSession();
568
+ break;
569
+ }
570
+ default:
571
+ ctx.ui.notify("Usage: /ncept login | logout | export-to-web | import-from-web", "info");
572
+ }
573
+ },
574
+ });
575
+ }
package/src/init.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { init } from "@mmon-co/ncept-local";
4
+ import { tutorSystemPrompt } from "@mmon-co/ncept-default-theory";
5
+
6
+ /** Create a learning project without changing the user's pi agent directory. */
7
+ export async function initProject(directory: string): Promise<string> {
8
+ const dir = resolve(directory);
9
+ await init(dir);
10
+ await mkdir(join(dir, ".pi"), { recursive: true });
11
+ await writeFile(
12
+ join(dir, ".pi/settings.json"),
13
+ JSON.stringify({ packages: ["npm:@mmon-co/ncept-pi"], sessionDir: "sessions" }, null, 2) + "\n",
14
+ { flag: "wx" },
15
+ );
16
+ await writeFile(join(dir, ".pi/SYSTEM.md"), tutorSystemPrompt("empty") + "\n", { flag: "wx" });
17
+ return dir;
18
+ }