@wheatley-ai/cli 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +180 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +204 -0
- package/dist/cli/session.js +87 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1020 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +61 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon.js +88 -0
- package/dist/core/deployment.js +347 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +95 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +206 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
- package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
- package/dist/dashboard/index.html +13 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +195 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +104 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +207 -0
- package/dist/triggers/webhook-ingress.js +216 -0
- package/dist/wiring/agent-services.js +144 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { isJsonValue } from "@wheatley-ai/protocol";
|
|
2
|
+
import { API_VERSION } from "@wheatley-ai/sdk";
|
|
3
|
+
const STANDARD_KEY = "~standard";
|
|
4
|
+
const STANDARD_VERSION = 1;
|
|
5
|
+
/** The message of a thrown value, for Agent health and logs. */
|
|
6
|
+
export const errorMessage = (cause) => cause instanceof Error ? cause.message : String(cause);
|
|
7
|
+
/** Returns true if `value` is a JSON object: a plain object whose values are all JSON values. */
|
|
8
|
+
export const isJsonObject = (value) => typeof value === "object" &&
|
|
9
|
+
value !== null &&
|
|
10
|
+
!Array.isArray(value) &&
|
|
11
|
+
isJsonValue(value);
|
|
12
|
+
const isStandardProps = (value) => typeof value === "object" &&
|
|
13
|
+
value !== null &&
|
|
14
|
+
"version" in value &&
|
|
15
|
+
value.version === STANDARD_VERSION &&
|
|
16
|
+
"jsonSchema" in value &&
|
|
17
|
+
typeof value.jsonSchema === "object" &&
|
|
18
|
+
value.jsonSchema !== null &&
|
|
19
|
+
"input" in value.jsonSchema &&
|
|
20
|
+
typeof value.jsonSchema.input === "function" &&
|
|
21
|
+
(!("validate" in value) ||
|
|
22
|
+
value.validate === undefined ||
|
|
23
|
+
typeof value.validate === "function");
|
|
24
|
+
/** Returns true if `value` implements Standard JSON Schema V1: a `~standard` property with a `jsonSchema.input` converter. */
|
|
25
|
+
export const isStandardSchemaValue = (value) => typeof value === "object" &&
|
|
26
|
+
value !== null &&
|
|
27
|
+
STANDARD_KEY in value &&
|
|
28
|
+
isStandardProps(value[STANDARD_KEY]);
|
|
29
|
+
/**
|
|
30
|
+
* Returns true if `value` is a schema that a Plugin can provide: a Standard JSON Schema V1 object, or a plain JSON
|
|
31
|
+
* Schema object with only JSON values. An object with a `~standard` property counts only as Standard JSON Schema.
|
|
32
|
+
*/
|
|
33
|
+
export const isSchemaInput = (value) => typeof value === "object" && value !== null && STANDARD_KEY in value
|
|
34
|
+
? isStandardSchemaValue(value)
|
|
35
|
+
: isJsonObject(value);
|
|
36
|
+
/** Returns true if `value` is an ES module namespace or object with a `default` property. */
|
|
37
|
+
export const hasDefaultExport = (value) => typeof value === "object" && value !== null && "default" in value;
|
|
38
|
+
/** Returns true if `value` is an object with an `apiVersion` property of any value. */
|
|
39
|
+
export const hasApiVersion = (value) => typeof value === "object" && value !== null && "apiVersion" in value;
|
|
40
|
+
/**
|
|
41
|
+
* Returns true if `value` has the runtime form of a `Plugin` of `@wheatley-ai/sdk`: `apiVersion` 1, `name` and `version`
|
|
42
|
+
* strings, a `setup` function, and an optional schema as `configSchema`. It does not check the name pattern.
|
|
43
|
+
*/
|
|
44
|
+
export const isPlugin = (value) => typeof value === "object" &&
|
|
45
|
+
value !== null &&
|
|
46
|
+
"apiVersion" in value &&
|
|
47
|
+
value.apiVersion === API_VERSION &&
|
|
48
|
+
"name" in value &&
|
|
49
|
+
typeof value.name === "string" &&
|
|
50
|
+
"version" in value &&
|
|
51
|
+
typeof value.version === "string" &&
|
|
52
|
+
"setup" in value &&
|
|
53
|
+
typeof value.setup === "function" &&
|
|
54
|
+
(!("configSchema" in value) ||
|
|
55
|
+
value.configSchema === undefined ||
|
|
56
|
+
isSchemaInput(value.configSchema));
|
|
57
|
+
/** Returns true if `value` has the runtime form of a `Tool` of `@wheatley-ai/sdk`. It does not check the name pattern. */
|
|
58
|
+
export const isPluginTool = (value) => typeof value === "object" &&
|
|
59
|
+
value !== null &&
|
|
60
|
+
"name" in value &&
|
|
61
|
+
typeof value.name === "string" &&
|
|
62
|
+
"description" in value &&
|
|
63
|
+
typeof value.description === "string" &&
|
|
64
|
+
"inputSchema" in value &&
|
|
65
|
+
isSchemaInput(value.inputSchema) &&
|
|
66
|
+
"execute" in value &&
|
|
67
|
+
typeof value.execute === "function";
|
|
68
|
+
/** Returns true if `value` has the runtime form of a `Frontend` of `@wheatley-ai/sdk`. */
|
|
69
|
+
export const isPluginFrontend = (value) => typeof value === "object" &&
|
|
70
|
+
value !== null &&
|
|
71
|
+
"type" in value &&
|
|
72
|
+
typeof value.type === "string" &&
|
|
73
|
+
"configSchema" in value &&
|
|
74
|
+
isSchemaInput(value.configSchema) &&
|
|
75
|
+
"createBinding" in value &&
|
|
76
|
+
typeof value.createBinding === "function";
|
|
77
|
+
/** Returns true if `value` is an object with a `dispose` function, valid contributions or not. */
|
|
78
|
+
export const hasDispose = (value) => typeof value === "object" &&
|
|
79
|
+
value !== null &&
|
|
80
|
+
"dispose" in value &&
|
|
81
|
+
typeof value.dispose === "function";
|
|
82
|
+
/** Returns true if `value` is an object whose `tools` and `frontends`, if present, are arrays. */
|
|
83
|
+
export const isContributionsObject = (value) => typeof value === "object" &&
|
|
84
|
+
value !== null &&
|
|
85
|
+
!Array.isArray(value) &&
|
|
86
|
+
(!("tools" in value) ||
|
|
87
|
+
value.tools === undefined ||
|
|
88
|
+
Array.isArray(value.tools)) &&
|
|
89
|
+
(!("frontends" in value) ||
|
|
90
|
+
value.frontends === undefined ||
|
|
91
|
+
Array.isArray(value.frontends));
|
|
92
|
+
const isToolContent = (block) => typeof block === "object" &&
|
|
93
|
+
block !== null &&
|
|
94
|
+
"type" in block &&
|
|
95
|
+
((block.type === "text" &&
|
|
96
|
+
"text" in block &&
|
|
97
|
+
typeof block.text === "string") ||
|
|
98
|
+
(block.type === "image" &&
|
|
99
|
+
"mimeType" in block &&
|
|
100
|
+
typeof block.mimeType === "string" &&
|
|
101
|
+
"data" in block &&
|
|
102
|
+
typeof block.data === "string"));
|
|
103
|
+
/** Returns true if a value that a Plugin Tool returned is a `ToolResult`. */
|
|
104
|
+
export const isToolResult = (value) => typeof value === "object" &&
|
|
105
|
+
value !== null &&
|
|
106
|
+
"content" in value &&
|
|
107
|
+
Array.isArray(value.content) &&
|
|
108
|
+
value.content.every(isToolContent) &&
|
|
109
|
+
(!("isError" in value) ||
|
|
110
|
+
value.isError === undefined ||
|
|
111
|
+
typeof value.isError === "boolean");
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { inspect } from "node:util";
|
|
5
|
+
import { API_VERSION } from "@wheatley-ai/sdk";
|
|
6
|
+
import { resolve as resolveModule } from "import-meta-resolve";
|
|
7
|
+
import { RESERVED_PLUGIN_NAME } from "../contracts/tool-names.js";
|
|
8
|
+
import { hasApiVersion, hasDefaultExport, isPlugin } from "./guards.js";
|
|
9
|
+
import { compileSchema } from "./schema.js";
|
|
10
|
+
const PLUGIN_NAME = /^[a-z][a-z0-9_-]*$/u;
|
|
11
|
+
const HOME_PREFIX = "~/";
|
|
12
|
+
const RELATIVE_PREFIXES = ["./", "../"];
|
|
13
|
+
/** The folder of the Deployment home that holds npm Plugin packages in its `node_modules/`. */
|
|
14
|
+
export const EXTENSIONS_DIR = "extensions";
|
|
15
|
+
const isLocalPath = (source) => path.isAbsolute(source) ||
|
|
16
|
+
source.startsWith(HOME_PREFIX) ||
|
|
17
|
+
RELATIVE_PREFIXES.some((prefix) => source.startsWith(prefix));
|
|
18
|
+
/**
|
|
19
|
+
* Resolves a Plugin `source` from `config.yaml` to the URL that `import()` loads.
|
|
20
|
+
*
|
|
21
|
+
* - An absolute path loads as is.
|
|
22
|
+
* - A path that starts with `~/` resolves against the user's home directory.
|
|
23
|
+
* - A path that starts with `./` or `../` resolves against `homeDir`.
|
|
24
|
+
* - Any other source is an npm package specifier, for example `wheatley-plugin-notes` or `@acme/wheatley-notes`. It
|
|
25
|
+
* resolves with the Node ESM algorithm from `<homeDir>/extensions/`, so it finds packages in
|
|
26
|
+
* `<homeDir>/extensions/node_modules/` and honors their `exports` field.
|
|
27
|
+
*
|
|
28
|
+
* Errors: throws if an npm package does not resolve, for example because it is not installed.
|
|
29
|
+
*/
|
|
30
|
+
export const resolvePluginUrl = (source, homeDir) => {
|
|
31
|
+
if (!isLocalPath(source)) {
|
|
32
|
+
const parent = `${pathToFileURL(path.join(homeDir, EXTENSIONS_DIR)).href}/`;
|
|
33
|
+
return resolveModule(source, parent);
|
|
34
|
+
}
|
|
35
|
+
const file = source.startsWith(HOME_PREFIX)
|
|
36
|
+
? path.join(homedir(), source.slice(HOME_PREFIX.length))
|
|
37
|
+
: path.resolve(homeDir, source);
|
|
38
|
+
return pathToFileURL(file).href;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Resolves and imports one Plugin module, then validates its default export against the `Plugin` contract of
|
|
42
|
+
* `@wheatley-ai/sdk`.
|
|
43
|
+
*
|
|
44
|
+
* Node caches modules by URL, so two Agents that list the same `source` share the module. Each Agent calls `setup`
|
|
45
|
+
* separately, so they share no Plugin instance (ADR 0006).
|
|
46
|
+
*
|
|
47
|
+
* Errors: rejects with a message for Agent health if the source does not resolve, the module throws on import, the
|
|
48
|
+
* module has no default export, `apiVersion` is not the integer `1`, the export breaks the `Plugin` contract, the name
|
|
49
|
+
* breaks `^[a-z][a-z0-9_-]*$` or is `mcp`, or `configSchema` does not compile.
|
|
50
|
+
*/
|
|
51
|
+
export const importPlugin = async (source, homeDir) => {
|
|
52
|
+
const module = await import(resolvePluginUrl(source, homeDir));
|
|
53
|
+
if (!hasDefaultExport(module)) {
|
|
54
|
+
throw new TypeError("The module has no default export");
|
|
55
|
+
}
|
|
56
|
+
const exported = module.default;
|
|
57
|
+
if (!hasApiVersion(exported)) {
|
|
58
|
+
throw new TypeError("The default export declares no apiVersion");
|
|
59
|
+
}
|
|
60
|
+
if (exported.apiVersion !== API_VERSION) {
|
|
61
|
+
throw new TypeError(`The Plugin declares apiVersion ${inspect(exported.apiVersion)}, but Wheatley supports only apiVersion ${API_VERSION}`);
|
|
62
|
+
}
|
|
63
|
+
if (!isPlugin(exported)) {
|
|
64
|
+
throw new TypeError("The default export breaks the Plugin contract: it needs name and version strings, a setup function, and an optional configSchema of plain JSON Schema or Standard JSON Schema");
|
|
65
|
+
}
|
|
66
|
+
if (!PLUGIN_NAME.test(exported.name) ||
|
|
67
|
+
exported.name === RESERVED_PLUGIN_NAME) {
|
|
68
|
+
throw new TypeError(`Invalid Plugin name ${inspect(exported.name)}: it must match ${PLUGIN_NAME.source} and must not be ${RESERVED_PLUGIN_NAME}`);
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
configSchema: exported.configSchema === undefined
|
|
72
|
+
? undefined
|
|
73
|
+
: compileSchema(exported.configSchema),
|
|
74
|
+
plugin: exported,
|
|
75
|
+
};
|
|
76
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createPluginProvider } from "./provider.js";
|
|
2
|
+
/** The Plugins module keeps no state in `agent.sqlite`. */
|
|
3
|
+
export const pluginMigrations = [];
|
|
4
|
+
/**
|
|
5
|
+
* The Plugins module handles no JSON-RPC method of its own. Plugin status reaches `extensions.list` and Agent health
|
|
6
|
+
* through `PluginProvider.health`, which the `ExtensionCatalog` merges with the other providers.
|
|
7
|
+
*/
|
|
8
|
+
export const pluginRpcHandlers = {};
|
|
9
|
+
/**
|
|
10
|
+
* The Plugins module of one Agent (ADR 0006). Its API is the `PluginProvider` of `createPluginProvider`.
|
|
11
|
+
*
|
|
12
|
+
* `create` loads the Plugins of `deps.config`. It never rejects because of a broken Plugin: that Plugin reports
|
|
13
|
+
* `failed` in `api.health()`, and the Agent starts without it. `stop` disposes every loaded Plugin.
|
|
14
|
+
*/
|
|
15
|
+
export const pluginsModule = {
|
|
16
|
+
create: async (ctx, deps) => {
|
|
17
|
+
const provider = await createPluginProvider({
|
|
18
|
+
agentDir: ctx.agentDir,
|
|
19
|
+
agentName: ctx.agentName,
|
|
20
|
+
config: deps.config,
|
|
21
|
+
homeDir: deps.homeDir,
|
|
22
|
+
log: ctx.log,
|
|
23
|
+
secrets: deps.secrets,
|
|
24
|
+
signal: deps.signal,
|
|
25
|
+
}, deps.options);
|
|
26
|
+
return { api: provider, rpc: pluginRpcHandlers, stop: provider.close };
|
|
27
|
+
},
|
|
28
|
+
migrations: pluginMigrations,
|
|
29
|
+
name: "plugins",
|
|
30
|
+
scope: "agent",
|
|
31
|
+
};
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isJsonValue } from "@wheatley-ai/protocol";
|
|
4
|
+
import { disposerOf, loadContributions } from "./contributions.js";
|
|
5
|
+
import { errorMessage, isToolResult } from "./guards.js";
|
|
6
|
+
import { importPlugin } from "./load.js";
|
|
7
|
+
/** The default time limit of one Plugin `setup` call. */
|
|
8
|
+
export const DEFAULT_SETUP_TIMEOUT_MS = 30_000;
|
|
9
|
+
/** The default time limit of one Plugin `dispose` call. */
|
|
10
|
+
export const DEFAULT_DISPOSE_TIMEOUT_MS = 10_000;
|
|
11
|
+
/** The folder of the Agent directory that holds one private data folder per Plugin. */
|
|
12
|
+
export const PLUGIN_DATA_DIR = "plugins";
|
|
13
|
+
const AGENT_STOPPED = "The Agent stopped while the Plugin loaded";
|
|
14
|
+
/** A Tool result that reports `text` as an error to the model. */
|
|
15
|
+
const toolErrorResult = (text) => ({
|
|
16
|
+
content: [{ text, type: "text" }],
|
|
17
|
+
isError: true,
|
|
18
|
+
});
|
|
19
|
+
const failed = (name, error) => ({
|
|
20
|
+
status: { error, name, state: "failed" },
|
|
21
|
+
});
|
|
22
|
+
const stopped = (name) => ({
|
|
23
|
+
status: { error: AGENT_STOPPED, name, state: "stopped" },
|
|
24
|
+
});
|
|
25
|
+
/**
|
|
26
|
+
* Settles with `work`, or rejects when `signal` aborts first. The abort reason becomes the rejection. Removes its
|
|
27
|
+
* listener when it settles.
|
|
28
|
+
*/
|
|
29
|
+
const raceAbort = async (work, signal) => {
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
const { promise: aborted, reject } = Promise.withResolvers();
|
|
32
|
+
const onAbort = () => {
|
|
33
|
+
reject(signal.reason);
|
|
34
|
+
};
|
|
35
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
36
|
+
try {
|
|
37
|
+
return await Promise.race([work, aborted]);
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
signal.removeEventListener("abort", onAbort);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
/** Starts `call` on a later microtask, so a synchronous throw becomes a rejection. */
|
|
44
|
+
const deferCall = async (call) => {
|
|
45
|
+
await Promise.resolve();
|
|
46
|
+
return await call();
|
|
47
|
+
};
|
|
48
|
+
const pluginLogger = (log, plugin) => ({
|
|
49
|
+
debug: (message, fields) => {
|
|
50
|
+
log.debug(message, { ...fields, plugin });
|
|
51
|
+
},
|
|
52
|
+
error: (message, fields) => {
|
|
53
|
+
log.error(message, { ...fields, plugin });
|
|
54
|
+
},
|
|
55
|
+
info: (message, fields) => {
|
|
56
|
+
log.info(message, { ...fields, plugin });
|
|
57
|
+
},
|
|
58
|
+
warn: (message, fields) => {
|
|
59
|
+
log.warn(message, { ...fields, plugin });
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
const prepareEntry = async (entry, homeDir) => {
|
|
63
|
+
if (entry.enabled === false) {
|
|
64
|
+
return {
|
|
65
|
+
kind: "done",
|
|
66
|
+
outcome: { status: { name: entry.source, state: "disabled" } },
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
const definition = await importPlugin(entry.source, homeDir);
|
|
71
|
+
return { definition, entry, kind: "defined" };
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
return { kind: "done", outcome: failed(entry.source, errorMessage(error)) };
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
/** Validates the `config` block of `entry` against the Plugin's `configSchema`. A missing block counts as `{}`. */
|
|
78
|
+
const checkPluginConfig = async (definition, entry) => {
|
|
79
|
+
const config = entry.config ?? {};
|
|
80
|
+
if (!isJsonValue(config)) {
|
|
81
|
+
return { message: "the config block is not JSON", ok: false };
|
|
82
|
+
}
|
|
83
|
+
return ((await definition.configSchema?.check(config)) ?? {
|
|
84
|
+
ok: true,
|
|
85
|
+
value: config,
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
/** Calls one Plugin's `dispose` with a time limit. Logs and swallows its errors. */
|
|
89
|
+
const disposePlugin = async (name, dispose, log, options) => {
|
|
90
|
+
try {
|
|
91
|
+
await raceAbort(deferCall(dispose), AbortSignal.timeout(options.disposeTimeoutMs));
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
log.warn("Plugin dispose failed", {
|
|
95
|
+
error: errorMessage(error),
|
|
96
|
+
plugin: name,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Waits for a `setup` call that lost the race against its time limit or the Agent stop, and disposes what it returns
|
|
102
|
+
* late. Logs and swallows a late rejection.
|
|
103
|
+
*/
|
|
104
|
+
const disposeLate = async (pending, log) => {
|
|
105
|
+
try {
|
|
106
|
+
await disposerOf(await pending)();
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
log.debug("Plugin setup failed after its time limit or the Agent stop", {
|
|
110
|
+
error: errorMessage(error),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
/** Waits for one late disposal up to the dispose time limit. Logs and swallows a timeout. */
|
|
115
|
+
const disposeWithin = async (late, log, options) => {
|
|
116
|
+
try {
|
|
117
|
+
await raceAbort(late, AbortSignal.timeout(options.disposeTimeoutMs));
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
log.warn("A late Plugin setup did not finish before close", {
|
|
121
|
+
error: errorMessage(error),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const setupTimeoutMessage = (options) => `Plugin setup timed out after ${options.setupTimeoutMs} ms`;
|
|
126
|
+
/**
|
|
127
|
+
* Calls `setup` of one Plugin with a time limit and validates what it returns. If `setup` resolves after the time
|
|
128
|
+
* limit or after the Agent stopped, the late contributions are disposed.
|
|
129
|
+
*/
|
|
130
|
+
const setupPlugin = async (definition, entry, { provider, options, lateDisposals }) => {
|
|
131
|
+
const { name } = definition.plugin;
|
|
132
|
+
const log = pluginLogger(provider.log, name);
|
|
133
|
+
const config = await checkPluginConfig(definition, entry);
|
|
134
|
+
if (!config.ok) {
|
|
135
|
+
return failed(name, `Invalid Plugin config: ${config.message}`);
|
|
136
|
+
}
|
|
137
|
+
const controller = new AbortController();
|
|
138
|
+
const { signal } = controller;
|
|
139
|
+
const onStop = () => {
|
|
140
|
+
controller.abort(provider.signal.reason);
|
|
141
|
+
};
|
|
142
|
+
const timer = setTimeout(() => {
|
|
143
|
+
controller.abort(new Error(setupTimeoutMessage(options)));
|
|
144
|
+
}, options.setupTimeoutMs);
|
|
145
|
+
const dataDir = path.join(provider.agentDir, PLUGIN_DATA_DIR, name);
|
|
146
|
+
let returned;
|
|
147
|
+
provider.signal.addEventListener("abort", onStop, { once: true });
|
|
148
|
+
try {
|
|
149
|
+
await mkdir(dataDir, { recursive: true });
|
|
150
|
+
const pending = deferCall(async () => await definition.plugin.setup({
|
|
151
|
+
agentName: provider.agentName,
|
|
152
|
+
config: config.value,
|
|
153
|
+
dataDir,
|
|
154
|
+
log,
|
|
155
|
+
secrets: provider.secrets,
|
|
156
|
+
signal,
|
|
157
|
+
}));
|
|
158
|
+
try {
|
|
159
|
+
returned = await raceAbort(pending, signal);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (signal.aborted) {
|
|
163
|
+
lateDisposals.push(disposeLate(pending, log));
|
|
164
|
+
}
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (provider.signal.aborted) {
|
|
170
|
+
return stopped(name);
|
|
171
|
+
}
|
|
172
|
+
return failed(name, signal.aborted
|
|
173
|
+
? setupTimeoutMessage(options)
|
|
174
|
+
: `Plugin setup failed: ${errorMessage(error)}`);
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
provider.signal.removeEventListener("abort", onStop);
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
const contributions = loadContributions(name, returned);
|
|
182
|
+
return {
|
|
183
|
+
plugin: { contributions, name },
|
|
184
|
+
status: { name, state: "ready" },
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
await disposePlugin(name, disposerOf(returned), provider.log, options);
|
|
189
|
+
return failed(name, errorMessage(error));
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
/** Fails the later of two Plugin entries with the same Plugin name, in config order. */
|
|
193
|
+
const dedupeNames = (prepared) => {
|
|
194
|
+
const seen = new Set();
|
|
195
|
+
return prepared.map((item) => {
|
|
196
|
+
if (item.kind === "done") {
|
|
197
|
+
return item;
|
|
198
|
+
}
|
|
199
|
+
const { name } = item.definition.plugin;
|
|
200
|
+
if (seen.has(name)) {
|
|
201
|
+
return {
|
|
202
|
+
kind: "done",
|
|
203
|
+
outcome: failed(name, `Another plugins entry already loaded a Plugin named ${name} (source ${item.entry.source})`),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
seen.add(name);
|
|
207
|
+
return item;
|
|
208
|
+
});
|
|
209
|
+
};
|
|
210
|
+
/** Fails a later Plugin that contributes a Frontend `type` that an earlier Plugin contributes, in config order. */
|
|
211
|
+
const dedupeFrontends = async (outcomes, input) => {
|
|
212
|
+
const owners = new Map();
|
|
213
|
+
const rejected = [];
|
|
214
|
+
const result = [];
|
|
215
|
+
for (const outcome of outcomes) {
|
|
216
|
+
const { plugin } = outcome;
|
|
217
|
+
if (plugin === undefined) {
|
|
218
|
+
result.push(outcome);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const { frontends } = plugin.contributions;
|
|
222
|
+
const taken = frontends
|
|
223
|
+
.map(({ type }) => ({ owner: owners.get(type), type }))
|
|
224
|
+
.find(({ owner }) => owner !== undefined);
|
|
225
|
+
if (taken?.owner !== undefined) {
|
|
226
|
+
rejected.push(plugin);
|
|
227
|
+
result.push(failed(plugin.name, `Plugin ${taken.owner} already contributes the Frontend type ${taken.type}`));
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
for (const { type } of frontends) {
|
|
231
|
+
owners.set(type, plugin.name);
|
|
232
|
+
}
|
|
233
|
+
result.push(outcome);
|
|
234
|
+
}
|
|
235
|
+
await Promise.all(rejected.map(async ({ name, contributions }) => {
|
|
236
|
+
await disposePlugin(name, contributions.dispose, input.provider.log, input.options);
|
|
237
|
+
}));
|
|
238
|
+
return result;
|
|
239
|
+
};
|
|
240
|
+
const loadEntries = async (input) => {
|
|
241
|
+
const entries = input.provider.config.plugins ?? [];
|
|
242
|
+
const prepared = dedupeNames(await Promise.all(entries.map(async (entry) => await prepareEntry(entry, input.provider.homeDir))));
|
|
243
|
+
const outcomes = await Promise.all(prepared.map(async (item) => {
|
|
244
|
+
if (item.kind === "done") {
|
|
245
|
+
return item.outcome;
|
|
246
|
+
}
|
|
247
|
+
if (input.provider.signal.aborted) {
|
|
248
|
+
return stopped(item.definition.plugin.name);
|
|
249
|
+
}
|
|
250
|
+
return await setupPlugin(item.definition, item.entry, input);
|
|
251
|
+
}));
|
|
252
|
+
return await dedupeFrontends(outcomes, input);
|
|
253
|
+
};
|
|
254
|
+
const runTool = async (tool, input, ctx) => {
|
|
255
|
+
const { name } = tool.descriptor;
|
|
256
|
+
const checked = await raceAbort(tool.schema.check(input), ctx.signal);
|
|
257
|
+
if (!checked.ok) {
|
|
258
|
+
return toolErrorResult(`Invalid input for ${name}: ${checked.message}`);
|
|
259
|
+
}
|
|
260
|
+
const result = await raceAbort(deferCall(async () => await tool.tool.execute(checked.value, ctx)), ctx.signal);
|
|
261
|
+
return isToolResult(result)
|
|
262
|
+
? result
|
|
263
|
+
: toolErrorResult(`${name} returned a result that is not a ToolResult`);
|
|
264
|
+
};
|
|
265
|
+
/**
|
|
266
|
+
* Loads the Plugins of one Agent from `input.config.plugins` and returns the `PluginProvider` over them (ADR 0006).
|
|
267
|
+
*
|
|
268
|
+
* Loading:
|
|
269
|
+
* - Each entry with `enabled: false` reports `disabled` under its `source` and does not import.
|
|
270
|
+
* - The provider imports every other entry (see `resolvePluginUrl`) and validates the default export against the
|
|
271
|
+
* `Plugin` contract, including the integer `apiVersion: 1`. Imports run in parallel.
|
|
272
|
+
* - It validates the entry's `config` block (`{}` if absent) against `configSchema`, creates the data folder
|
|
273
|
+
* `<agentDir>/plugins/<name>/`, and calls `setup` with a time limit. Setups run in parallel.
|
|
274
|
+
* - It names each Tool `<plugin>:<tool>` and collects Frontends by `type`. If two entries load the same Plugin name or
|
|
275
|
+
* contribute the same Frontend `type`, the later entry in config order fails.
|
|
276
|
+
*
|
|
277
|
+
* Invariants: one broken Plugin never rejects this function and never removes another Plugin. It contributes no Tools
|
|
278
|
+
* or Frontends, and `health` reports it as `failed` with its error under its Plugin name, or under its `source` if the
|
|
279
|
+
* module did not load. `health` lists the entries in config order. If `input.signal` aborts during loading, the
|
|
280
|
+
* Plugins that did not finish report `stopped`.
|
|
281
|
+
*
|
|
282
|
+
* `close` runs once. It disposes every loaded Plugin and each `setup` that finished after its time limit or the Agent
|
|
283
|
+
* stop, and waits up to the dispose time limit for each.
|
|
284
|
+
*
|
|
285
|
+
* Errors: rejects only for defects in the provider itself.
|
|
286
|
+
*/
|
|
287
|
+
export const createPluginProvider = async (input, options = {}) => {
|
|
288
|
+
const limits = {
|
|
289
|
+
disposeTimeoutMs: options.disposeTimeoutMs ?? DEFAULT_DISPOSE_TIMEOUT_MS,
|
|
290
|
+
setupTimeoutMs: options.setupTimeoutMs ?? DEFAULT_SETUP_TIMEOUT_MS,
|
|
291
|
+
};
|
|
292
|
+
const lateDisposals = [];
|
|
293
|
+
const outcomes = await loadEntries({
|
|
294
|
+
lateDisposals,
|
|
295
|
+
options: limits,
|
|
296
|
+
provider: input,
|
|
297
|
+
});
|
|
298
|
+
for (const { status } of outcomes) {
|
|
299
|
+
if (status.state === "failed") {
|
|
300
|
+
input.log.warn("Plugin failed to load", {
|
|
301
|
+
error: status.error ?? "",
|
|
302
|
+
plugin: status.name,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const plugins = outcomes.flatMap(({ plugin }) => plugin === undefined ? [] : [plugin]);
|
|
307
|
+
const tools = new Map(plugins.flatMap(({ contributions }) => contributions.tools.map((tool) => [tool.descriptor.name, tool])));
|
|
308
|
+
const frontends = plugins.flatMap(({ contributions }) => contributions.frontends);
|
|
309
|
+
let statuses = outcomes.map(({ status }) => status);
|
|
310
|
+
let closing;
|
|
311
|
+
const close = async () => {
|
|
312
|
+
closing ??= (async () => {
|
|
313
|
+
statuses = statuses.map((status) => status.state === "ready"
|
|
314
|
+
? { name: status.name, state: "stopped" }
|
|
315
|
+
: status);
|
|
316
|
+
await Promise.all([
|
|
317
|
+
...plugins.map(async ({ name, contributions }) => {
|
|
318
|
+
await disposePlugin(name, contributions.dispose, input.log, limits);
|
|
319
|
+
}),
|
|
320
|
+
...lateDisposals.map(async (late) => {
|
|
321
|
+
await disposeWithin(late, input.log, limits);
|
|
322
|
+
}),
|
|
323
|
+
]);
|
|
324
|
+
})();
|
|
325
|
+
await closing;
|
|
326
|
+
};
|
|
327
|
+
return {
|
|
328
|
+
close,
|
|
329
|
+
execute: async (name, toolInput, ctx) => {
|
|
330
|
+
const tool = closing === undefined ? tools.get(name) : undefined;
|
|
331
|
+
if (tool === undefined) {
|
|
332
|
+
return toolErrorResult(`Unknown Tool: ${name}`);
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
return await runTool(tool, toolInput, ctx);
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
return ctx.signal.aborted
|
|
339
|
+
? toolErrorResult(`${name} was aborted`)
|
|
340
|
+
: toolErrorResult(`${name} failed: ${errorMessage(error)}`);
|
|
341
|
+
}
|
|
342
|
+
},
|
|
343
|
+
frontends: () => closing === undefined ? frontends : [],
|
|
344
|
+
health: () => statuses,
|
|
345
|
+
tools: () => closing === undefined
|
|
346
|
+
? [...tools.values()].map((tool) => tool.descriptor)
|
|
347
|
+
: [],
|
|
348
|
+
};
|
|
349
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
2
|
+
import { isStandardJsonSchema } from "@wheatley-ai/sdk";
|
|
3
|
+
import { errorMessage, isJsonObject } from "./guards.js";
|
|
4
|
+
const JSON_SCHEMA_TARGET = "draft-2020-12";
|
|
5
|
+
const formatErrors = (errors) => errors.map((error) => `${error.path || "/"}: ${error.message}`).join("; ");
|
|
6
|
+
/** Compiles plain JSON Schema with pi-schema. Throws if the schema is malformed or has an unresolved `$ref`. */
|
|
7
|
+
const jsonValidator = (jsonSchema) => {
|
|
8
|
+
const validator = compile(jsonSchema);
|
|
9
|
+
return (value) => {
|
|
10
|
+
const result = validator.validate(value);
|
|
11
|
+
return result.ok
|
|
12
|
+
? { ok: true, value: result.value }
|
|
13
|
+
: { message: formatErrors(result.errors), ok: false };
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
const isKeyObject = (segment) => typeof segment === "object";
|
|
17
|
+
const formatIssue = (issue) => {
|
|
18
|
+
const segments = (issue.path ?? []).map((segment) => String(isKeyObject(segment) ? segment.key : segment));
|
|
19
|
+
return `/${segments.join("/")}: ${issue.message}`;
|
|
20
|
+
};
|
|
21
|
+
const standardCheck = (result) => result.issues === undefined
|
|
22
|
+
? { ok: true, value: result.value }
|
|
23
|
+
: { message: result.issues.map(formatIssue).join("; "), ok: false };
|
|
24
|
+
const compileStandard = (schema) => {
|
|
25
|
+
const props = schema["~standard"];
|
|
26
|
+
const converted = props.jsonSchema.input({ target: JSON_SCHEMA_TARGET });
|
|
27
|
+
if (!isJsonObject(converted)) {
|
|
28
|
+
throw new TypeError("The Standard JSON Schema converter did not return a JSON object");
|
|
29
|
+
}
|
|
30
|
+
// Compiling also rejects a converted schema that the model provider could not read.
|
|
31
|
+
const checkJson = jsonValidator(converted);
|
|
32
|
+
return {
|
|
33
|
+
check: async (value) => props.validate === undefined
|
|
34
|
+
? checkJson(value)
|
|
35
|
+
: standardCheck(await props.validate(value)),
|
|
36
|
+
jsonSchema: converted,
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Compiles a schema that a Plugin provided for Tool input or for configuration: plain JSON Schema or a Standard JSON
|
|
41
|
+
* Schema V1 object (ADR 0006).
|
|
42
|
+
*
|
|
43
|
+
* Plain JSON Schema validates with `@earendil-works/pi-schema` and passes to the model provider unchanged. A Standard
|
|
44
|
+
* JSON Schema converts to draft 2020-12 for the model provider. It validates with its own Standard Schema validator if
|
|
45
|
+
* it has one, so library refinements and transforms apply, and with the converted JSON Schema otherwise.
|
|
46
|
+
*
|
|
47
|
+
* Errors: throws a `TypeError` with a message for Agent health if the converter fails or the JSON Schema is
|
|
48
|
+
* malformed.
|
|
49
|
+
*/
|
|
50
|
+
export const compileSchema = (schema) => {
|
|
51
|
+
try {
|
|
52
|
+
if (isStandardJsonSchema(schema)) {
|
|
53
|
+
return compileStandard(schema);
|
|
54
|
+
}
|
|
55
|
+
const checkJson = jsonValidator(schema);
|
|
56
|
+
return {
|
|
57
|
+
check: async (value) => {
|
|
58
|
+
await Promise.resolve();
|
|
59
|
+
return checkJson(value);
|
|
60
|
+
},
|
|
61
|
+
jsonSchema: schema,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
throw new TypeError(`Invalid schema: ${errorMessage(error)}`, {
|
|
66
|
+
cause: error,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
};
|