@nookplot/runtime 0.5.142 → 0.5.144

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.
Files changed (60) hide show
  1. package/dist/__tests__/bdAgentPack.test.d.ts +2 -0
  2. package/dist/__tests__/bdAgentPack.test.d.ts.map +1 -0
  3. package/dist/__tests__/bdAgentPack.test.js +44 -0
  4. package/dist/__tests__/bdAgentPack.test.js.map +1 -0
  5. package/dist/__tests__/externalMcpTools.test.d.ts +2 -0
  6. package/dist/__tests__/externalMcpTools.test.d.ts.map +1 -0
  7. package/dist/__tests__/externalMcpTools.test.js +94 -0
  8. package/dist/__tests__/externalMcpTools.test.js.map +1 -0
  9. package/dist/__tests__/pack.gating.test.d.ts +2 -0
  10. package/dist/__tests__/pack.gating.test.d.ts.map +1 -0
  11. package/dist/__tests__/pack.gating.test.js +134 -0
  12. package/dist/__tests__/pack.gating.test.js.map +1 -0
  13. package/dist/__tests__/pack.test.d.ts +2 -0
  14. package/dist/__tests__/pack.test.d.ts.map +1 -0
  15. package/dist/__tests__/pack.test.js +299 -0
  16. package/dist/__tests__/pack.test.js.map +1 -0
  17. package/dist/__tests__/packLoader.test.d.ts +2 -0
  18. package/dist/__tests__/packLoader.test.d.ts.map +1 -0
  19. package/dist/__tests__/packLoader.test.js +304 -0
  20. package/dist/__tests__/packLoader.test.js.map +1 -0
  21. package/dist/__tests__/presetLoader.test.d.ts +2 -0
  22. package/dist/__tests__/presetLoader.test.d.ts.map +1 -0
  23. package/dist/__tests__/presetLoader.test.js +766 -0
  24. package/dist/__tests__/presetLoader.test.js.map +1 -0
  25. package/dist/actionCatalog.d.ts.map +1 -1
  26. package/dist/actionCatalog.generated.d.ts +1 -1
  27. package/dist/actionCatalog.generated.d.ts.map +1 -1
  28. package/dist/actionCatalog.generated.js +7 -2
  29. package/dist/actionCatalog.generated.js.map +1 -1
  30. package/dist/actionCatalog.js +4 -12
  31. package/dist/actionCatalog.js.map +1 -1
  32. package/dist/autonomous.d.ts +24 -1
  33. package/dist/autonomous.d.ts.map +1 -1
  34. package/dist/autonomous.js +66 -8
  35. package/dist/autonomous.js.map +1 -1
  36. package/dist/index.d.ts +7 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +6 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/pack.d.ts +181 -0
  41. package/dist/pack.d.ts.map +1 -0
  42. package/dist/pack.js +379 -0
  43. package/dist/pack.js.map +1 -0
  44. package/dist/packLoader.d.ts +109 -0
  45. package/dist/packLoader.d.ts.map +1 -0
  46. package/dist/packLoader.js +236 -0
  47. package/dist/packLoader.js.map +1 -0
  48. package/dist/presetLoader.d.ts +132 -0
  49. package/dist/presetLoader.d.ts.map +1 -0
  50. package/dist/presetLoader.js +740 -0
  51. package/dist/presetLoader.js.map +1 -0
  52. package/dist/signalActionMap.d.ts +17 -1
  53. package/dist/signalActionMap.d.ts.map +1 -1
  54. package/dist/signalActionMap.js +37 -2
  55. package/dist/signalActionMap.js.map +1 -1
  56. package/dist/tools.d.ts +23 -7
  57. package/dist/tools.d.ts.map +1 -1
  58. package/dist/tools.js +20 -6
  59. package/dist/tools.js.map +1 -1
  60. package/package.json +2 -2
@@ -0,0 +1,236 @@
1
+ /**
2
+ * PackLoader — loads a Pack at agent boot (ROADMAP_external-mcp-connectors
3
+ * Phase 3; the minimal pack-load slice that ROADMAP_pack-primitive inherits).
4
+ *
5
+ * On load it:
6
+ * 1. Parses + validates the pack (from options.pack or a pack YAML file).
7
+ * 2. Pre-flights every declared connection — which external services are
8
+ * already connected (agent credential / OAuth / workspace connection) —
9
+ * and produces actionable hints for the missing ones.
10
+ * 3. Mounts the declared MCP servers via the Phase-1/2 bridge
11
+ * (POST /v1/agents/me/mcp/servers is an upsert, so re-loading is
12
+ * idempotent). Servers whose connection is unsatisfied are skipped.
13
+ * 4. Reports connector binding status (Discord bindings are created in the
14
+ * platform install flow — a pack declares the capability; the loader
15
+ * reports bound/unbound).
16
+ * 5. Delegates the embedded `preset` block verbatim to PresetLoader.
17
+ *
18
+ * The loader mounts and reports; it does NOT gate. Pass the same pack to
19
+ * `new AutonomousAgent(runtime, { pack })` for prompt + dispatch gating.
20
+ *
21
+ * @module packLoader
22
+ */
23
+ import { readFile } from "node:fs/promises";
24
+ import { PresetLoader } from "./presetLoader.js";
25
+ import { CONNECTOR_PLATFORMS, parsePack, resolvePackActions } from "./pack.js";
26
+ // ── Registry fetch (shared by PackLoader + the CLI loops) ─────
27
+ /**
28
+ * Fetch a pack from the gateway registry by `"name"` or `"name@1.2.3"` via
29
+ * POST /v1/agents/me/pack/load — which also records it as the calling
30
+ * agent's active pack. Registry content is untrusted: it is re-validated
31
+ * with parsePack before returning; invalid content throws.
32
+ */
33
+ export async function fetchRegistryPack(runtime, ref) {
34
+ const at = ref.indexOf("@");
35
+ const name = at === -1 ? ref : ref.slice(0, at);
36
+ const version = at === -1 ? undefined : ref.slice(at + 1);
37
+ const res = await runtime.connection.request("POST", "/v1/agents/me/pack/load", {
38
+ name,
39
+ ...(version ? { version } : {}),
40
+ });
41
+ const result = parsePack(res.pack.content);
42
+ if (!result.ok || !result.pack) {
43
+ throw new Error(`Registry pack "${ref}" failed validation:\n - ${result.errors.join("\n - ")}`);
44
+ }
45
+ return { pack: result.pack, contentHash: res.pack.contentHash };
46
+ }
47
+ // ── PackLoader ────────────────────────────────────────────────
48
+ export class PackLoader {
49
+ runtime;
50
+ options;
51
+ constructor(runtime, options = {}) {
52
+ this.runtime = runtime;
53
+ this.options = options;
54
+ }
55
+ /** Load the pack: validate → pre-flight → mount → connector status → preset. */
56
+ async load() {
57
+ const { pack, source, contentHash } = await this.resolvePack();
58
+ const connections = await this.checkConnections(pack);
59
+ const mcpServers = await this.mountServers(pack, connections);
60
+ const connectors = await this.checkConnectors(pack);
61
+ let preset;
62
+ if (pack.preset) {
63
+ const presetLoader = new PresetLoader(this.runtime, this.options.presetConfigPath ?? "./nookplot.yaml", pack.preset);
64
+ preset = await presetLoader.load();
65
+ }
66
+ return {
67
+ name: pack.name,
68
+ version: pack.version,
69
+ source,
70
+ ...(contentHash ? { contentHash } : {}),
71
+ connections,
72
+ mcpServers,
73
+ connectors,
74
+ ...(preset ? { preset } : {}),
75
+ actions: resolvePackActions(pack),
76
+ ok: connections.every((c) => c.status === "satisfied") &&
77
+ mcpServers.every((s) => s.status === "mounted"),
78
+ };
79
+ }
80
+ async resolvePack() {
81
+ if (this.options.pack)
82
+ return { pack: this.options.pack, source: "inline" };
83
+ if (this.options.packRef) {
84
+ const { pack, contentHash } = await fetchRegistryPack(this.runtime, this.options.packRef);
85
+ return { pack, source: "registry", contentHash };
86
+ }
87
+ const path = this.options.packPath ?? "./pack.yaml";
88
+ const text = await readFile(path, "utf-8");
89
+ const result = parsePack(text);
90
+ if (!result.ok || !result.pack) {
91
+ throw new Error(`Pack "${path}" is invalid:\n - ${result.errors.join("\n - ")}`);
92
+ }
93
+ return { pack: result.pack, source: "file" };
94
+ }
95
+ // ── Connection pre-flight ───────────────────────────────────
96
+ async checkConnections(pack) {
97
+ const declared = pack.connections ?? [];
98
+ if (declared.length === 0)
99
+ return [];
100
+ // One credentials fetch covers every agent-owned connection.
101
+ let agentServices = null;
102
+ if (declared.some((c) => c.owner === "agent")) {
103
+ try {
104
+ const res = await this.runtime.connection.request("GET", "/v1/agents/me/credentials");
105
+ agentServices = new Set((res.credentials ?? []).map((c) => c.service));
106
+ }
107
+ catch {
108
+ agentServices = new Set();
109
+ }
110
+ }
111
+ // One workspace-connections fetch covers every workspace-owned connection.
112
+ let workspaceServices = null;
113
+ if (declared.some((c) => c.owner === "workspace") && this.options.workspaceId) {
114
+ try {
115
+ const res = await this.runtime.connection.request("GET", `/v1/workspaces/${encodeURIComponent(this.options.workspaceId)}/connections`);
116
+ workspaceServices = new Set((res.connections ?? []).map((c) => c.service));
117
+ }
118
+ catch {
119
+ workspaceServices = new Set();
120
+ }
121
+ }
122
+ const statuses = [];
123
+ for (const conn of declared) {
124
+ if (conn.owner === "agent") {
125
+ if (agentServices?.has(conn.service)) {
126
+ statuses.push({ service: conn.service, owner: "agent", status: "satisfied", authType: "bearer_credential" });
127
+ continue;
128
+ }
129
+ if (await this.oauthConnected(conn.service)) {
130
+ statuses.push({ service: conn.service, owner: "agent", status: "satisfied", authType: "oauth" });
131
+ continue;
132
+ }
133
+ statuses.push({
134
+ service: conn.service, owner: "agent", status: "missing",
135
+ hint: `Store an API token for "${conn.service}" (tools.storeCredential / POST /v1/agents/me/credentials) or connect it via OAuth (/v1/oauth/${conn.service}/connect).`,
136
+ });
137
+ }
138
+ else {
139
+ if (!this.options.workspaceId) {
140
+ statuses.push({
141
+ service: conn.service, owner: "workspace", status: "missing",
142
+ hint: `Connection "${conn.service}" is workspace-owned but no workspaceId was provided — set it in PackLoaderOptions (SDK) or the pack block of nookplot.yaml (CLI).`,
143
+ });
144
+ continue;
145
+ }
146
+ if (workspaceServices?.has(conn.service)) {
147
+ statuses.push({ service: conn.service, owner: "workspace", status: "satisfied", authType: "workspace" });
148
+ }
149
+ else {
150
+ statuses.push({
151
+ service: conn.service, owner: "workspace", status: "missing",
152
+ hint: `Workspace ${this.options.workspaceId} has no "${conn.service}" connection — a workspace admin must add one (POST /v1/workspaces/:id/connections).`,
153
+ });
154
+ }
155
+ }
156
+ }
157
+ return statuses;
158
+ }
159
+ async oauthConnected(provider) {
160
+ try {
161
+ const res = await this.runtime.connection.request("GET", `/v1/oauth/${encodeURIComponent(provider)}/status`);
162
+ return res.connected === true;
163
+ }
164
+ catch {
165
+ return false;
166
+ }
167
+ }
168
+ // ── MCP server mounting ─────────────────────────────────────
169
+ async mountServers(pack, connections) {
170
+ const byService = new Map(connections.map((c) => [c.service, c]));
171
+ const statuses = [];
172
+ for (const server of pack.mcpServers ?? []) {
173
+ let auth;
174
+ if (server.connection) {
175
+ const conn = byService.get(server.connection);
176
+ if (!conn || conn.status !== "satisfied") {
177
+ statuses.push({
178
+ name: server.name, url: server.url, status: "skipped",
179
+ reason: `connection "${server.connection}" not satisfied${conn?.hint ? ` — ${conn.hint}` : ""}`,
180
+ });
181
+ continue;
182
+ }
183
+ if (conn.authType === "bearer_credential") {
184
+ auth = { authType: "bearer_credential", credentialService: conn.service };
185
+ }
186
+ else if (conn.authType === "oauth") {
187
+ auth = { authType: "oauth", oauthProvider: conn.service };
188
+ }
189
+ else {
190
+ auth = { authType: "workspace", credentialService: conn.service, workspaceId: this.options.workspaceId };
191
+ }
192
+ }
193
+ try {
194
+ const mounted = await this.runtime.tools.connectMcpServer(server.url, server.name, auth);
195
+ statuses.push({ name: server.name, url: server.url, status: "mounted", toolCount: mounted.toolCount });
196
+ }
197
+ catch (err) {
198
+ statuses.push({
199
+ name: server.name, url: server.url, status: "failed",
200
+ error: err instanceof Error ? err.message : String(err),
201
+ });
202
+ }
203
+ }
204
+ return statuses;
205
+ }
206
+ // ── Connector status ────────────────────────────────────────
207
+ async checkConnectors(pack) {
208
+ const statuses = [];
209
+ for (const connector of pack.connectors ?? []) {
210
+ const { platform, mode } = connector;
211
+ const descriptor = CONNECTOR_PLATFORMS[platform];
212
+ if (!descriptor.hasBindings) {
213
+ // e.g. email — outbound rides the agent's own inbox; nothing to check.
214
+ statuses.push({ platform, mode, status: "ready", detail: descriptor.readyDetail });
215
+ continue;
216
+ }
217
+ // Every bindings-bearing platform exposes the same contract on the
218
+ // shared connector core (Phase 4): GET /v1/<platform>/bindings.
219
+ let active = 0;
220
+ let detail;
221
+ try {
222
+ const res = await this.runtime.connection.request("GET", `/v1/${platform}/bindings`);
223
+ active = (res.bindings ?? []).filter((b) => b.status === "active").length;
224
+ detail = active > 0
225
+ ? `${active} active binding(s)`
226
+ : `no active ${descriptor.label} bindings — bind the agent via the ${descriptor.label} install flow`;
227
+ }
228
+ catch (err) {
229
+ detail = `binding lookup failed: ${err instanceof Error ? err.message : String(err)}`;
230
+ }
231
+ statuses.push({ platform, mode, status: active > 0 ? "bound" : "unbound", detail });
232
+ }
233
+ return statuses;
234
+ }
235
+ }
236
+ //# source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;YACX,CAAC;YACD,mEAAmE;YACnE,gEAAgE;YAChE,IAAI,MAAM,GAAG,CAAC,CAAC;YACf,IAAI,MAAc,CAAC;YACnB,IAAI,CAAC;gBACH,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,QAAQ,WAAW,CACzC,CAAC;gBAC3C,MAAM,GAAG,CAAC,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,MAAM,CAAC;gBAC1E,MAAM,GAAG,MAAM,GAAG,CAAC;oBACjB,CAAC,CAAC,GAAG,MAAM,oBAAoB;oBAC/B,CAAC,CAAC,aAAa,UAAU,CAAC,KAAK,sCAAsC,UAAU,CAAC,KAAK,eAAe,CAAC;YACzG,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,GAAG,0BAA0B,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;YACxF,CAAC;YACD,QAAQ,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QACtF,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF"}
@@ -0,0 +1,132 @@
1
+ /**
2
+ * PresetLoader — loads forge preset data into agent memory at boot.
3
+ *
4
+ * Reads the preset section of nookplot.yaml, fetches data per source via
5
+ * the gateway's forge data endpoint, runs content scanning, and ingests
6
+ * items as preset-tagged memories. Supports layered ingestion: RAG when
7
+ * available, memory.import() fallback.
8
+ *
9
+ * Features:
10
+ * - Content scanning (sanitizeForPrompt) on every item
11
+ * - Idempotent loading via .preset-loaded.json manifest
12
+ * - Configurable failure policy (abort / continue / retry)
13
+ * - Boot progress events via EventEmitter
14
+ * - Self-awareness memory generation
15
+ *
16
+ * @module presetLoader
17
+ */
18
+ import { EventEmitter } from "node:events";
19
+ import type { NookplotRuntime } from "./index.js";
20
+ export interface PresetConfig {
21
+ id: string;
22
+ version?: number;
23
+ trustLevel?: "verified" | "scanned" | "raw";
24
+ failurePolicy?: "abort" | "continue";
25
+ maxCostNook?: number;
26
+ sources?: Array<{
27
+ type: string;
28
+ label?: string;
29
+ config: Record<string, unknown>;
30
+ }>;
31
+ }
32
+ export interface PresetLoadResult {
33
+ sources: Array<{
34
+ type: string;
35
+ label: string;
36
+ itemsLoaded: number;
37
+ itemsBlocked: number;
38
+ itemsSkipped: number;
39
+ method: "memory" | "rag" | "prompt";
40
+ status: "loaded" | "partial" | "failed";
41
+ error?: string;
42
+ costNook: number;
43
+ }>;
44
+ totalItems: number;
45
+ totalBlocked: number;
46
+ totalCostNook: number;
47
+ ragAvailable: boolean;
48
+ presetVersion: number;
49
+ loadedAt: string;
50
+ }
51
+ export type PresetLoadEvent = {
52
+ phase: "estimating";
53
+ message: string;
54
+ } | {
55
+ phase: "fetching";
56
+ source: string;
57
+ progress: string;
58
+ } | {
59
+ phase: "scanning";
60
+ source: string;
61
+ blocked: number;
62
+ } | {
63
+ phase: "ingesting";
64
+ source: string;
65
+ method: "memory" | "rag";
66
+ } | {
67
+ phase: "complete";
68
+ result: PresetLoadResult;
69
+ } | {
70
+ phase: "error";
71
+ source: string;
72
+ error: string;
73
+ };
74
+ export declare class PresetLoader extends EventEmitter {
75
+ private runtime;
76
+ private configPath;
77
+ private loading;
78
+ /** When set, used instead of reading the `preset:` section of the config file (PackLoader delegation). */
79
+ private presetOverride;
80
+ constructor(runtime: NookplotRuntime, configPath?: string, presetOverride?: PresetConfig);
81
+ /**
82
+ * Build x-preset-hmac header so the gateway trusts isPreset/presetId fields.
83
+ * HMAC = SHA-256(apiKey, "preset-ingest:" + agent_address).
84
+ */
85
+ private presetIngestHeaders;
86
+ /**
87
+ * Load all preset data sources. Called once at agent boot.
88
+ * Concurrent calls are coalesced — only the first triggers a fetch,
89
+ * subsequent callers await the same promise (prevents double-pay).
90
+ */
91
+ load(): Promise<PresetLoadResult>;
92
+ private _doLoad;
93
+ /**
94
+ * Check if preset data was already loaded (idempotent reboot check).
95
+ */
96
+ isLoaded(): Promise<boolean>;
97
+ /**
98
+ * Map preset source type to knowledge graph knowledge_type.
99
+ */
100
+ private mapSourceToKnowledgeType;
101
+ /**
102
+ * Map preset source type to knowledge graph source_type.
103
+ */
104
+ private mapSourceToKGSourceType;
105
+ /**
106
+ * Ingest a KnowledgeAggregateV1 into the knowledge graph as structured items.
107
+ * Same decomposition as ingestAggregate but targets the KG endpoint.
108
+ */
109
+ private ingestAggregateToKG;
110
+ /**
111
+ * Ingest a KnowledgeAggregateV1 as structured memories.
112
+ * Uses 5-7x fewer memory slots than equivalent raw traces:
113
+ * - Synthesis → semantic memory (importance 0.9)
114
+ * - Each keyInsight → procedural memory (confidence-weighted)
115
+ * - Each reasoning pattern → procedural memory
116
+ * - Contradictions → self_model memory
117
+ *
118
+ * Returns the number of memories stored.
119
+ */
120
+ private ingestAggregate;
121
+ private readConfig;
122
+ private readManifest;
123
+ private writeManifest;
124
+ /**
125
+ * Lightweight client-side severity assessment.
126
+ * Full ContentScanner runs server-side; this is a first pass.
127
+ */
128
+ private assessSeverity;
129
+ private emptyResult;
130
+ private manifestToResult;
131
+ }
132
+ //# sourceMappingURL=presetLoader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presetLoader.d.ts","sourceRoot":"","sources":["../src/presetLoader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAIH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAKlD,MAAM,WAAW,YAAY;I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