@mmon-co/ncept-local 0.2.0 → 0.3.1
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 +1 -1
- package/README.md +1 -1
- package/dist/directory.d.ts +2 -1
- package/dist/directory.js +9 -1
- package/dist/host-tools.js +1 -1
- package/dist/host.d.ts +18 -1
- package/dist/hub-auth.d.ts +15 -0
- package/dist/hub-auth.js +97 -3
- package/dist/hub.d.ts +11 -1
- package/dist/hub.js +170 -52
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/learning.d.ts +13 -3
- package/dist/learning.js +91 -20
- package/dist/runtime.d.ts +2 -0
- package/dist/runtime.js +1 -0
- package/package.json +3 -3
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -68,7 +68,7 @@ Pull verifies the closed bundle and all attachment digests before adopting its r
|
|
|
68
68
|
|
|
69
69
|
`openHost({ ..., hub: { url, clientMetadataUrl, credentialsFile, openUrl } })` optionally overrides the Application base URL (default `https://co.mmon.co/ncept`), credential file (default `credentialsPath()`) and browser opening. For issuers using CIMD rather than dynamic registration, supply the front end's public native-client metadata document as `clientMetadataUrl` (the pi package uses pi's published identity). Front ends running remotely can present the authorization URL themselves through `openUrl`; the browser must be able to reach the host machine’s loopback callback. HTTP is allowed only for loopback development URLs.
|
|
70
70
|
|
|
71
|
-
Confirmation proposals distinguish `hub.publish`, `hub.export
|
|
71
|
+
Confirmation proposals distinguish `hub.publish`, `hub.export` and `hub.import`. Declining the final replacement leaves the live Profile unchanged. Import from web validates the archive before confirmation and stages it before replacement, retains the entire previous project directory as `<profileDir>.backup-<uuid>`, and relocates transcripts to the final directory. Reopen any active Session after replacing the Profile; unrelated old project files and Material working copies remain in the backup, not in the replacement.
|
|
72
72
|
|
|
73
73
|
## First use from this repository
|
|
74
74
|
|
package/dist/directory.d.ts
CHANGED
|
@@ -13,7 +13,8 @@ export interface ProfileDirectory {
|
|
|
13
13
|
readonly dir: string;
|
|
14
14
|
read(): Promise<ValidatedProfile>;
|
|
15
15
|
files(): Promise<ProfileFiles>;
|
|
16
|
-
|
|
16
|
+
/** A conditional append checks the current Profile while holding its write lock. */
|
|
17
|
+
appendLog(entries: readonly ProfileLogEntry[], accept?: (current: ValidatedProfile) => boolean): Promise<void>;
|
|
17
18
|
addRevision(identity: PatchId, content: PatchContent): Promise<ExactPatchRef>;
|
|
18
19
|
setPersonal(ref: ExactPatchRef): Promise<void>;
|
|
19
20
|
configure(options: InitOptions): Promise<void>;
|
package/dist/directory.js
CHANGED
|
@@ -163,6 +163,12 @@ export async function openProfile(dir, theories, options = {}) {
|
|
|
163
163
|
const files = await filesAt(dir);
|
|
164
164
|
const manifest = { ...parseManifest(files.get("profile.json")), ...change };
|
|
165
165
|
files.set("profile.json", jsonBytes(manifest));
|
|
166
|
+
// A surface re-registered to another file (bb's edit-message rewinds onto a fresh pi session)
|
|
167
|
+
// leaves its previous transcript on disk, outside the exchange.
|
|
168
|
+
const kept = new Set(Object.values(manifest.sessions).map((filename) => "sessions/" + filename));
|
|
169
|
+
for (const path of files.keys())
|
|
170
|
+
if (path.startsWith("sessions/") && !kept.has(path))
|
|
171
|
+
files.delete(path);
|
|
166
172
|
for (const filename of Object.values(manifest.sessions)) {
|
|
167
173
|
const path = "sessions/" + filename;
|
|
168
174
|
if (!files.has(path))
|
|
@@ -188,8 +194,10 @@ export async function openProfile(dir, theories, options = {}) {
|
|
|
188
194
|
dir,
|
|
189
195
|
read,
|
|
190
196
|
files: () => filesAt(dir),
|
|
191
|
-
appendLog: (entries) => serial(async () => {
|
|
197
|
+
appendLog: (entries, accept) => serial(async () => {
|
|
192
198
|
const current = await read();
|
|
199
|
+
if (accept && !accept(current))
|
|
200
|
+
return;
|
|
193
201
|
const bytes = logBytes(mergeProfileLogs(current.log, entries));
|
|
194
202
|
const manifest = { ...current.manifest, log: attachmentDigest(bytes) };
|
|
195
203
|
await immutable(dir, liveLogPath(manifest), bytes);
|
package/dist/host-tools.js
CHANGED
|
@@ -89,7 +89,7 @@ export function hostTools(host, opened, capabilities, skills, metadataKeys) {
|
|
|
89
89
|
schema: definition,
|
|
90
90
|
run: (raw) => host.serial(async () => {
|
|
91
91
|
const session = await host.current(opened);
|
|
92
|
-
if (session.closed || session.mode !== opened.mode)
|
|
92
|
+
if (session.closed || session.closing || session.mode !== opened.mode)
|
|
93
93
|
throw new Error("Tool belongs to an inactive Session mode");
|
|
94
94
|
const result = await run(args(raw), session);
|
|
95
95
|
if (!object(result.content) || result.content.status !== "refused") {
|
package/dist/host.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export interface Proposal {
|
|
|
12
12
|
readonly title: string;
|
|
13
13
|
readonly description: string;
|
|
14
14
|
readonly detail: unknown;
|
|
15
|
+
readonly defaultAccepted?: boolean;
|
|
15
16
|
}
|
|
16
17
|
export type Confirm = (proposal: Proposal) => Promise<boolean>;
|
|
17
18
|
export type ModeSwitch = ModeSwitchDefault & Readonly<{
|
|
@@ -106,8 +107,12 @@ export interface Host {
|
|
|
106
107
|
turn(session: HostSession, input: Readonly<{
|
|
107
108
|
learnerMessage?: string;
|
|
108
109
|
}>): Promise<HostChatSetup>;
|
|
109
|
-
/** After the conversation stops,
|
|
110
|
+
/** After the conversation stops, end a completed Lesson and return its next surface. */
|
|
110
111
|
settle(session: HostSession): Promise<ModeSwitch | undefined>;
|
|
112
|
+
/** End admission immediately, leaving Theory judgments pending. */
|
|
113
|
+
end(session: HostSession): Promise<void>;
|
|
114
|
+
/** Finish pending Theory closes without holding up other Session operations. */
|
|
115
|
+
closePending(): Promise<void>;
|
|
111
116
|
close(session: HostSession): Promise<void>;
|
|
112
117
|
};
|
|
113
118
|
readonly missions: {
|
|
@@ -126,6 +131,16 @@ export interface Host {
|
|
|
126
131
|
title: string;
|
|
127
132
|
description?: string;
|
|
128
133
|
}>): Promise<HubRelease>;
|
|
134
|
+
/**
|
|
135
|
+
* Publish one Mission's map (its targets and their prerequisites) as a new Hub release and
|
|
136
|
+
* return its link. Unlisted unless asked otherwise; signs in first when needed.
|
|
137
|
+
*/
|
|
138
|
+
share(input: Readonly<{
|
|
139
|
+
mission: string;
|
|
140
|
+
title: string;
|
|
141
|
+
visibility?: "public" | "unlisted";
|
|
142
|
+
signIn?: false;
|
|
143
|
+
}>): Promise<HubRelease>;
|
|
129
144
|
exportTo(destination: "web"): Promise<void>;
|
|
130
145
|
importFrom(source: "web"): Promise<ImportResult>;
|
|
131
146
|
};
|
|
@@ -153,5 +168,7 @@ export interface OpenHostOptions<S> {
|
|
|
153
168
|
readonly theories: readonly Theory<S>[];
|
|
154
169
|
readonly model: Model;
|
|
155
170
|
readonly confirm: Confirm;
|
|
171
|
+
/** Receives failures from the background recovery sweep. */
|
|
172
|
+
readonly onCloseError?: (error: unknown) => void;
|
|
156
173
|
}
|
|
157
174
|
export { openHost } from "./learning.js";
|
package/dist/hub-auth.d.ts
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
import { type OAuthClientProvider, type OAuthDiscoveryState } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
2
2
|
import type { OAuthClientInformationMixed, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
3
3
|
import type { HubOptions } from "./host.js";
|
|
4
|
+
export declare function hubBaseUrl(value?: string): string;
|
|
5
|
+
export declare function hasHubCredentials(options: HubOptions): Promise<boolean>;
|
|
6
|
+
export declare function beginHubBrowserSignIn(options: HubOptions): Promise<HubBrowserSignIn>;
|
|
7
|
+
export declare class HubSignInRequired extends Error {
|
|
8
|
+
constructor();
|
|
9
|
+
}
|
|
10
|
+
export interface HubBrowserSignIn {
|
|
11
|
+
readonly url: string;
|
|
12
|
+
readonly expiresAt: number;
|
|
13
|
+
/** True once consent has been exchanged for locally stored Hub credentials. */
|
|
14
|
+
poll(): Promise<boolean>;
|
|
15
|
+
}
|
|
4
16
|
/** SDK owns discovery, issuer/resource binding, dynamic registration, PKCE and refresh. */
|
|
5
17
|
export declare class HubAuth implements OAuthClientProvider {
|
|
6
18
|
readonly resource: string;
|
|
@@ -11,6 +23,7 @@ export declare class HubAuth implements OAuthClientProvider {
|
|
|
11
23
|
private verifier?;
|
|
12
24
|
private authorize?;
|
|
13
25
|
private nonce;
|
|
26
|
+
private transient;
|
|
14
27
|
private constructor();
|
|
15
28
|
static open(resource: string, options: HubOptions): Promise<HubAuth>;
|
|
16
29
|
get redirectUrl(): string | undefined;
|
|
@@ -42,5 +55,7 @@ export declare class HubAuth implements OAuthClientProvider {
|
|
|
42
55
|
redirectToAuthorization(url: URL): Promise<void>;
|
|
43
56
|
invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
|
|
44
57
|
private save;
|
|
58
|
+
/** The browser can be on another machine. Keep the PKCE verifier and claim secret in this process. */
|
|
59
|
+
beginBrowserSignIn(): Promise<HubBrowserSignIn>;
|
|
45
60
|
signIn(): Promise<void>;
|
|
46
61
|
}
|
package/dist/hub-auth.js
CHANGED
|
@@ -1,11 +1,34 @@
|
|
|
1
1
|
import { createServer } from "node:http";
|
|
2
2
|
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
3
|
import { dirname } from "node:path";
|
|
4
|
-
import { randomBytes, randomUUID } from "node:crypto";
|
|
4
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
5
5
|
import { execFile } from "node:child_process";
|
|
6
|
-
import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
6
|
+
import { auth, UnauthorizedError, } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
7
7
|
import { credentialsPath } from "./directory.js";
|
|
8
8
|
const scopes = "patches publish learn";
|
|
9
|
+
const defaultHub = "https://co.mmon.co/ncept";
|
|
10
|
+
export function hubBaseUrl(value = defaultHub) {
|
|
11
|
+
const url = new URL(value);
|
|
12
|
+
if ((url.protocol !== "https:" &&
|
|
13
|
+
!(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) ||
|
|
14
|
+
url.username ||
|
|
15
|
+
url.password ||
|
|
16
|
+
url.search ||
|
|
17
|
+
url.hash)
|
|
18
|
+
throw new Error("Hub URL must use HTTPS (or loopback HTTP)");
|
|
19
|
+
return url.href.replace(/\/$/, "");
|
|
20
|
+
}
|
|
21
|
+
export async function hasHubCredentials(options) {
|
|
22
|
+
return Boolean((await HubAuth.open(hubBaseUrl(options.url) + "/mcp", options)).tokens());
|
|
23
|
+
}
|
|
24
|
+
export async function beginHubBrowserSignIn(options) {
|
|
25
|
+
return (await HubAuth.open(hubBaseUrl(options.url) + "/mcp", options)).beginBrowserSignIn();
|
|
26
|
+
}
|
|
27
|
+
export class HubSignInRequired extends Error {
|
|
28
|
+
constructor() {
|
|
29
|
+
super("Sign in to Common Concept first");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
9
32
|
async function load(path) {
|
|
10
33
|
try {
|
|
11
34
|
const stored = JSON.parse(await readFile(path, "utf8"));
|
|
@@ -34,6 +57,7 @@ export class HubAuth {
|
|
|
34
57
|
verifier;
|
|
35
58
|
authorize;
|
|
36
59
|
nonce = "";
|
|
60
|
+
transient = false;
|
|
37
61
|
constructor(resource, path, openUrl, clientMetadataUrl) {
|
|
38
62
|
this.resource = resource;
|
|
39
63
|
this.path = path;
|
|
@@ -96,7 +120,7 @@ export class HubAuth {
|
|
|
96
120
|
}
|
|
97
121
|
async redirectToAuthorization(url) {
|
|
98
122
|
if (!this.authorize)
|
|
99
|
-
throw new
|
|
123
|
+
throw new UnauthorizedError("Sign in to Common Concept first");
|
|
100
124
|
await this.authorize(url);
|
|
101
125
|
}
|
|
102
126
|
async invalidateCredentials(scope) {
|
|
@@ -110,12 +134,82 @@ export class HubAuth {
|
|
|
110
134
|
}
|
|
111
135
|
async save(change) {
|
|
112
136
|
this.credentials = { ...this.credentials, ...change };
|
|
137
|
+
if (this.transient)
|
|
138
|
+
return;
|
|
113
139
|
const all = { ...(await load(this.path)), [this.resource]: this.credentials };
|
|
114
140
|
await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
115
141
|
const temporary = this.path + "." + randomUUID() + ".tmp";
|
|
116
142
|
await writeFile(temporary, JSON.stringify(all) + "\n", { mode: 0o600, flag: "wx" });
|
|
117
143
|
await rename(temporary, this.path);
|
|
118
144
|
}
|
|
145
|
+
/** The browser can be on another machine. Keep the PKCE verifier and claim secret in this process. */
|
|
146
|
+
async beginBrowserSignIn() {
|
|
147
|
+
const path = this.resource.replace(/\/mcp$/, "/bb-sign-in");
|
|
148
|
+
const attempt = new HubAuth(this.resource, this.path, this.openUrl);
|
|
149
|
+
attempt.transient = true;
|
|
150
|
+
const state = (attempt.nonce = randomBytes(32).toString("base64url"));
|
|
151
|
+
const secret = randomBytes(32).toString("base64url");
|
|
152
|
+
const claimHash = createHash("sha256").update(secret).digest("hex");
|
|
153
|
+
const send = (body) => fetch(path, {
|
|
154
|
+
method: "POST",
|
|
155
|
+
headers: { "Content-Type": "application/json" },
|
|
156
|
+
body: JSON.stringify({ state, ...body }),
|
|
157
|
+
redirect: "error",
|
|
158
|
+
signal: AbortSignal.timeout(10_000),
|
|
159
|
+
});
|
|
160
|
+
const startedAt = Date.now();
|
|
161
|
+
const started = await send({ claimHash });
|
|
162
|
+
if (!started.ok)
|
|
163
|
+
throw new Error("Common Concept sign-in is unavailable");
|
|
164
|
+
const config = await started.json();
|
|
165
|
+
if (!config ||
|
|
166
|
+
typeof config !== "object" ||
|
|
167
|
+
!("clientId" in config) ||
|
|
168
|
+
typeof config.clientId !== "string" ||
|
|
169
|
+
!("redirect" in config) ||
|
|
170
|
+
config.redirect !== path ||
|
|
171
|
+
!path.startsWith("https://") ||
|
|
172
|
+
!("expiresIn" in config) ||
|
|
173
|
+
typeof config.expiresIn !== "number")
|
|
174
|
+
throw new Error("Invalid Common Concept sign-in configuration");
|
|
175
|
+
attempt.credentials = { client: { client_id: config.clientId }, redirect: config.redirect };
|
|
176
|
+
let url;
|
|
177
|
+
attempt.authorize = async (authorization) => {
|
|
178
|
+
url = authorization.href;
|
|
179
|
+
};
|
|
180
|
+
const settings = {
|
|
181
|
+
serverUrl: this.resource,
|
|
182
|
+
resourceMetadataUrl: new URL(this.resource.replace(/\/mcp$/, "/.well-known/oauth-protected-resource")),
|
|
183
|
+
scope: scopes + " offline_access",
|
|
184
|
+
fetchFn: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(10_000) }),
|
|
185
|
+
};
|
|
186
|
+
await auth(attempt, settings);
|
|
187
|
+
if (!url)
|
|
188
|
+
throw new Error("Common Concept did not open sign-in");
|
|
189
|
+
const expiresAt = startedAt + config.expiresIn;
|
|
190
|
+
return {
|
|
191
|
+
url,
|
|
192
|
+
expiresAt,
|
|
193
|
+
poll: async () => {
|
|
194
|
+
const response = await send({ secret });
|
|
195
|
+
if (response.status === 410)
|
|
196
|
+
throw new Error("Sign-in expired. Try again.");
|
|
197
|
+
if (!response.ok)
|
|
198
|
+
throw new Error("Common Concept sign-in is unavailable");
|
|
199
|
+
const result = await response.json();
|
|
200
|
+
if (!result || typeof result !== "object")
|
|
201
|
+
throw new Error("Invalid Common Concept sign-in response");
|
|
202
|
+
if (!("code" in result))
|
|
203
|
+
return false;
|
|
204
|
+
if (typeof result.code !== "string")
|
|
205
|
+
throw new Error("Sign-in declined");
|
|
206
|
+
await auth(attempt, { ...settings, authorizationCode: result.code });
|
|
207
|
+
attempt.transient = false;
|
|
208
|
+
await attempt.save({});
|
|
209
|
+
return true;
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
119
213
|
async signIn() {
|
|
120
214
|
this.nonce = randomBytes(32).toString("base64url");
|
|
121
215
|
let accept;
|
package/dist/hub.d.ts
CHANGED
|
@@ -1,4 +1,14 @@
|
|
|
1
|
+
import { type ClosedPatchBundle, type Mission } from "@mmon-co/ncept-core";
|
|
1
2
|
import { type ProfileDirectory } from "./directory.js";
|
|
2
3
|
import { type ConfiguredTheory } from "./exchange.js";
|
|
3
4
|
import type { Confirm, Host, HubOptions } from "./host.js";
|
|
4
|
-
|
|
5
|
+
/**
|
|
6
|
+
* One Mission's map as a standalone Patch: its targets and their prerequisites, flattened so
|
|
7
|
+
* the release carries that map alone whatever Patches it was learnt from, and offering the
|
|
8
|
+
* Mission to whoever opens it.
|
|
9
|
+
*/
|
|
10
|
+
export declare function missionBundle(patches: ClosedPatchBundle, mission: Mission, title: string): {
|
|
11
|
+
bundle: ClosedPatchBundle;
|
|
12
|
+
skills: number;
|
|
13
|
+
};
|
|
14
|
+
export declare function connectHub(profile: ProfileDirectory, theories: readonly ConfiguredTheory[], confirm: Confirm, createMission: Host["missions"]["create"], options?: HubOptions): Host["hub"];
|
package/dist/hub.js
CHANGED
|
@@ -2,23 +2,98 @@ import { mkdtemp, rename, rm } from "node:fs/promises";
|
|
|
2
2
|
import { dirname, basename, join } from "node:path";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import metadata from "../package.json" with { type: "json" };
|
|
5
|
-
import { attachmentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isPatchId, migrateTheoryPatchClosure, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
|
|
5
|
+
import { attachmentDigest, canonicalJson, contentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isMission, isMissionRevision, isPatchId, migrateTheoryPatchClosure, notebookSelection, reifyView, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, selectGraph, } from "@mmon-co/ncept-core";
|
|
6
6
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
7
7
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
8
|
-
import {
|
|
8
|
+
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
9
|
+
import { hubBaseUrl, HubAuth, HubSignInRequired } from "./hub-auth.js";
|
|
9
10
|
import { unpackDirectory } from "./directory.js";
|
|
10
11
|
import { object, parsePiSession } from "./sessions.js";
|
|
11
12
|
import { validate, unpack } from "./exchange.js";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
13
|
+
/**
|
|
14
|
+
* One Mission's map as a standalone Patch: its targets and their prerequisites, flattened so
|
|
15
|
+
* the release carries that map alone whatever Patches it was learnt from, and offering the
|
|
16
|
+
* Mission to whoever opens it.
|
|
17
|
+
*/
|
|
18
|
+
export function missionBundle(patches, mission, title) {
|
|
19
|
+
const graph = resolvePatchBundle(patches, new Set(["local"]), notebookSelection(patches));
|
|
20
|
+
const cone = selectGraph(graph, { cone: { targets: mission.targets.map(({ node }) => node) } });
|
|
21
|
+
if (!cone.nodes.length)
|
|
22
|
+
throw new Error("This Mission has no map yet");
|
|
23
|
+
// Flattened: the link carries the Mission's map alone, whatever Patches it was learnt from.
|
|
24
|
+
const reified = reifyView(cone, {
|
|
25
|
+
metadata: { properties: { "patch:title": title, "patch:description": mission.statement }, citations: [] },
|
|
26
|
+
});
|
|
27
|
+
const provenance = reified.metadata.citations.find((citation) => citation.kind === "reified_from");
|
|
28
|
+
const mapped = new Map(provenance?.kind === "reified_from" ? provenance.entities.nodes.map(({ source, target }) => [source, target]) : []);
|
|
29
|
+
const node = (id) => mapped.get(id) ?? id;
|
|
30
|
+
const entries = (list) => list?.map((entry) => ({
|
|
31
|
+
...entry,
|
|
32
|
+
...(entry.nodes ? { nodes: entry.nodes.map(node) } : {}),
|
|
33
|
+
...(entry.mode === "append"
|
|
34
|
+
? {}
|
|
35
|
+
: "replace" in entry.mode
|
|
36
|
+
? { mode: { replace: entry.mode.replace.map((ref) => ("name" in ref ? ref : { node: node(ref.node) })) } }
|
|
37
|
+
: { mode: { keep: entry.mode.keep.map((ref) => ("name" in ref ? ref : { node: node(ref.node) })) } }),
|
|
38
|
+
}));
|
|
39
|
+
const guidance = entries(mission.guidance);
|
|
40
|
+
const assessment = entries(mission.assessment);
|
|
41
|
+
// The Hub offers this to whoever opens the link as a Mission they can start.
|
|
42
|
+
const suggestion = {
|
|
43
|
+
id: randomUUID(),
|
|
44
|
+
preselected: true,
|
|
45
|
+
statement: mission.statement,
|
|
46
|
+
shortName: title,
|
|
47
|
+
targetNodes: mission.targets.map((target) => node(target.node)),
|
|
48
|
+
...(guidance?.length ? { guidance } : {}),
|
|
49
|
+
...(assessment?.length ? { assessment } : {}),
|
|
50
|
+
};
|
|
51
|
+
const content = {
|
|
52
|
+
...reified,
|
|
53
|
+
metadata: {
|
|
54
|
+
// The Hub records provenance itself and refuses it from a client.
|
|
55
|
+
citations: reified.metadata.citations.filter((citation) => citation.kind !== "reified_from"),
|
|
56
|
+
properties: { ...reified.metadata.properties, [MISSION_SUGGESTIONS]: canonicalJson([suggestion]) },
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
const revision = candidateRevision(`patch-${randomUUID()}`, content);
|
|
60
|
+
const bundle = bundleForRevision(revision.ref, new Map([[revision.ref.digest, content]]));
|
|
61
|
+
resolvePatchBundle(bundle);
|
|
62
|
+
return { bundle, skills: cone.nodes.length };
|
|
63
|
+
}
|
|
64
|
+
/** The Application's metadata property for Missions a release offers its readers. */
|
|
65
|
+
const MISSION_SUGGESTIONS = "application:mission-suggestions";
|
|
66
|
+
function suggestedMissions(revision, contents) {
|
|
67
|
+
const encoded = revision.metadata.properties[MISSION_SUGGESTIONS];
|
|
68
|
+
if (encoded === undefined)
|
|
69
|
+
return [];
|
|
70
|
+
if (typeof encoded !== "string")
|
|
71
|
+
throw new Error("Invalid Mission suggestions metadata");
|
|
72
|
+
const suggestions = JSON.parse(encoded);
|
|
73
|
+
if (!Array.isArray(suggestions))
|
|
74
|
+
throw new Error("Invalid Mission suggestions metadata");
|
|
75
|
+
const nodes = new Set(resolvePatchBundle(bundleForRevision(revision.ref, contents)).nodes.map(({ id }) => id));
|
|
76
|
+
const ids = new Set();
|
|
77
|
+
return suggestions.map((item) => {
|
|
78
|
+
if (!object(item) || typeof item.id !== "string" || !item.id || !Array.isArray(item.targetNodes))
|
|
79
|
+
throw new Error("Invalid Mission suggestion");
|
|
80
|
+
const { statement, targetNodes, guidance, assessment, preselected } = item;
|
|
81
|
+
const mission = {
|
|
82
|
+
id: "hub-" + contentDigest([revision.ref.identity, item.id]),
|
|
83
|
+
statement,
|
|
84
|
+
priority: 1,
|
|
85
|
+
targets: targetNodes.map((node) => ({ node, provenance: revision.ref })),
|
|
86
|
+
...(guidance === undefined ? {} : { guidance }),
|
|
87
|
+
...(assessment === undefined ? {} : { assessment }),
|
|
88
|
+
};
|
|
89
|
+
if (!isMission(mission) ||
|
|
90
|
+
ids.has(mission.id) ||
|
|
91
|
+
new Set(targetNodes).size !== targetNodes.length ||
|
|
92
|
+
mission.targets.some(({ node }) => !nodes.has(node)))
|
|
93
|
+
throw new Error("Invalid Mission suggestion");
|
|
94
|
+
ids.add(mission.id);
|
|
95
|
+
return { mission, preselected: preselected === true };
|
|
96
|
+
});
|
|
22
97
|
}
|
|
23
98
|
function releaseAddress(value, base) {
|
|
24
99
|
const page = value.match(/^(https?:\/\/.+)\/hub\/([^/]+)\/releases\/([^/?#]+)(?:[?#].*)?$/);
|
|
@@ -30,7 +105,7 @@ function releaseAddress(value, base) {
|
|
|
30
105
|
if (!isPatchId(patchId) || !version)
|
|
31
106
|
throw new Error("Use a Hub release page URL or patch-id@version");
|
|
32
107
|
releasePrecedenceKey(version);
|
|
33
|
-
return { base: match ?
|
|
108
|
+
return { base: match ? hubBaseUrl(match[1] ?? "") : base, patchId, version };
|
|
34
109
|
}
|
|
35
110
|
function releasePath(patchId, version) {
|
|
36
111
|
return "/hub/v1/releases/" + encodeURIComponent(patchId) + "/" + encodeURIComponent(version);
|
|
@@ -94,17 +169,24 @@ function theoryRequirement(value) {
|
|
|
94
169
|
throw new Error("Invalid Hub release Theory requirement");
|
|
95
170
|
return { theory: value.theory, range: value.range };
|
|
96
171
|
}
|
|
97
|
-
export function connectHub(profile, theories, confirm, options = {}) {
|
|
98
|
-
const base =
|
|
172
|
+
export function connectHub(profile, theories, confirm, createMission, options = {}) {
|
|
173
|
+
const base = hubBaseUrl(options.url);
|
|
99
174
|
const resource = base + "/mcp";
|
|
100
175
|
const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + metadata.version };
|
|
101
176
|
async function connected(operation) {
|
|
102
177
|
const provider = await HubAuth.open(resource, options);
|
|
103
178
|
if (!provider.tokens())
|
|
104
|
-
throw new
|
|
105
|
-
const client = new Client({ name:
|
|
179
|
+
throw new HubSignInRequired();
|
|
180
|
+
const client = new Client({ name: metadata.name, version: metadata.version });
|
|
106
181
|
try {
|
|
107
|
-
|
|
182
|
+
try {
|
|
183
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider }));
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (error instanceof UnauthorizedError)
|
|
187
|
+
throw new HubSignInRequired();
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
108
190
|
return await operation(async (name, args) => {
|
|
109
191
|
const result = await client.callTool({ name, arguments: args });
|
|
110
192
|
const text = Array.isArray(result.content)
|
|
@@ -135,6 +217,25 @@ export function connectHub(profile, theories, confirm, options = {}) {
|
|
|
135
217
|
});
|
|
136
218
|
return hash;
|
|
137
219
|
}
|
|
220
|
+
/** Upload a closed bundle's attachments, capture it as a new Hub Patch and release it. */
|
|
221
|
+
async function release(bundle, blobs, version, visibility) {
|
|
222
|
+
return connected(async (call) => {
|
|
223
|
+
for (const attachment of attachments(bundle)) {
|
|
224
|
+
const bytes = blobs.get(attachment.hash);
|
|
225
|
+
if (!bytes)
|
|
226
|
+
throw new Error("Missing Profile blob: " + attachment.hash);
|
|
227
|
+
await upload(call, bytes, attachment.mediaType);
|
|
228
|
+
}
|
|
229
|
+
const captured = await call("capture", { bundle });
|
|
230
|
+
await call("name", { patchId: captured.ref.identity, digest: captured.ref.digest, version });
|
|
231
|
+
await call("publish", { patchId: captured.ref.identity, version, visibility });
|
|
232
|
+
return {
|
|
233
|
+
ref: captured.ref,
|
|
234
|
+
version,
|
|
235
|
+
url: base + "/hub/" + captured.ref.identity + "/releases/" + encodeURIComponent(version),
|
|
236
|
+
};
|
|
237
|
+
});
|
|
238
|
+
}
|
|
138
239
|
return {
|
|
139
240
|
async pull(address) {
|
|
140
241
|
const selected = releaseAddress(address, base);
|
|
@@ -193,6 +294,21 @@ export function connectHub(profile, theories, confirm, options = {}) {
|
|
|
193
294
|
const next = candidateRevision(personal.ref.identity, content);
|
|
194
295
|
contents.set(next.ref.digest, content);
|
|
195
296
|
resolvePatchBundle(bundleForRevision(next.ref, contents));
|
|
297
|
+
const suggestions = suggestedMissions(adopted, contents);
|
|
298
|
+
const existing = new Set(current.log.filter(isMissionRevision).map(({ mission }) => mission.id));
|
|
299
|
+
const selectedMissions = [];
|
|
300
|
+
for (const { mission, preselected } of suggestions) {
|
|
301
|
+
if (existing.has(mission.id))
|
|
302
|
+
continue;
|
|
303
|
+
if (await confirm({
|
|
304
|
+
kind: "hub.pull.mission",
|
|
305
|
+
title: "Add the suggested Mission?",
|
|
306
|
+
description: mission.statement,
|
|
307
|
+
detail: { statement: mission.statement },
|
|
308
|
+
defaultAccepted: preselected,
|
|
309
|
+
}))
|
|
310
|
+
selectedMissions.push(mission);
|
|
311
|
+
}
|
|
196
312
|
// Nothing touches the live head until every downloaded revision and blob verifies.
|
|
197
313
|
for (const bytes of blobs.values())
|
|
198
314
|
await profile.addBlob(bytes);
|
|
@@ -202,6 +318,8 @@ export function connectHub(profile, theories, confirm, options = {}) {
|
|
|
202
318
|
if (!revisions.has(exactPatchRefKey(revision.ref)))
|
|
203
319
|
await profile.addRevision(revision.ref.identity, revisionContent(revision));
|
|
204
320
|
await profile.setPersonal(await profile.addRevision(personal.ref.identity, content));
|
|
321
|
+
for (const mission of selectedMissions)
|
|
322
|
+
await createMission(mission);
|
|
205
323
|
return adopted.ref;
|
|
206
324
|
},
|
|
207
325
|
async signIn() {
|
|
@@ -237,54 +355,54 @@ export function connectHub(profile, theories, confirm, options = {}) {
|
|
|
237
355
|
detail: { ...input, bundle },
|
|
238
356
|
})))
|
|
239
357
|
throw new Error("Publication declined");
|
|
240
|
-
return
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
358
|
+
return release(bundle, current.blobs, input.version, "public");
|
|
359
|
+
},
|
|
360
|
+
async share(input) {
|
|
361
|
+
const title = input.title.trim();
|
|
362
|
+
if (!title)
|
|
363
|
+
throw new Error("A shared Mission needs a title");
|
|
364
|
+
const visibility = input.visibility ?? "unlisted";
|
|
365
|
+
const current = await profile.read();
|
|
366
|
+
const mission = current.log
|
|
367
|
+
.filter(isMissionRevision)
|
|
368
|
+
.findLast((entry) => entry.mission.id === input.mission)?.mission;
|
|
369
|
+
if (!mission)
|
|
370
|
+
throw new Error("Unknown Mission");
|
|
371
|
+
const { bundle, skills } = missionBundle(current.patches, mission, title);
|
|
372
|
+
if (!(await confirm({
|
|
373
|
+
kind: "hub.share",
|
|
374
|
+
title: "Share " + title,
|
|
375
|
+
description: visibility === "public"
|
|
376
|
+
? "List this Mission's map (" + skills + " skills) and its Materials publicly on the Hub."
|
|
377
|
+
: "Publish this Mission's map (" +
|
|
378
|
+
skills +
|
|
379
|
+
" skills) and its Materials at a link. Anyone with the link can read and learn from it; it isn't listed on the Hub.",
|
|
380
|
+
detail: { mission: mission.id, statement: mission.statement, title, visibility, skills: skills },
|
|
381
|
+
})))
|
|
382
|
+
throw new Error("Share declined");
|
|
383
|
+
const provider = await HubAuth.open(resource, options);
|
|
384
|
+
if (!provider.tokens()) {
|
|
385
|
+
if (input.signIn === false)
|
|
386
|
+
throw new HubSignInRequired();
|
|
387
|
+
await provider.signIn();
|
|
388
|
+
}
|
|
389
|
+
return release(bundle, current.blobs, "0.1.0", visibility);
|
|
256
390
|
},
|
|
257
391
|
async exportTo() {
|
|
258
392
|
const archive = await profile.pack();
|
|
259
393
|
await connected(async (call) => {
|
|
260
394
|
const hash = await upload(call, archive, "application/x-tar");
|
|
261
395
|
const preview = await call("import_profile", { hash });
|
|
262
|
-
let missions;
|
|
263
|
-
if (preview.status === "choose-missions") {
|
|
264
|
-
missions = [];
|
|
265
|
-
for (const mission of preview.missions) {
|
|
266
|
-
if (preview.available !== null && missions.length >= preview.available)
|
|
267
|
-
break;
|
|
268
|
-
if (await confirm({
|
|
269
|
-
kind: "hub.choose-mission",
|
|
270
|
-
title: "Keep Mission: " + mission.statement,
|
|
271
|
-
description: "Choose Missions to move to the web within your allowance, or upgrade on the web first.",
|
|
272
|
-
detail: { mission, available: preview.available, upgrade: preview.upgrade },
|
|
273
|
-
}))
|
|
274
|
-
missions.push(mission.id);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
396
|
if (!(await confirm({
|
|
278
397
|
kind: "hub.export",
|
|
279
398
|
title: "Replace web Main with this local Profile",
|
|
280
|
-
description: "The old web Main is retained as history.
|
|
281
|
-
detail:
|
|
399
|
+
description: "The old web Main is retained as history.",
|
|
400
|
+
detail: preview,
|
|
282
401
|
})))
|
|
283
402
|
return;
|
|
284
403
|
const result = await call("import_profile", {
|
|
285
404
|
hash,
|
|
286
405
|
expectedMainProfileId: preview.mainProfileId,
|
|
287
|
-
...(missions === undefined ? {} : { missions }),
|
|
288
406
|
});
|
|
289
407
|
if (result.status !== "imported")
|
|
290
408
|
throw new Error("Web import needs a new preview: " + JSON.stringify(result));
|
package/dist/index.d.ts
CHANGED
|
@@ -2,4 +2,5 @@ export * from "./exchange.js";
|
|
|
2
2
|
export * from "./sessions.js";
|
|
3
3
|
export * from "./directory.js";
|
|
4
4
|
export * from "./host.js";
|
|
5
|
+
export { beginHubBrowserSignIn, hasHubCredentials, HubSignInRequired, type HubBrowserSignIn } from "./hub-auth.js";
|
|
5
6
|
export { openLearningReader } from "./learning.js";
|
package/dist/index.js
CHANGED
|
@@ -2,4 +2,5 @@ export * from "./exchange.js";
|
|
|
2
2
|
export * from "./sessions.js";
|
|
3
3
|
export * from "./directory.js";
|
|
4
4
|
export * from "./host.js";
|
|
5
|
+
export { beginHubBrowserSignIn, hasHubCredentials, HubSignInRequired } from "./hub-auth.js";
|
|
5
6
|
export { openLearningReader } from "./learning.js";
|
package/dist/learning.d.ts
CHANGED
|
@@ -9,6 +9,11 @@ export declare function openLearningReader<S>(profileDir: string, theories: read
|
|
|
9
9
|
id: `node-${string}`;
|
|
10
10
|
label: string;
|
|
11
11
|
status: "open" | "done" | "tentative";
|
|
12
|
+
frontier: boolean;
|
|
13
|
+
}[];
|
|
14
|
+
edges: {
|
|
15
|
+
from: `node-${string}`;
|
|
16
|
+
to: `node-${string}`;
|
|
12
17
|
}[];
|
|
13
18
|
dueReview: {
|
|
14
19
|
id: `node-${string}`;
|
|
@@ -24,6 +29,7 @@ export declare function openLearningReader<S>(profileDir: string, theories: read
|
|
|
24
29
|
surface: import("@mmon-co/ncept-core").SurfaceId;
|
|
25
30
|
about: readonly NodeId[];
|
|
26
31
|
closed: boolean;
|
|
32
|
+
closing?: string;
|
|
27
33
|
mission?: string;
|
|
28
34
|
parent?: string;
|
|
29
35
|
id: import("@mmon-co/ncept-core").SessionRef;
|
|
@@ -36,13 +42,15 @@ export declare function openLearningReader<S>(profileDir: string, theories: read
|
|
|
36
42
|
export declare class LearningHost<S> {
|
|
37
43
|
readonly runtime: Runtime<S>;
|
|
38
44
|
readonly confirm: OpenHostOptions<S>["confirm"];
|
|
45
|
+
readonly onCloseError: (error: unknown) => void;
|
|
39
46
|
private tail;
|
|
40
47
|
private pendingSwitch?;
|
|
48
|
+
private readonly closeJobs;
|
|
41
49
|
readonly drafts: Map<string, {
|
|
42
50
|
base: string;
|
|
43
51
|
content: PatchContent;
|
|
44
52
|
}>;
|
|
45
|
-
constructor(runtime: Runtime<S>, confirm: OpenHostOptions<S>["confirm"]);
|
|
53
|
+
constructor(runtime: Runtime<S>, confirm: OpenHostOptions<S>["confirm"], onCloseError?: (error: unknown) => void);
|
|
46
54
|
serial<T>(operation: () => Promise<T>): Promise<T>;
|
|
47
55
|
reload(): Promise<void>;
|
|
48
56
|
current(session: HostSession): Promise<LocalSession>;
|
|
@@ -55,8 +63,10 @@ export declare class LearningHost<S> {
|
|
|
55
63
|
}>;
|
|
56
64
|
reviseMission(mission: Mission, create: boolean): Promise<void>;
|
|
57
65
|
private closing;
|
|
58
|
-
private
|
|
59
|
-
|
|
66
|
+
private markClosing;
|
|
67
|
+
private endingRun;
|
|
68
|
+
end(session: HostSession): Promise<void>;
|
|
69
|
+
closePending(): Promise<void>;
|
|
60
70
|
settle(session: HostSession): Promise<ModeSwitch | undefined>;
|
|
61
71
|
retireMission(id: string, outcome: "achieved" | "abandoned"): Promise<void>;
|
|
62
72
|
begin(intent: SessionIntent): Promise<HostSession>;
|
package/dist/learning.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { isMission, isMissionRevision, isRunActiveChange, isRunPastEntry, isRunRetirement, nodeCascadedProperty, readMissionPath, readMissionRun, retire, selectGraph, setActive, tagIndex, } from "@mmon-co/ncept-core";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { lock } from "proper-lockfile";
|
|
2
4
|
import { openProfile } from "./directory.js";
|
|
3
5
|
import { connectHub } from "./hub.js";
|
|
4
6
|
import { checkedTimezone, learnerDayAt } from "./days.js";
|
|
@@ -58,11 +60,19 @@ export async function openLearningReader(profileDir, theories) {
|
|
|
58
60
|
const view = await runtime.snapshot();
|
|
59
61
|
const projection = view.theory.project(view.graph, view.state);
|
|
60
62
|
const progress = view.theory.progress(view.graph, projection, view.graph.nodes.map(({ id }) => id));
|
|
61
|
-
const
|
|
63
|
+
const tagged = tagIndex(projection);
|
|
64
|
+
const dueReview = [...tagged("review:due")];
|
|
65
|
+
const frontier = tagged("frontier");
|
|
62
66
|
const label = (id) => stringProperty(view.graph, id, "display:label", id);
|
|
63
67
|
return {
|
|
64
68
|
missions: readMissions(view, true),
|
|
65
|
-
nodes: view.graph.nodes.map(({ id }) => ({
|
|
69
|
+
nodes: view.graph.nodes.map(({ id }) => ({
|
|
70
|
+
id,
|
|
71
|
+
label: label(id),
|
|
72
|
+
status: progress[id]?.status ?? "open",
|
|
73
|
+
frontier: frontier.has(id),
|
|
74
|
+
})),
|
|
75
|
+
edges: view.graph.edges.map(({ from, to }) => ({ from, to })),
|
|
66
76
|
dueReview: dueReview.map((id) => ({ id, label: label(id) })),
|
|
67
77
|
sessions: sessionStates(view.profile).map((session) => ({
|
|
68
78
|
...session,
|
|
@@ -131,7 +141,7 @@ function missions(profile) {
|
|
|
131
141
|
function runs(sessions) {
|
|
132
142
|
return sessions.map((session) => ({
|
|
133
143
|
ref: session.id,
|
|
134
|
-
open: !session.closed,
|
|
144
|
+
open: !session.closed && !session.closing,
|
|
135
145
|
...(session.parent === undefined ? {} : { parent: session.parent }),
|
|
136
146
|
}));
|
|
137
147
|
}
|
|
@@ -173,12 +183,15 @@ function runEntries(before, after, at) {
|
|
|
173
183
|
export class LearningHost {
|
|
174
184
|
runtime;
|
|
175
185
|
confirm;
|
|
186
|
+
onCloseError;
|
|
176
187
|
tail = Promise.resolve();
|
|
177
188
|
pendingSwitch;
|
|
189
|
+
closeJobs = new Map();
|
|
178
190
|
drafts = new Map();
|
|
179
|
-
constructor(runtime, confirm) {
|
|
191
|
+
constructor(runtime, confirm, onCloseError = (error) => console.error("Session close failed:", error)) {
|
|
180
192
|
this.runtime = runtime;
|
|
181
193
|
this.confirm = confirm;
|
|
194
|
+
this.onCloseError = onCloseError;
|
|
182
195
|
}
|
|
183
196
|
serial(operation) {
|
|
184
197
|
const result = this.tail.then(operation);
|
|
@@ -292,10 +305,15 @@ export class LearningHost {
|
|
|
292
305
|
}, session);
|
|
293
306
|
return [
|
|
294
307
|
...event.entries,
|
|
295
|
-
platform({ kind: "local.session", session: { ...session, closed: true } }, session.surface),
|
|
308
|
+
platform({ kind: "local.session", session: { ...session, closing: undefined, closed: true } }, session.surface),
|
|
296
309
|
];
|
|
297
310
|
}
|
|
298
|
-
|
|
311
|
+
markClosing(session) {
|
|
312
|
+
return session.closed || session.closing
|
|
313
|
+
? []
|
|
314
|
+
: [platform({ kind: "local.session", session: { ...session, closing: identity() } }, session.surface)];
|
|
315
|
+
}
|
|
316
|
+
endingRun(current, profile) {
|
|
299
317
|
const known = sessionStates(profile);
|
|
300
318
|
const closing = new Set([current.id]);
|
|
301
319
|
for (const id of closing)
|
|
@@ -315,20 +333,63 @@ export class LearningHost {
|
|
|
315
333
|
}
|
|
316
334
|
for (const session of known)
|
|
317
335
|
if (closing.has(session.id))
|
|
318
|
-
entries.push(...
|
|
336
|
+
entries.push(...this.markClosing(session));
|
|
319
337
|
return entries;
|
|
320
338
|
}
|
|
321
|
-
async
|
|
339
|
+
async end(session) {
|
|
322
340
|
const current = await this.current(session);
|
|
323
|
-
await this.runtime.profile.appendLog(
|
|
341
|
+
await this.runtime.profile.appendLog(this.endingRun(current, await this.runtime.profile.read()));
|
|
342
|
+
}
|
|
343
|
+
async closePending() {
|
|
344
|
+
const pending = sessionStates(await this.runtime.profile.read()).filter((session) => !session.closed && session.closing);
|
|
345
|
+
const failures = [];
|
|
346
|
+
for (const session of pending) {
|
|
347
|
+
const key = session.closing;
|
|
348
|
+
if (!key)
|
|
349
|
+
continue;
|
|
350
|
+
let job = this.closeJobs.get(key);
|
|
351
|
+
if (!job) {
|
|
352
|
+
job = (async () => {
|
|
353
|
+
// The receiving thread's startup sweep may meet the source's background close.
|
|
354
|
+
// Lock only this close, leaving the Profile writable throughout model calls.
|
|
355
|
+
const release = await lock(join(this.runtime.profile.dir, ".close-" + encodeURIComponent(key)), {
|
|
356
|
+
realpath: false,
|
|
357
|
+
retries: { forever: true, minTimeout: 10, maxTimeout: 100, randomize: true },
|
|
358
|
+
});
|
|
359
|
+
try {
|
|
360
|
+
const before = await this.current(session);
|
|
361
|
+
if (before.closed || before.closing !== key)
|
|
362
|
+
return;
|
|
363
|
+
const entries = await this.closing(before);
|
|
364
|
+
// Check under the Profile write lock: another process may have resumed it.
|
|
365
|
+
await this.runtime.profile.appendLog(entries, (profile) => sessionStates(profile).some((current) => current.id === session.id && !current.closed && current.closing === key));
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
await release();
|
|
369
|
+
}
|
|
370
|
+
})();
|
|
371
|
+
this.closeJobs.set(key, job);
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
await job;
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
failures.push(error);
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
this.closeJobs.delete(key);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (failures.length)
|
|
384
|
+
throw new AggregateError(failures, "Session close failed");
|
|
324
385
|
}
|
|
325
386
|
async settle(session) {
|
|
326
387
|
const current = await this.current(session);
|
|
327
|
-
if (current.closed || current.mode !== "lesson" || current.entry?.kind !== "lesson")
|
|
388
|
+
if (current.closed || current.closing || current.mode !== "lesson" || current.entry?.kind !== "lesson")
|
|
328
389
|
return;
|
|
329
390
|
if (!(await this.context(current)).lesson?.complete)
|
|
330
391
|
return;
|
|
331
|
-
await this.
|
|
392
|
+
await this.end(current);
|
|
332
393
|
return {
|
|
333
394
|
mode: "charting",
|
|
334
395
|
then: "next",
|
|
@@ -555,11 +616,11 @@ export class LearningHost {
|
|
|
555
616
|
for (const ref of result.close) {
|
|
556
617
|
const outgoing = known.find(({ id }) => id === ref);
|
|
557
618
|
if (outgoing)
|
|
558
|
-
entries.push(...
|
|
619
|
+
entries.push(...this.markClosing(outgoing));
|
|
559
620
|
}
|
|
560
621
|
}
|
|
561
622
|
if (pending?.to.then === "next" && (!missionId || pending.from.mission !== missionId))
|
|
562
|
-
entries.push(...
|
|
623
|
+
entries.push(...this.endingRun(pending.from, view.profile));
|
|
563
624
|
const event = await this.runtime.event({ kind: "surface.open", surface: session.surface, format: "local", about }, session);
|
|
564
625
|
entries.push(...event.entries, platform({ kind: "local.session", session }, session.surface));
|
|
565
626
|
if (skipped.length) {
|
|
@@ -640,7 +701,7 @@ export class LearningHost {
|
|
|
640
701
|
for (const id of result.close) {
|
|
641
702
|
const outgoing = sessionStates(view.profile).find((item) => item.id === id);
|
|
642
703
|
if (outgoing)
|
|
643
|
-
entries.push(...
|
|
704
|
+
entries.push(...this.markClosing(outgoing));
|
|
644
705
|
}
|
|
645
706
|
}
|
|
646
707
|
entries.push(platform({ kind: "local.session", session: updated }, session.surface));
|
|
@@ -700,8 +761,8 @@ export class LearningHost {
|
|
|
700
761
|
}
|
|
701
762
|
async turn(input, learnerMessage) {
|
|
702
763
|
const session = await this.current(input);
|
|
703
|
-
if (session.closed)
|
|
704
|
-
throw new Error("Session is
|
|
764
|
+
if (session.closed || session.closing)
|
|
765
|
+
throw new Error("Session is ended; resume it first");
|
|
705
766
|
let view = await this.runtime.snapshot();
|
|
706
767
|
let ctx = await this.context(session);
|
|
707
768
|
if (learnerMessage !== undefined && view.theory.chat?.reply) {
|
|
@@ -732,7 +793,7 @@ export class LearningHost {
|
|
|
732
793
|
schema: tool.schema,
|
|
733
794
|
run: (args) => this.serial(async () => {
|
|
734
795
|
const current = await this.current(session);
|
|
735
|
-
if (current.closed || current.mode !== session.mode)
|
|
796
|
+
if (current.closed || current.closing || current.mode !== session.mode)
|
|
736
797
|
throw new Error("Tool belongs to an inactive Session mode");
|
|
737
798
|
const result = await this.runtime.prepare(tool.run(args, await this.context(current)), current);
|
|
738
799
|
const feature = await this.runtime.event({ kind: "feature.used", operation: tool.name, at: new Date().toISOString(), about: current.about }, current);
|
|
@@ -793,15 +854,19 @@ export class LearningHost {
|
|
|
793
854
|
}
|
|
794
855
|
if (typeof localSettings(view.profile).timezone !== "string")
|
|
795
856
|
await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone: this.runtime.timezone })]);
|
|
857
|
+
// Only persisted closing tokens record an interrupted close. An unmarked Session
|
|
858
|
+
// may still be live in another host, including Charting without a Mission run.
|
|
859
|
+
// Recovery must not delay startup of a thread receiving a Session handoff.
|
|
860
|
+
void this.closePending().catch(this.onCloseError);
|
|
796
861
|
}
|
|
797
862
|
}
|
|
798
863
|
export async function openHost(options) {
|
|
799
864
|
const profile = await openProfile(options.profileDir, options.theories);
|
|
800
865
|
const config = localSettings(await profile.read());
|
|
801
866
|
const timezone = checkedTimezone(typeof config.timezone === "string" ? config.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
802
|
-
const learning = new LearningHost(new Runtime(profile, options.theories, options.model, timezone), options.confirm);
|
|
867
|
+
const learning = new LearningHost(new Runtime(profile, options.theories, options.model, timezone), options.confirm, options.onCloseError ?? ((error) => console.error("Session close failed:", error)));
|
|
803
868
|
await learning.start();
|
|
804
|
-
const hub = connectHub(profile, options.theories, options.confirm, options.hub);
|
|
869
|
+
const hub = connectHub(profile, options.theories, options.confirm, (mission) => learning.reviseMission(mission, true), options.hub);
|
|
805
870
|
return {
|
|
806
871
|
profile,
|
|
807
872
|
sessions: {
|
|
@@ -809,7 +874,12 @@ export async function openHost(options) {
|
|
|
809
874
|
begin: (intent) => learning.serial(() => learning.begin(intent)),
|
|
810
875
|
turn: (session, input) => learning.serial(() => learning.turn(session, input.learnerMessage)),
|
|
811
876
|
settle: (session) => learning.serial(() => learning.settle(session)),
|
|
812
|
-
|
|
877
|
+
end: (session) => learning.serial(() => learning.end(session)),
|
|
878
|
+
closePending: () => learning.closePending(),
|
|
879
|
+
close: async (session) => {
|
|
880
|
+
await learning.serial(() => learning.end(session));
|
|
881
|
+
await learning.closePending();
|
|
882
|
+
},
|
|
813
883
|
},
|
|
814
884
|
missions: {
|
|
815
885
|
list: () => learning.missionReadings(),
|
|
@@ -823,6 +893,7 @@ export async function openHost(options) {
|
|
|
823
893
|
pull: (address) => learning.serial(() => hub.pull(address)),
|
|
824
894
|
signIn: () => learning.serial(() => hub.signIn()),
|
|
825
895
|
publish: (input) => learning.serial(() => hub.publish(input)),
|
|
896
|
+
share: (input) => learning.serial(() => hub.share(input)),
|
|
826
897
|
exportTo: (destination) => learning.serial(() => hub.exportTo(destination)),
|
|
827
898
|
importFrom: (source) => learning.serial(async () => {
|
|
828
899
|
const result = await hub.importFrom(source);
|
package/dist/runtime.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export interface LocalSession extends HostSession {
|
|
|
6
6
|
readonly surface: SurfaceId;
|
|
7
7
|
readonly about: readonly NodeId[];
|
|
8
8
|
readonly closed: boolean;
|
|
9
|
+
/** Identifies a pending close; resuming the Session clears it. */
|
|
10
|
+
readonly closing?: string;
|
|
9
11
|
readonly mission?: string;
|
|
10
12
|
readonly parent?: string;
|
|
11
13
|
}
|
package/dist/runtime.js
CHANGED
|
@@ -38,6 +38,7 @@ export function sessionStates(profile) {
|
|
|
38
38
|
surface: session.surface,
|
|
39
39
|
mode: session.mode,
|
|
40
40
|
closed: session.closed,
|
|
41
|
+
...(typeof session.closing === "string" ? { closing: session.closing } : {}),
|
|
41
42
|
about: nodeIds(session.about),
|
|
42
43
|
...(session.entry === undefined ? {} : { entry: modeEntry(session.entry) }),
|
|
43
44
|
...(typeof session.mission === "string" ? { mission: session.mission } : {}),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mmon-co/ncept-local",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -36,12 +36,12 @@
|
|
|
36
36
|
"prepack": "bun run build"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@mmon-co/ncept-core": "^0.
|
|
39
|
+
"@mmon-co/ncept-core": "^0.4.0",
|
|
40
40
|
"@modelcontextprotocol/sdk": "1.32.1",
|
|
41
41
|
"proper-lockfile": "4.1.2"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@mmon-co/ncept-default-theory": "^
|
|
44
|
+
"@mmon-co/ncept-default-theory": "^3.0.0",
|
|
45
45
|
"@types/proper-lockfile": "^4.1.4",
|
|
46
46
|
"bun-types": "^1.3.14",
|
|
47
47
|
"typescript": "5.9.3"
|