@mmon-co/ncept-pi 0.1.0 → 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/README.md +6 -1
- package/dist/events.d.ts +43 -0
- package/dist/events.js +18 -0
- package/dist/extension.js +253 -81
- package/dist/init.js +2 -1
- package/package.json +8 -4
- package/src/events.ts +44 -0
- package/src/extension.ts +264 -90
- package/src/init.ts +2 -1
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@ pi
|
|
|
15
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
16
|
|
|
17
17
|
- `/learn <goal>` charts what you want to learn. `/learn` offers Missions and their next stops; `/learn <mission-id>` opens a particular Mission.
|
|
18
|
+
- `/skip` in a Mission Lesson skips this Lesson or ahead to a later planned stop, recording the skipped Nodes as claimed known.
|
|
18
19
|
- `/review` opens the due review batch; `/author [goal]` opens an authoring Session.
|
|
19
20
|
- `/missions` shows the dashboard again.
|
|
20
21
|
- `/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.
|
|
@@ -23,12 +24,16 @@ Accept pi's one-time project trust prompt. The dashboard above the editor shows
|
|
|
23
24
|
- `/ncept export-to-web` replaces web Main with this Profile after confirmation (and, if needed, choosing the Missions that fit the web allowance).
|
|
24
25
|
- `/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
|
|
|
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.
|
|
27
|
+
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. A session pi keeps elsewhere (`--session-dir`, `PI_CODING_AGENT_SESSION_DIR`, or a front end such as bb's pi bridge) is mirrored into `sessions/`, so the Profile still carries every transcript.
|
|
27
28
|
|
|
28
29
|
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
|
|
|
30
31
|
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
|
|
|
33
|
+
## Front ends over this extension
|
|
34
|
+
|
|
35
|
+
A front end layered over pi can own where Sessions open, a new window or thread per Session say, through pi's shared extension bus. When a Session opens while the current pi session already holds a conversation, the extension emits `ncept:open-session` with the opened Session, its kickoff message, its hidden carry and whether it is aside; a listener that calls `claim` opens it itself, and the current pi session stays visible for the learner to archive. Its next message resumes its previous host Session before the turn. The claimant can return a learner-facing continuation (a link, for example); a tutor-requested switch returns it in the tool result so the tutor can finish the outgoing turn normally. In the fresh pi session, the front end emits `ncept:adopt-session` with the Session and carry before the first prompt. For a learner control without an outgoing conversation, emit `ncept:begin-session` after this extension's `session_start`, supplying a local-host `SessionIntent` and a `claim` callback. Await the claimed function before the first prompt; it resolves the intent and records the Session in pi. The channels and payload types are exported from `@mmon-co/ncept-pi/events`.
|
|
36
|
+
|
|
32
37
|
## Development first use
|
|
33
38
|
|
|
34
39
|
From a repository checkout:
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { HostSession, SessionIntent } from "@mmon-co/ncept-local";
|
|
2
|
+
/**
|
|
3
|
+
* Channels on pi's shared extension bus (`pi.events`) that let another front end
|
|
4
|
+
* layered over this extension (a bb thread per Session, say) own where Sessions open.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Emitted when the tutor or a command opens a host Session while the current pi
|
|
8
|
+
* session already holds a conversation. A listener that calls `claim` opens it
|
|
9
|
+
* elsewhere; otherwise this extension starts a new pi session in-process.
|
|
10
|
+
*/
|
|
11
|
+
export declare const OPEN_SESSION = "ncept:open-session";
|
|
12
|
+
export type OpenSession = {
|
|
13
|
+
/** The opened host Session, already recorded in the Profile. */
|
|
14
|
+
readonly session: string;
|
|
15
|
+
readonly mode: string;
|
|
16
|
+
/** Starting text for the new conversation. */
|
|
17
|
+
readonly kickoff?: string;
|
|
18
|
+
/** The learner supplied this text, rather than a host continuation. */
|
|
19
|
+
readonly learnerKickoff?: boolean;
|
|
20
|
+
/** Context the next tutor needs from this conversation, hidden from the learner. */
|
|
21
|
+
readonly carry?: string;
|
|
22
|
+
/** The previous Session stays open beside the new one. */
|
|
23
|
+
readonly aside: boolean;
|
|
24
|
+
/** Take over opening; return a learner-facing continuation for the tutor's tool result.
|
|
25
|
+
* A rejection closes the new Session and keeps the current one. */
|
|
26
|
+
claim(open: () => Promise<void | string>): void;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Emitted by the claiming front end in a fresh pi session, before its first prompt,
|
|
30
|
+
* to continue a claimed host Session there.
|
|
31
|
+
*/
|
|
32
|
+
export declare const ADOPT_SESSION = "ncept:adopt-session";
|
|
33
|
+
export type AdoptSession = {
|
|
34
|
+
readonly session: string;
|
|
35
|
+
readonly carry?: string;
|
|
36
|
+
};
|
|
37
|
+
/** A front end starts a fresh conversation from a learner entry, after session_start.
|
|
38
|
+
* The tutoring extension alone resolves the entry and writes the Profile. */
|
|
39
|
+
export declare const BEGIN_SESSION = "ncept:begin-session";
|
|
40
|
+
export type BeginSession = {
|
|
41
|
+
readonly intent: SessionIntent;
|
|
42
|
+
claim(begin: () => Promise<HostSession>): void;
|
|
43
|
+
};
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Channels on pi's shared extension bus (`pi.events`) that let another front end
|
|
3
|
+
* layered over this extension (a bb thread per Session, say) own where Sessions open.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Emitted when the tutor or a command opens a host Session while the current pi
|
|
7
|
+
* session already holds a conversation. A listener that calls `claim` opens it
|
|
8
|
+
* elsewhere; otherwise this extension starts a new pi session in-process.
|
|
9
|
+
*/
|
|
10
|
+
export const OPEN_SESSION = "ncept:open-session";
|
|
11
|
+
/**
|
|
12
|
+
* Emitted by the claiming front end in a fresh pi session, before its first prompt,
|
|
13
|
+
* to continue a claimed host Session there.
|
|
14
|
+
*/
|
|
15
|
+
export const ADOPT_SESSION = "ncept:adopt-session";
|
|
16
|
+
/** A front end starts a fresh conversation from a learner entry, after session_start.
|
|
17
|
+
* The tutoring extension alone resolves the entry and writes the Profile. */
|
|
18
|
+
export const BEGIN_SESSION = "ncept:begin-session";
|
package/dist/extension.js
CHANGED
|
@@ -3,6 +3,7 @@ import { basename, dirname, join, relative } from "node:path";
|
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { defaultTheory } from "@mmon-co/ncept-default-theory";
|
|
5
5
|
import { credentialsPath, openHost, parsePiSession, } from "@mmon-co/ncept-local";
|
|
6
|
+
import { ADOPT_SESSION, BEGIN_SESSION, OPEN_SESSION } from "./events.js";
|
|
6
7
|
const { version } = createRequire(import.meta.url)("../package.json");
|
|
7
8
|
const STATE = "ncept.session";
|
|
8
9
|
function storedSession(ctx) {
|
|
@@ -13,6 +14,34 @@ function storedSession(ctx) {
|
|
|
13
14
|
return undefined;
|
|
14
15
|
return "id" in saved.data && typeof saved.data.id === "string" ? saved.data.id : undefined;
|
|
15
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
|
+
}
|
|
16
45
|
/** One extension instance belongs to one pi session, including after /resume. */
|
|
17
46
|
export default function ncept(pi) {
|
|
18
47
|
let host;
|
|
@@ -20,9 +49,12 @@ export default function ncept(pi) {
|
|
|
20
49
|
let context;
|
|
21
50
|
let mounted;
|
|
22
51
|
let transition;
|
|
52
|
+
let pendingEnter;
|
|
23
53
|
const ownTools = new Set();
|
|
24
54
|
const graded = new Set();
|
|
25
55
|
let gradeReply = false;
|
|
56
|
+
let relayingContinuation = false;
|
|
57
|
+
let promptOptions;
|
|
26
58
|
let importConfirmed = false;
|
|
27
59
|
async function model(request) {
|
|
28
60
|
if (!context.model)
|
|
@@ -138,25 +170,26 @@ export default function ncept(pi) {
|
|
|
138
170
|
return;
|
|
139
171
|
throw error;
|
|
140
172
|
}
|
|
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
173
|
const entries = ctx.sessionManager.getEntries();
|
|
144
174
|
const leaf = ctx.sessionManager.getLeafEntry();
|
|
145
175
|
// The local host follows the last entry's branch, including after /tree.
|
|
146
176
|
const selected = leaf ? [...entries.filter((entry) => entry.id !== leaf.id), leaf] : entries;
|
|
147
177
|
const source = [header, ...selected].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
|
|
148
178
|
parsePiSession(source);
|
|
149
|
-
await mkdir(dirname(file), { recursive: true });
|
|
150
179
|
// Pi owns file creation. Refresh only a file it has persisted, preserving
|
|
151
180
|
// the selected /tree branch for the host without racing its exclusive create.
|
|
152
|
-
|
|
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);
|
|
153
186
|
await host.profile.registerSession(active.surface, basename(file), { trusted: ctx.isProjectTrusted() });
|
|
154
187
|
}
|
|
155
188
|
function permitted(name, description) {
|
|
156
189
|
if (ownTools.has(name))
|
|
157
190
|
return !!mounted?.tools.some((tool) => tool.name === name);
|
|
158
191
|
if (mounted?.capabilities.includes("bash") &&
|
|
159
|
-
["bash", "powershell", "edit", "write", "grep", "find", "ls"].includes(name))
|
|
192
|
+
["bash", "powershell", "edit", "write", "grep", "find", "ls", "codemode"].includes(name))
|
|
160
193
|
return true;
|
|
161
194
|
return !!mounted?.capabilities.includes("web") && /web|search|browse|fetch/i.test(name + " " + description);
|
|
162
195
|
}
|
|
@@ -234,8 +267,14 @@ export default function ncept(pi) {
|
|
|
234
267
|
await prepare(toolCtx);
|
|
235
268
|
}
|
|
236
269
|
else if (result.switch) {
|
|
237
|
-
|
|
238
|
-
toolCtx
|
|
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
|
+
};
|
|
239
278
|
}
|
|
240
279
|
return { content: [{ type: "text", text: JSON.stringify(result.content ?? null) }], details: result };
|
|
241
280
|
},
|
|
@@ -271,8 +310,8 @@ export default function ncept(pi) {
|
|
|
271
310
|
const old = active;
|
|
272
311
|
const empty = !ctx.sessionManager.getBranch().some((entry) => entry.type === "message");
|
|
273
312
|
await sync(ctx);
|
|
274
|
-
//
|
|
275
|
-
if (old && !aside)
|
|
313
|
+
// Skip admission needs the current stop; it closes the outgoing Mission Session itself.
|
|
314
|
+
if (old && !aside && !selection.skip)
|
|
276
315
|
await h.sessions.close(old);
|
|
277
316
|
const opened = await h.sessions.open(selection);
|
|
278
317
|
if (empty) {
|
|
@@ -285,39 +324,126 @@ export default function ncept(pi) {
|
|
|
285
324
|
pi.sendUserMessage(kickoff);
|
|
286
325
|
return;
|
|
287
326
|
}
|
|
288
|
-
|
|
289
|
-
const
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
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;
|
|
299
338
|
},
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
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
|
+
}
|
|
305
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;
|
|
306
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
|
+
});
|
|
307
403
|
pi.on("session_start", async (_event, ctx) => {
|
|
308
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
|
+
}
|
|
309
413
|
});
|
|
310
414
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
311
415
|
ctx.ui.setWidget("ncept", undefined);
|
|
416
|
+
relayingContinuation = event.messageType === "custom" && event.message.customType === "ncept.continuation";
|
|
312
417
|
gradeReply = event.messageType === "user";
|
|
313
|
-
const setup = await prepare(ctx);
|
|
418
|
+
const setup = relayingContinuation ? undefined : await prepare(ctx);
|
|
419
|
+
if (relayingContinuation)
|
|
420
|
+
pi.setActiveTools([]);
|
|
314
421
|
event.systemPromptOptions.contextFiles = [];
|
|
315
422
|
event.systemPromptOptions.skills = [];
|
|
316
423
|
event.systemPromptOptions.appendSystemPrompt = "";
|
|
317
|
-
event.systemPromptOptions
|
|
424
|
+
promptOptions = event.systemPromptOptions;
|
|
425
|
+
event.systemPromptOptions.customPrompt = setup ? prompt(setup) : "Return the host's continuation to the learner.";
|
|
318
426
|
event.systemPromptOptions.sections = {};
|
|
319
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
|
+
});
|
|
320
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
|
+
};
|
|
321
447
|
// before_agent_start precedes persistence of the starting user message. Grade
|
|
322
448
|
// only once pi has assigned its real entry id, before the provider sees it.
|
|
323
449
|
const learner = ctx.sessionManager
|
|
@@ -361,69 +487,79 @@ export default function ncept(pi) {
|
|
|
361
487
|
if (event.reason === "quit")
|
|
362
488
|
await host.sessions.close(active);
|
|
363
489
|
});
|
|
364
|
-
pi.on("agent_settled", (_event, ctx) => {
|
|
365
|
-
|
|
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)
|
|
366
495
|
pi.sendUserMessage("/ncept-next", { expandPromptTemplates: true });
|
|
367
496
|
else if (active)
|
|
368
497
|
ctx.ui.setStatus("ncept", active.mode);
|
|
369
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
|
+
}
|
|
370
549
|
pi.registerCommand("ncept-next", {
|
|
371
550
|
description: "Continue a tutor-requested Session switch",
|
|
372
551
|
handler: async (_args, ctx) => {
|
|
373
|
-
if (
|
|
552
|
+
if (pendingEnter) {
|
|
553
|
+
const finish = pendingEnter;
|
|
554
|
+
pendingEnter = undefined;
|
|
555
|
+
await finish(ctx);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
if (!transition || transition.then === "here")
|
|
374
559
|
return;
|
|
375
560
|
const to = transition;
|
|
376
561
|
transition = undefined;
|
|
377
|
-
|
|
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");
|
|
562
|
+
await enter(ctx, to, "Continue.", await carryFor(ctx, to), to.then === "aside");
|
|
427
563
|
},
|
|
428
564
|
});
|
|
429
565
|
pi.registerCommand("learn", {
|
|
@@ -451,6 +587,40 @@ export default function ncept(pi) {
|
|
|
451
587
|
await enter(ctx, { mode: "charting", entry: { kind: "goal", text: args.trim() } }, args.trim());
|
|
452
588
|
},
|
|
453
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
|
+
});
|
|
454
624
|
pi.registerCommand("review", {
|
|
455
625
|
description: "Review what is due",
|
|
456
626
|
handler: async (_args, ctx) => {
|
|
@@ -464,7 +634,9 @@ export default function ncept(pi) {
|
|
|
464
634
|
});
|
|
465
635
|
pi.registerCommand("author", {
|
|
466
636
|
description: "Author a learning map and Materials",
|
|
467
|
-
handler: async (args, ctx) =>
|
|
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
|
+
},
|
|
468
640
|
});
|
|
469
641
|
pi.registerCommand("missions", {
|
|
470
642
|
description: "Show Missions and next stops",
|
package/dist/init.js
CHANGED
|
@@ -7,7 +7,8 @@ export async function initProject(directory) {
|
|
|
7
7
|
const dir = resolve(directory);
|
|
8
8
|
await init(dir);
|
|
9
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"
|
|
10
|
+
await writeFile(join(dir, ".pi/settings.json"), JSON.stringify({ packages: ["npm:@mmon-co/ncept-pi"], sessionDir: "sessions", codemode: { mode: "on" } }, null, 2) +
|
|
11
|
+
"\n", { flag: "wx" });
|
|
11
12
|
await writeFile(join(dir, ".pi/SYSTEM.md"), tutorSystemPrompt("empty") + "\n", { flag: "wx" });
|
|
12
13
|
return dir;
|
|
13
14
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mmon-co/ncept-pi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Learn in pi from a Profile directory you own",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package"
|
|
@@ -25,6 +25,10 @@
|
|
|
25
25
|
".": {
|
|
26
26
|
"types": "./dist/init.d.ts",
|
|
27
27
|
"default": "./dist/init.js"
|
|
28
|
+
},
|
|
29
|
+
"./events": {
|
|
30
|
+
"types": "./dist/events.d.ts",
|
|
31
|
+
"default": "./dist/events.js"
|
|
28
32
|
}
|
|
29
33
|
},
|
|
30
34
|
"scripts": {
|
|
@@ -32,9 +36,9 @@
|
|
|
32
36
|
"prepack": "bun run build"
|
|
33
37
|
},
|
|
34
38
|
"dependencies": {
|
|
35
|
-
"@mmon-co/ncept-core": "^0.
|
|
36
|
-
"@mmon-co/ncept-default-theory": "^1.
|
|
37
|
-
"@mmon-co/ncept-local": "^0.
|
|
39
|
+
"@mmon-co/ncept-core": "^0.2.0",
|
|
40
|
+
"@mmon-co/ncept-default-theory": "^1.1.0",
|
|
41
|
+
"@mmon-co/ncept-local": "^0.2.0"
|
|
38
42
|
},
|
|
39
43
|
"devDependencies": {
|
|
40
44
|
"@earendil-works/pi-ai": "1.5.0",
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { HostSession, SessionIntent } from "@mmon-co/ncept-local";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Channels on pi's shared extension bus (`pi.events`) that let another front end
|
|
5
|
+
* layered over this extension (a bb thread per Session, say) own where Sessions open.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Emitted when the tutor or a command opens a host Session while the current pi
|
|
10
|
+
* session already holds a conversation. A listener that calls `claim` opens it
|
|
11
|
+
* elsewhere; otherwise this extension starts a new pi session in-process.
|
|
12
|
+
*/
|
|
13
|
+
export const OPEN_SESSION = "ncept:open-session";
|
|
14
|
+
export type OpenSession = {
|
|
15
|
+
/** The opened host Session, already recorded in the Profile. */
|
|
16
|
+
readonly session: string;
|
|
17
|
+
readonly mode: string;
|
|
18
|
+
/** Starting text for the new conversation. */
|
|
19
|
+
readonly kickoff?: string;
|
|
20
|
+
/** The learner supplied this text, rather than a host continuation. */
|
|
21
|
+
readonly learnerKickoff?: boolean;
|
|
22
|
+
/** Context the next tutor needs from this conversation, hidden from the learner. */
|
|
23
|
+
readonly carry?: string;
|
|
24
|
+
/** The previous Session stays open beside the new one. */
|
|
25
|
+
readonly aside: boolean;
|
|
26
|
+
/** Take over opening; return a learner-facing continuation for the tutor's tool result.
|
|
27
|
+
* A rejection closes the new Session and keeps the current one. */
|
|
28
|
+
claim(open: () => Promise<void | string>): void;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Emitted by the claiming front end in a fresh pi session, before its first prompt,
|
|
33
|
+
* to continue a claimed host Session there.
|
|
34
|
+
*/
|
|
35
|
+
export const ADOPT_SESSION = "ncept:adopt-session";
|
|
36
|
+
export type AdoptSession = { readonly session: string; readonly carry?: string };
|
|
37
|
+
|
|
38
|
+
/** A front end starts a fresh conversation from a learner entry, after session_start.
|
|
39
|
+
* The tutoring extension alone resolves the entry and writes the Profile. */
|
|
40
|
+
export const BEGIN_SESSION = "ncept:begin-session";
|
|
41
|
+
export type BeginSession = {
|
|
42
|
+
readonly intent: SessionIntent;
|
|
43
|
+
claim(begin: () => Promise<HostSession>): void;
|
|
44
|
+
};
|
package/src/extension.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
2
|
import { basename, dirname, join, relative } from "node:path";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
|
-
import type {
|
|
5
|
-
|
|
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";
|
|
6
11
|
import { defaultTheory } from "@mmon-co/ncept-default-theory";
|
|
7
12
|
import {
|
|
8
13
|
credentialsPath,
|
|
@@ -13,11 +18,13 @@ import {
|
|
|
13
18
|
type HostChatSetup,
|
|
14
19
|
type ModeSwitch,
|
|
15
20
|
type ModelRequest,
|
|
21
|
+
type SessionOpening,
|
|
16
22
|
} from "@mmon-co/ncept-local";
|
|
23
|
+
import { ADOPT_SESSION, BEGIN_SESSION, OPEN_SESSION, type BeginSession, type OpenSession } from "./events.js";
|
|
17
24
|
|
|
18
25
|
const { version }: { version: string } = createRequire(import.meta.url)("../package.json");
|
|
19
26
|
const STATE = "ncept.session";
|
|
20
|
-
type Selection =
|
|
27
|
+
type Selection = SessionOpening;
|
|
21
28
|
|
|
22
29
|
function storedSession(ctx: ExtensionContext): string | undefined {
|
|
23
30
|
const saved = ctx.sessionManager
|
|
@@ -27,6 +34,36 @@ function storedSession(ctx: ExtensionContext): string | undefined {
|
|
|
27
34
|
return "id" in saved.data && typeof saved.data.id === "string" ? saved.data.id : undefined;
|
|
28
35
|
}
|
|
29
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
|
+
|
|
30
67
|
/** One extension instance belongs to one pi session, including after /resume. */
|
|
31
68
|
export default function ncept(pi: ExtensionAPI) {
|
|
32
69
|
let host: Host | undefined;
|
|
@@ -34,9 +71,12 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
34
71
|
let context: ExtensionContext;
|
|
35
72
|
let mounted: HostChatSetup | undefined;
|
|
36
73
|
let transition: ModeSwitch | undefined;
|
|
74
|
+
let pendingEnter: ((ctx: ExtensionCommandContext) => Promise<void>) | undefined;
|
|
37
75
|
const ownTools = new Set<string>();
|
|
38
76
|
const graded = new Set<string>();
|
|
39
77
|
let gradeReply = false;
|
|
78
|
+
let relayingContinuation = false;
|
|
79
|
+
let promptOptions: BuildSystemPromptOptions | undefined;
|
|
40
80
|
let importConfirmed = false;
|
|
41
81
|
|
|
42
82
|
async function model(request: ModelRequest): Promise<unknown> {
|
|
@@ -159,20 +199,19 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
159
199
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
|
|
160
200
|
throw error;
|
|
161
201
|
}
|
|
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
202
|
const entries = ctx.sessionManager.getEntries();
|
|
167
203
|
const leaf = ctx.sessionManager.getLeafEntry();
|
|
168
204
|
// The local host follows the last entry's branch, including after /tree.
|
|
169
205
|
const selected = leaf ? [...entries.filter((entry) => entry.id !== leaf.id), leaf] : entries;
|
|
170
206
|
const source = [header, ...selected].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
|
|
171
207
|
parsePiSession(source);
|
|
172
|
-
await mkdir(dirname(file), { recursive: true });
|
|
173
208
|
// Pi owns file creation. Refresh only a file it has persisted, preserving
|
|
174
209
|
// the selected /tree branch for the host without racing its exclusive create.
|
|
175
|
-
|
|
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);
|
|
176
215
|
await host.profile.registerSession(active.surface, basename(file), { trusted: ctx.isProjectTrusted() });
|
|
177
216
|
}
|
|
178
217
|
|
|
@@ -180,7 +219,7 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
180
219
|
if (ownTools.has(name)) return !!mounted?.tools.some((tool) => tool.name === name);
|
|
181
220
|
if (
|
|
182
221
|
mounted?.capabilities.includes("bash") &&
|
|
183
|
-
["bash", "powershell", "edit", "write", "grep", "find", "ls"].includes(name)
|
|
222
|
+
["bash", "powershell", "edit", "write", "grep", "find", "ls", "codemode"].includes(name)
|
|
184
223
|
)
|
|
185
224
|
return true;
|
|
186
225
|
return !!mounted?.capabilities.includes("web") && /web|search|browse|fetch/i.test(name + " " + description);
|
|
@@ -258,8 +297,14 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
258
297
|
};
|
|
259
298
|
await prepare(toolCtx);
|
|
260
299
|
} else if (result.switch) {
|
|
261
|
-
|
|
262
|
-
toolCtx
|
|
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
|
+
};
|
|
263
308
|
}
|
|
264
309
|
return { content: [{ type: "text", text: JSON.stringify(result.content ?? null) }], details: result };
|
|
265
310
|
},
|
|
@@ -304,7 +349,7 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
304
349
|
}
|
|
305
350
|
|
|
306
351
|
async function enter(
|
|
307
|
-
ctx: ExtensionCommandContext,
|
|
352
|
+
ctx: ExtensionContext & Partial<Pick<ExtensionCommandContext, "newSession">>,
|
|
308
353
|
selection: Selection,
|
|
309
354
|
kickoff?: string,
|
|
310
355
|
carry?: string,
|
|
@@ -314,8 +359,8 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
314
359
|
const old = active;
|
|
315
360
|
const empty = !ctx.sessionManager.getBranch().some((entry) => entry.type === "message");
|
|
316
361
|
await sync(ctx);
|
|
317
|
-
//
|
|
318
|
-
if (old && !aside) await h.sessions.close(old);
|
|
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);
|
|
319
364
|
const opened = await h.sessions.open(selection);
|
|
320
365
|
if (empty) {
|
|
321
366
|
active = opened;
|
|
@@ -325,38 +370,119 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
325
370
|
if (kickoff) pi.sendUserMessage(kickoff);
|
|
326
371
|
return;
|
|
327
372
|
}
|
|
328
|
-
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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;
|
|
337
384
|
},
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
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
|
+
}
|
|
343
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;
|
|
344
424
|
}
|
|
345
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
|
+
});
|
|
346
444
|
pi.on("session_start", async (_event, ctx) => {
|
|
347
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
|
+
}
|
|
348
454
|
});
|
|
349
455
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
350
456
|
ctx.ui.setWidget("ncept", undefined);
|
|
457
|
+
relayingContinuation = event.messageType === "custom" && event.message.customType === "ncept.continuation";
|
|
351
458
|
gradeReply = event.messageType === "user";
|
|
352
|
-
const setup = await prepare(ctx);
|
|
459
|
+
const setup = relayingContinuation ? undefined : await prepare(ctx);
|
|
460
|
+
if (relayingContinuation) pi.setActiveTools([]);
|
|
353
461
|
event.systemPromptOptions.contextFiles = [];
|
|
354
462
|
event.systemPromptOptions.skills = [];
|
|
355
463
|
event.systemPromptOptions.appendSystemPrompt = "";
|
|
356
|
-
event.systemPromptOptions
|
|
464
|
+
promptOptions = event.systemPromptOptions;
|
|
465
|
+
event.systemPromptOptions.customPrompt = setup ? prompt(setup) : "Return the host's continuation to the learner.";
|
|
357
466
|
event.systemPromptOptions.sections = {};
|
|
358
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
|
+
});
|
|
359
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
|
+
};
|
|
360
486
|
// before_agent_start precedes persistence of the starting user message. Grade
|
|
361
487
|
// only once pi has assigned its real entry id, before the provider sees it.
|
|
362
488
|
const learner = ctx.sessionManager
|
|
@@ -397,70 +523,80 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
397
523
|
await sync(ctx);
|
|
398
524
|
if (event.reason === "quit") await host.sessions.close(active);
|
|
399
525
|
});
|
|
400
|
-
pi.on("agent_settled", (_event, ctx) => {
|
|
401
|
-
|
|
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 });
|
|
402
530
|
else if (active) ctx.ui.setStatus("ncept", active.mode);
|
|
403
531
|
});
|
|
404
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
|
+
}
|
|
405
587
|
pi.registerCommand("ncept-next", {
|
|
406
588
|
description: "Continue a tutor-requested Session switch",
|
|
407
589
|
handler: async (_args, ctx) => {
|
|
408
|
-
if (
|
|
590
|
+
if (pendingEnter) {
|
|
591
|
+
const finish = pendingEnter;
|
|
592
|
+
pendingEnter = undefined;
|
|
593
|
+
await finish(ctx);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (!transition || transition.then === "here") return;
|
|
409
597
|
const to = transition;
|
|
410
598
|
transition = undefined;
|
|
411
|
-
|
|
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");
|
|
599
|
+
await enter(ctx, to, "Continue.", await carryFor(ctx, to), to.then === "aside");
|
|
464
600
|
},
|
|
465
601
|
});
|
|
466
602
|
pi.registerCommand("learn", {
|
|
@@ -491,6 +627,43 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
491
627
|
else await enter(ctx, { mode: "charting", entry: { kind: "goal", text: args.trim() } }, args.trim());
|
|
492
628
|
},
|
|
493
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
|
+
});
|
|
494
667
|
pi.registerCommand("review", {
|
|
495
668
|
description: "Review what is due",
|
|
496
669
|
handler: async (_args, ctx) => {
|
|
@@ -504,12 +677,13 @@ export default function ncept(pi: ExtensionAPI) {
|
|
|
504
677
|
});
|
|
505
678
|
pi.registerCommand("author", {
|
|
506
679
|
description: "Author a learning map and Materials",
|
|
507
|
-
handler: async (args, ctx) =>
|
|
508
|
-
enter(
|
|
680
|
+
handler: async (args, ctx) => {
|
|
681
|
+
await enter(
|
|
509
682
|
ctx,
|
|
510
683
|
{ mode: "authoring", ...(args.trim() ? { entry: { kind: "goal", text: args.trim() } as const } : {}) },
|
|
511
684
|
args.trim() || "Let's author a learning map.",
|
|
512
|
-
)
|
|
685
|
+
);
|
|
686
|
+
},
|
|
513
687
|
});
|
|
514
688
|
pi.registerCommand("missions", {
|
|
515
689
|
description: "Show Missions and next stops",
|
package/src/init.ts
CHANGED
|
@@ -10,7 +10,8 @@ export async function initProject(directory: string): Promise<string> {
|
|
|
10
10
|
await mkdir(join(dir, ".pi"), { recursive: true });
|
|
11
11
|
await writeFile(
|
|
12
12
|
join(dir, ".pi/settings.json"),
|
|
13
|
-
JSON.stringify({ packages: ["npm:@mmon-co/ncept-pi"], sessionDir: "sessions" }, null, 2) +
|
|
13
|
+
JSON.stringify({ packages: ["npm:@mmon-co/ncept-pi"], sessionDir: "sessions", codemode: { mode: "on" } }, null, 2) +
|
|
14
|
+
"\n",
|
|
14
15
|
{ flag: "wx" },
|
|
15
16
|
);
|
|
16
17
|
await writeFile(join(dir, ".pi/SYSTEM.md"), tutorSystemPrompt("empty") + "\n", { flag: "wx" });
|