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