@mmon-co/ncept-bb 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/src/server.ts ADDED
@@ -0,0 +1,447 @@
1
+ import { basename } from "node:path";
2
+ import { cliCommand, defineCli, type BbPluginApi } from "@get-bb/plugin-sdk";
3
+ import { hostContract, rpcContract } from "./contract";
4
+ import { entrySchema } from "./entries";
5
+ import { stateName } from "./reading";
6
+
7
+ export default function ncept(bb: BbPluginApi) {
8
+ const host = bb.hosts.experimental_client({ contract: hostContract });
9
+
10
+ bb.events.on("thread.idle", () => bb.rpc.experimental_invalidate(["learning"]));
11
+
12
+ async function carried(threadId: string) {
13
+ const metadata = await bb.sdk.threads.getPluginMetadata({ threadId });
14
+ if (typeof metadata.carry === "string") return metadata.carry;
15
+ if (typeof metadata.carryRef === "string") return (await bb.storage.kv.get<string>(metadata.carryRef)) ?? "";
16
+ return "";
17
+ }
18
+
19
+ async function profile(projectId: string) {
20
+ const project = await bb.sdk.projects.get({ projectId });
21
+ const source = project.sources.find((item) => item.isDefault) ?? project.sources[0];
22
+ if (!source) throw new Error("The learn project has no Profile source");
23
+ return { directory: source.path, hostId: source.hostId };
24
+ }
25
+
26
+ async function association(projectId: string, session: string) {
27
+ const target = await profile(projectId);
28
+ const key = "session:" + JSON.stringify([target.hostId, target.directory, session]);
29
+ const saved = await bb.storage.kv.get<string>(key);
30
+ // A deleted thread leaves a stale entry; fall through to the scan.
31
+ if (
32
+ saved &&
33
+ (await bb.sdk.threads.get({ threadId: saved }).then(
34
+ () => true,
35
+ () => false,
36
+ ))
37
+ )
38
+ return saved;
39
+ // Includes pre-panel handoffs, whose metadata already names the Session.
40
+ for (const archived of [false, true]) {
41
+ for (let offset = 0; ; offset += 200) {
42
+ const threads = await bb.sdk.threads.list({ projectId, archived, includeHidden: true, limit: 200, offset });
43
+ if (!threads.length) break;
44
+ const metadata = await bb.sdk.threads.experimental_listPluginMetadata({
45
+ threadIds: threads.map((item) => item.id),
46
+ });
47
+ for (const item of metadata.threads) {
48
+ if (item.metadata.session !== session) continue;
49
+ const thread = threads.find((thread) => thread.id === item.threadId);
50
+ if (!thread?.environmentId) continue;
51
+ const environment = await bb.sdk.environments.get({ environmentId: thread.environmentId });
52
+ if (environment.hostId !== target.hostId || environment.path !== target.directory) continue;
53
+ await bb.storage.kv.set(key, thread.id);
54
+ return thread.id;
55
+ }
56
+ if (threads.length < 200) break;
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+
62
+ async function remember(projectId: string, session: string, threadId: string) {
63
+ const target = await profile(projectId);
64
+ await bb.storage.kv.set("session:" + JSON.stringify([target.hostId, target.directory, session]), threadId);
65
+ }
66
+
67
+ // Map parts as composer pills. An id is the project, the kind and the part's own ids, "~"-joined; the tutor
68
+ // receives what `resolve` returns when the message is sent.
69
+ async function learnMap(projectId: string) {
70
+ const target = await profile(projectId);
71
+ if (!(await host.call("recognize", { directory: target.directory }, { hostId: target.hostId }))) return null;
72
+ return host.call("map", { directory: target.directory }, { hostId: target.hostId });
73
+ }
74
+ bb.ui.registerMentionProvider({
75
+ id: "map",
76
+ label: "Map",
77
+ async search({ query, projectId }) {
78
+ const map = projectId ? await learnMap(projectId).catch(() => null) : null;
79
+ if (!map) return [];
80
+ const matches = (text: string) => text.toLowerCase().includes(query.toLowerCase());
81
+ return [
82
+ ...map.nodes
83
+ .filter((node) => matches(node.label))
84
+ .map((node) => ({
85
+ id: [projectId, "node", node.id].join("~"),
86
+ title: node.label,
87
+ subtitle: "Node · " + stateName(node),
88
+ })),
89
+ ...map.missions
90
+ .filter((mission) => matches(mission.statement))
91
+ .map((mission) => ({
92
+ id: [projectId, "mission", mission.id].join("~"),
93
+ title: mission.statement,
94
+ subtitle: "Mission",
95
+ })),
96
+ ].slice(0, 20);
97
+ },
98
+ async resolve(itemId) {
99
+ const [projectId = "", kind, id = "", to = ""] = itemId.split("~");
100
+ const map = await learnMap(projectId);
101
+ if (!map) throw new Error("That Profile is no longer a learn project");
102
+ const node = (id: string) => map.nodes.find((item) => item.id === id);
103
+ const name = (id: string) => JSON.stringify(node(id)?.label ?? id) + " (" + id + ")";
104
+ const list = (ids: readonly string[]) => ids.map(name).join(", ") || "nothing";
105
+ if (kind === "mission") {
106
+ const mission = map.missions.find((item) => item.id === id);
107
+ if (!mission) throw new Error("That Mission is no longer in the Profile");
108
+ return {
109
+ context:
110
+ "Mission " +
111
+ JSON.stringify(mission.statement) +
112
+ " (id " +
113
+ mission.id +
114
+ "). Its Nodes: " +
115
+ list(mission.cone) +
116
+ ".",
117
+ };
118
+ }
119
+ if (kind === "edge") {
120
+ if (!map.edges.some((edge) => edge.from === id && edge.to === to))
121
+ throw new Error("That Edge is no longer in the graph");
122
+ return { context: "Edge: " + name(id) + " is needed for " + name(to) + "." };
123
+ }
124
+ const found = node(id);
125
+ if (!found) throw new Error("That Node is no longer in the graph");
126
+ return {
127
+ context:
128
+ "Node " +
129
+ JSON.stringify(found.label) +
130
+ " (id " +
131
+ found.id +
132
+ ", " +
133
+ stateName(found) +
134
+ "). Needs: " +
135
+ list(map.edges.filter((edge) => edge.to === id).map((edge) => edge.from)) +
136
+ ". Unlocks: " +
137
+ list(map.edges.filter((edge) => edge.from === id).map((edge) => edge.to)) +
138
+ ".",
139
+ };
140
+ },
141
+ });
142
+
143
+ bb.rpc.register(rpcContract, {
144
+ profiles: async () => {
145
+ // One host lookup per machine and all projects probed together: the badge polls this.
146
+ const connected = new Map<string, Promise<boolean>>();
147
+ const found = await Promise.all(
148
+ (await bb.sdk.projects.list()).map(async (project) => {
149
+ const source = project.sources.find((item) => item.isDefault) ?? project.sources[0];
150
+ if (!source) return [];
151
+ let ready = connected.get(source.hostId);
152
+ if (!ready) {
153
+ ready = bb.sdk.hosts.get({ hostId: source.hostId }).then((item) => item.status === "connected");
154
+ connected.set(source.hostId, ready);
155
+ }
156
+ if (!(await ready)) return [];
157
+ if (!(await host.call("recognize", { directory: source.path }, { hostId: source.hostId }))) return [];
158
+ return [{ projectId: project.id, name: project.name, directory: source.path, hostId: source.hostId }];
159
+ }),
160
+ );
161
+ return found.flat();
162
+ },
163
+ reading: async ({ projectId }) => {
164
+ const target = await profile(projectId);
165
+ const reading = await host.call("reading", { directory: target.directory }, { hostId: target.hostId });
166
+ return {
167
+ ...reading,
168
+ sessions: await Promise.all(
169
+ reading.sessions.map(async (session) => ({ ...session, threadId: await association(projectId, session.id) })),
170
+ ),
171
+ };
172
+ },
173
+ threadProject: async ({ threadId }) => {
174
+ const thread = await bb.sdk.threads.get({ threadId });
175
+ const target = await profile(thread.projectId).catch(() => null);
176
+ const learn =
177
+ target && (await host.call("recognize", { directory: target.directory }, { hostId: target.hostId }));
178
+ return learn ? thread.projectId : null;
179
+ },
180
+ map: async ({ projectId, missionId }) => {
181
+ const target = await profile(projectId);
182
+ return host.call("map", { directory: target.directory, missionId }, { hostId: target.hostId });
183
+ },
184
+ retire: async ({ projectId, missionId, outcome }) => {
185
+ const target = await profile(projectId);
186
+ return host.call("retire", { directory: target.directory, missionId, outcome }, { hostId: target.hostId });
187
+ },
188
+ share: async ({ projectId, missionId, title }) => {
189
+ const target = await profile(projectId);
190
+ return host.call("share", { directory: target.directory, missionId, title }, { hostId: target.hostId });
191
+ },
192
+ mission: async ({ projectId, missionId }) => {
193
+ const target = await profile(projectId);
194
+ return host.call("mission", { directory: target.directory, missionId }, { hostId: target.hostId });
195
+ },
196
+ context: async ({ threadId }) => {
197
+ const thread = await bb.sdk.threads.get({ threadId });
198
+ const metadata = await bb.sdk.threads.getPluginMetadata({ threadId });
199
+ if (typeof metadata.session !== "string" || !thread.projectId) return null;
200
+ const target = await profile(thread.projectId);
201
+ const reading = await host.call("reading", { directory: target.directory }, { hostId: target.hostId });
202
+ return reading.sessions.find((session) => session.id === metadata.session) ?? null;
203
+ },
204
+ thread: async ({ projectId, session }) => ({ threadId: await association(projectId, session) }),
205
+ open: async ({ projectId, intent }) => {
206
+ const target = await profile(projectId);
207
+ const entry = await host.call("entry", { directory: target.directory, intent }, { hostId: target.hostId });
208
+ if (entry.resume) {
209
+ const threadId = await association(projectId, entry.resume);
210
+ if (threadId) return { threadId, title: (await bb.sdk.threads.get({ threadId })).title ?? entry.title };
211
+ }
212
+ const environments = await bb.sdk.environments.list({ projectId, hostId: target.hostId, path: target.directory });
213
+ const environment = environments.find((item) => item.path === target.directory);
214
+ const execution = await bb.sdk.projects.defaultExecutionOptions({ projectId });
215
+ const prompt =
216
+ intent.kind === "tell-tutor"
217
+ ? intent.request
218
+ : intent.kind === "new-mission"
219
+ ? "/ncept-kickoff Chart a new Mission."
220
+ : intent.kind === "review"
221
+ ? "/ncept-kickoff Begin the Review."
222
+ : intent.kind === "revise-lesson"
223
+ ? "/ncept-kickoff Rework this Lesson; the learner requested a different approach."
224
+ : intent.kind === "revise-route"
225
+ ? "/ncept-kickoff Revise the route for this Mission."
226
+ : intent.kind === "skip-lesson" || intent.kind === "skip-to"
227
+ ? "/ncept-kickoff Continue from the stop the learner skipped to."
228
+ : "/ncept-kickoff Continue this Mission.";
229
+ const next = await bb.sdk.threads.spawn({
230
+ projectId,
231
+ environment: environment
232
+ ? { type: "reuse", environmentId: environment.id }
233
+ : { type: "host", hostId: target.hostId, workspace: { type: "unmanaged", path: target.directory } },
234
+ providerId: "pi",
235
+ ...(execution?.providerId === "pi"
236
+ ? {
237
+ model: execution.model,
238
+ reasoningLevel: execution.reasoningLevel,
239
+ serviceTier: execution.serviceTier,
240
+ permissionMode: execution.permissionMode,
241
+ }
242
+ : {}),
243
+ input: [
244
+ {
245
+ type: "text",
246
+ mentions: [],
247
+ text: prompt,
248
+ ...(intent.kind === "tell-tutor" ? {} : { visibility: "agent-only" as const }),
249
+ },
250
+ ],
251
+ title: entry.title.slice(0, 200),
252
+ pluginMetadata: entry.resume ? { session: entry.resume } : { intent },
253
+ });
254
+ if (entry.resume) await remember(projectId, entry.resume, next.id);
255
+ return { threadId: next.id, title: entry.title.slice(0, 200) };
256
+ },
257
+ });
258
+
259
+ bb.providers.experimental_contributeEnv("pi", async ({ threadId }) => {
260
+ if (!threadId) return [];
261
+ const metadata = await bb.sdk.threads.getPluginMetadata({ threadId });
262
+ // Keep contributions stable after association: a changed provider environment
263
+ // makes bb replace pi, racing the outgoing process\'s Session close with resume.
264
+ if (metadata.localSession === true) return [];
265
+ if (metadata.intent) {
266
+ const entry = entrySchema.safeParse(metadata.intent);
267
+ return entry.success
268
+ ? [
269
+ {
270
+ name: "NCEPT_BB_ENTRY",
271
+ value: JSON.stringify(entry.data),
272
+ reason: "Open the requested tutoring Session entry",
273
+ },
274
+ ]
275
+ : [];
276
+ }
277
+ if (typeof metadata.session !== "string") return [];
278
+ const entries = [
279
+ { name: "NCEPT_BB_SESSION", value: metadata.session, reason: "Adopt this thread's tutoring Session" },
280
+ ];
281
+ if (typeof metadata.carryRef === "string")
282
+ entries.push({
283
+ name: "NCEPT_BB_CARRY_REF",
284
+ value: threadId,
285
+ reason: "Fetch the full Session carry through bb concept carry",
286
+ });
287
+ else if (typeof metadata.carry === "string")
288
+ entries.push({ name: "NCEPT_BB_CARRY", value: metadata.carry, reason: "Carry context to the next tutor" });
289
+ return entries;
290
+ });
291
+
292
+ bb.cli.register(
293
+ defineCli({
294
+ name: "concept",
295
+ summary: "Learn in bb from a local Common Concept Profile",
296
+ commands: {
297
+ init: cliCommand({
298
+ summary: "Create a Profile, trust its pi extensions, and create its bb project",
299
+ positionals: [{ name: "dir", description: "Profile directory on the selected machine (default ~/learn)" }],
300
+ options: {
301
+ machine: {
302
+ type: "string",
303
+ description: "Machine ID or name; defaults to this thread's machine, otherwise the server",
304
+ },
305
+ source: {
306
+ type: "string",
307
+ description: "Unpublished packages/bb directory on that machine (uses sibling packages/pi too)",
308
+ },
309
+ name: { type: "string", description: "bb project name (default: directory name)" },
310
+ },
311
+ async run(input, ctx) {
312
+ let hostId: string | null | undefined;
313
+ if (input.options.machine) {
314
+ const machines = await bb.sdk.hosts.list();
315
+ const matches = machines.filter(
316
+ (machine) => machine.id === input.options.machine || machine.name === input.options.machine,
317
+ );
318
+ const machine = matches[0];
319
+ if (!machine || matches.length !== 1)
320
+ throw new Error("Choose an unambiguous connected machine ID or name.");
321
+ hostId = machine.id;
322
+ } else if (ctx.threadId) {
323
+ const thread = await bb.sdk.threads.get({ threadId: ctx.threadId });
324
+ if (thread.environmentId)
325
+ hostId = (await bb.sdk.environments.get({ environmentId: thread.environmentId })).hostId;
326
+ } else {
327
+ hostId = (await bb.sdk.system.config()).primaryHostId;
328
+ }
329
+ if (!hostId) throw new Error("No machine selected. Add --machine <id>.");
330
+ const { directory } = await host.call(
331
+ "init",
332
+ {
333
+ directory: input.positionals.dir ?? "~/learn",
334
+ ...(input.options.source ? { source: input.options.source } : {}),
335
+ },
336
+ { hostId, signal: ctx.signal },
337
+ );
338
+ const project = await bb.sdk.projects.create({
339
+ name: input.options.name ?? basename(directory),
340
+ source: { type: "local_path", hostId, path: directory },
341
+ });
342
+ return { exitCode: 0, stdout: JSON.stringify({ projectId: project.id, hostId, directory }) };
343
+ },
344
+ }),
345
+ spawn: cliCommand({
346
+ summary: "Open an already-created tutoring Session in this thread's project and environment",
347
+ options: {
348
+ "request-file": {
349
+ type: "string",
350
+ required: true,
351
+ description: "Absolute host-local JSON handoff file (carry limited to 4 MiB)",
352
+ },
353
+ },
354
+ async run(input, ctx) {
355
+ if (!ctx.threadId) throw new Error("Run from a bb thread (BB_THREAD_ID is required).");
356
+ const previous = await bb.sdk.threads.get({ threadId: ctx.threadId });
357
+ if (!previous.environmentId) throw new Error("The tutoring thread has no environment.");
358
+ const environment = await bb.sdk.environments.get({ environmentId: previous.environmentId });
359
+ if (!environment.path) throw new Error("The tutoring environment has no Profile path.");
360
+ const request = await host.call(
361
+ "handoff",
362
+ {
363
+ directory: environment.path,
364
+ requestFile: input.options["request-file"],
365
+ },
366
+ { hostId: environment.hostId, signal: ctx.signal },
367
+ );
368
+ // Keep metadata and the provider environment comfortably below both bb's
369
+ // 256 KiB namespace and the OS's per-environment-variable limit.
370
+ const carryRef =
371
+ request.carry && Buffer.byteLength(request.carry, "utf8") > 24 * 1024
372
+ ? "carry:" + request.session
373
+ : undefined;
374
+ if (carryRef) await bb.storage.kv.set(carryRef, request.carry);
375
+ const execution = await bb.sdk.threads.defaultExecutionOptions({ threadId: previous.id });
376
+ const next = await bb.sdk.threads.spawn({
377
+ projectId: previous.projectId,
378
+ environment: { type: "reuse", environmentId: previous.environmentId },
379
+ providerId: "pi",
380
+ ...(execution
381
+ ? {
382
+ model: execution.model,
383
+ reasoningLevel: execution.reasoningLevel,
384
+ serviceTier: execution.serviceTier,
385
+ permissionMode: execution.permissionMode,
386
+ }
387
+ : {}),
388
+ input: [
389
+ {
390
+ type: "text",
391
+ mentions: [],
392
+ text: request.learnerKickoff
393
+ ? (request.kickoff ?? "")
394
+ : "/ncept-kickoff " + (request.kickoff || "Continue."),
395
+ ...(request.learnerKickoff ? {} : { visibility: "agent-only" as const }),
396
+ },
397
+ ],
398
+ title: request.title,
399
+ ...(request.aside ? { parentThreadId: previous.id, parentNotifications: "off" as const } : {}),
400
+ pluginMetadata: {
401
+ session: request.session,
402
+ ...(carryRef ? { carryRef } : request.carry ? { carry: request.carry } : {}),
403
+ },
404
+ });
405
+ await remember(previous.projectId, request.session, next.id);
406
+ return { exitCode: 0, stdout: JSON.stringify({ threadId: next.id, title: request.title }) };
407
+ },
408
+ }),
409
+ associate: cliCommand({
410
+ summary: "Associate this tutoring thread with its pi-owned Session",
411
+ options: { session: { type: "string", required: true, description: "The Session recorded by ncept-pi" } },
412
+ async run(input, ctx) {
413
+ if (!ctx.threadId) throw new Error("Run from a bb thread");
414
+ const thread = await bb.sdk.threads.get({ threadId: ctx.threadId });
415
+ if (!thread.environmentId) throw new Error("The thread has no Profile environment");
416
+ const environment = await bb.sdk.environments.get({ environmentId: thread.environmentId });
417
+ const target = await profile(thread.projectId);
418
+ if (environment.hostId !== target.hostId || environment.path !== target.directory)
419
+ throw new Error("The thread is not in its learn project's Profile environment");
420
+ const description = await host.call(
421
+ "session",
422
+ { directory: target.directory, session: input.options.session },
423
+ { hostId: target.hostId, signal: ctx.signal },
424
+ );
425
+ const metadata = await bb.sdk.threads.getPluginMetadata({ threadId: thread.id });
426
+ await bb.sdk.threads.updatePluginMetadata({
427
+ threadId: thread.id,
428
+ set: { ...description, ...(!metadata.intent && !metadata.session ? { localSession: true } : {}) },
429
+ });
430
+ if (metadata.intent) await bb.sdk.threads.update({ threadId: thread.id, title: description.title });
431
+ await remember(thread.projectId, description.session, thread.id);
432
+ return { exitCode: 0, stdout: JSON.stringify(description) };
433
+ },
434
+ }),
435
+ carry: cliCommand({
436
+ summary: "Read a thread's hidden tutoring carry (for the pi extension)",
437
+ options: {
438
+ thread: { type: "string", required: true, description: "Thread ID supplied by NCEPT_BB_CARRY_REF" },
439
+ },
440
+ async run(input) {
441
+ return { exitCode: 0, stdout: JSON.stringify({ carry: await carried(input.options.thread) }) };
442
+ },
443
+ }),
444
+ },
445
+ }),
446
+ );
447
+ }
@@ -0,0 +1,26 @@
1
+ import type { ButtonHTMLAttributes } from "react";
2
+
3
+ // BB's vendored button recipe (bb plugin new, BB 0.48.1), limited to the
4
+ // variants used by Learn. No Slot or variant-merging dependency is needed.
5
+ export function Button({
6
+ variant = "default",
7
+ className = "",
8
+ ...props
9
+ }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: "default" | "outline" | "ghost" }) {
10
+ const variants = {
11
+ default: "bg-foreground text-background hover:bg-foreground/90",
12
+ outline: "border border-input bg-transparent hover:bg-state-hover hover:text-foreground",
13
+ ghost: "hover:bg-state-hover hover:text-foreground",
14
+ };
15
+ return (
16
+ <button
17
+ {...props}
18
+ className={
19
+ "inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 h-8 px-3 " +
20
+ variants[variant] +
21
+ " " +
22
+ className
23
+ }
24
+ />
25
+ );
26
+ }