openclaw-cloudflare-vectorize-memory 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -1
- package/cli-metadata.ts +26 -18
- package/dist/cli.js +60 -43
- package/dist/cli.js.map +1 -1
- package/dist/doctor.js +29 -9
- package/dist/doctor.js.map +1 -1
- package/dist/service.js +222 -20
- package/dist/service.js.map +1 -1
- package/dist/types/service.d.ts +13 -2
- package/dist/types/types.d.ts +20 -0
- package/dist/types/vectorize-client.d.ts +1 -0
- package/dist/vectorize-client.js +7 -0
- package/dist/vectorize-client.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -123,16 +123,30 @@ You can also store `cloudflare.apiToken` as an OpenClaw secret ref instead of pl
|
|
|
123
123
|
|
|
124
124
|
Run:
|
|
125
125
|
|
|
126
|
+
```bash
|
|
127
|
+
openclaw cf-memory init
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
to create or repair the configured Vectorize index so it matches the active embedding model dimensions.
|
|
131
|
+
|
|
132
|
+
Validate configuration without changing infrastructure:
|
|
133
|
+
|
|
126
134
|
```bash
|
|
127
135
|
openclaw cf-memory doctor
|
|
128
136
|
```
|
|
129
137
|
|
|
130
|
-
|
|
138
|
+
Validate configuration and create the Vectorize index when missing:
|
|
131
139
|
|
|
132
140
|
```bash
|
|
133
141
|
openclaw cf-memory doctor --create-index
|
|
134
142
|
```
|
|
135
143
|
|
|
144
|
+
Run an end-to-end smoke test that verifies embedding, write, search, and cleanup:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
openclaw cf-memory test
|
|
148
|
+
```
|
|
149
|
+
|
|
136
150
|
The doctor flow checks:
|
|
137
151
|
|
|
138
152
|
- Cloudflare credentials
|
|
@@ -143,6 +157,18 @@ The doctor flow checks:
|
|
|
143
157
|
|
|
144
158
|
## CLI usage
|
|
145
159
|
|
|
160
|
+
Initialize or repair the Vectorize index:
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
openclaw cf-memory init
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Run a smoke test:
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
openclaw cf-memory test
|
|
170
|
+
```
|
|
171
|
+
|
|
146
172
|
Migrate the default OpenClaw markdown memory corpus from the current workspace:
|
|
147
173
|
|
|
148
174
|
```bash
|
package/cli-metadata.ts
CHANGED
|
@@ -1,18 +1,26 @@
|
|
|
1
|
-
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
2
|
-
|
|
3
|
-
export default definePluginEntry({
|
|
4
|
-
id: "memory-cloudflare-vectorize",
|
|
5
|
-
name: "Cloudflare Vectorize Memory",
|
|
6
|
-
description: "OpenClaw memory plugin backed by Cloudflare Vectorize and Workers AI embeddings.",
|
|
7
|
-
register(api) {
|
|
8
|
-
api.registerCli(() => {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
|
|
1
|
+
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
2
|
+
|
|
3
|
+
export default definePluginEntry({
|
|
4
|
+
id: "memory-cloudflare-vectorize",
|
|
5
|
+
name: "Cloudflare Vectorize Memory",
|
|
6
|
+
description: "OpenClaw memory plugin backed by Cloudflare Vectorize and Workers AI embeddings.",
|
|
7
|
+
register(api) {
|
|
8
|
+
api.registerCli(async ({ program }) => {
|
|
9
|
+
const cliModulePath = "./dist/cli.js";
|
|
10
|
+
const { registerCloudflareMemoryCli }: typeof import("./src/cli.js") = await import(cliModulePath);
|
|
11
|
+
registerCloudflareMemoryCli(program, {
|
|
12
|
+
pluginConfig: api.pluginConfig,
|
|
13
|
+
openClawConfig: api.config,
|
|
14
|
+
resolvePath: api.resolvePath,
|
|
15
|
+
});
|
|
16
|
+
}, {
|
|
17
|
+
descriptors: [
|
|
18
|
+
{
|
|
19
|
+
name: "cf-memory",
|
|
20
|
+
description: "Manage Cloudflare Vectorize memory",
|
|
21
|
+
hasSubcommands: true,
|
|
22
|
+
},
|
|
23
|
+
],
|
|
24
|
+
});
|
|
25
|
+
},
|
|
26
|
+
});
|
package/dist/cli.js
CHANGED
|
@@ -5,23 +5,26 @@ function r(e) {
|
|
|
5
5
|
console.log(JSON.stringify(e, null, 2));
|
|
6
6
|
}
|
|
7
7
|
function i(e) {
|
|
8
|
+
for (let t of e.checks) console.log(`[${t.status}] ${t.name}: ${t.message}`);
|
|
9
|
+
}
|
|
10
|
+
function a(e) {
|
|
8
11
|
if (!e) return;
|
|
9
12
|
let t = JSON.parse(e);
|
|
10
13
|
if (!t || typeof t != "object" || Array.isArray(t)) throw Error("--metadata must be a JSON object.");
|
|
11
14
|
return t;
|
|
12
15
|
}
|
|
13
|
-
function
|
|
16
|
+
function o(e) {
|
|
14
17
|
if (!e) return;
|
|
15
18
|
let t = JSON.parse(e);
|
|
16
19
|
if (!t || typeof t != "object" || Array.isArray(t)) throw Error("--filter must be a JSON object.");
|
|
17
20
|
return t;
|
|
18
21
|
}
|
|
19
|
-
function
|
|
22
|
+
function s(e) {
|
|
20
23
|
return !!e && typeof e == "object" && typeof e.opts == "function";
|
|
21
24
|
}
|
|
22
|
-
function
|
|
25
|
+
function c(e) {
|
|
23
26
|
let t = e.at(-1);
|
|
24
|
-
return
|
|
27
|
+
return s(t) ? {
|
|
25
28
|
positionals: e.slice(0, -1),
|
|
26
29
|
options: t.opts?.() ?? {}
|
|
27
30
|
} : {
|
|
@@ -29,83 +32,97 @@ function s(e) {
|
|
|
29
32
|
options: {}
|
|
30
33
|
};
|
|
31
34
|
}
|
|
32
|
-
function
|
|
35
|
+
function l(e) {
|
|
33
36
|
if (e !== void 0) {
|
|
34
37
|
if (e === "overwrite" || e === "skip" || e === "fail") return e;
|
|
35
38
|
throw Error("--if-exists must be overwrite, skip, or fail.");
|
|
36
39
|
}
|
|
37
40
|
}
|
|
38
|
-
function
|
|
39
|
-
let
|
|
40
|
-
function
|
|
41
|
-
return
|
|
41
|
+
function u(s, u) {
|
|
42
|
+
let d = s.command("cf-memory").description("Manage Cloudflare memory records.");
|
|
43
|
+
function f(e) {
|
|
44
|
+
return c(e).options;
|
|
42
45
|
}
|
|
43
|
-
|
|
44
|
-
let t =
|
|
45
|
-
pluginConfig:
|
|
46
|
-
openClawConfig:
|
|
46
|
+
d.command("doctor").description("Validate Workers AI and Vectorize configuration.").option("--create-index", "Create the Vectorize index if missing.").option("--json", "Print structured JSON output.").action(async (...e) => {
|
|
47
|
+
let t = f(e), a = await (await n({
|
|
48
|
+
pluginConfig: u.pluginConfig,
|
|
49
|
+
openClawConfig: u.openClawConfig,
|
|
47
50
|
env: process.env,
|
|
48
|
-
resolvePath:
|
|
51
|
+
resolvePath: u.resolvePath
|
|
49
52
|
})).doctor({ createIndexIfMissing: !!t.createIndex });
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
t.json ? r(a) : i(a), a.ok || (process.exitCode = 1);
|
|
54
|
+
}), d.command("init").description("Initialize the Cloudflare Vectorize index for the configured embedding model.").option("--json", "Print structured JSON output.").action(async (...e) => {
|
|
55
|
+
let t = f(e), a = await (await n({
|
|
56
|
+
pluginConfig: u.pluginConfig,
|
|
57
|
+
openClawConfig: u.openClawConfig,
|
|
58
|
+
env: process.env,
|
|
59
|
+
resolvePath: u.resolvePath
|
|
60
|
+
})).initializeIndex();
|
|
61
|
+
t.json ? r(a) : i(a), a.ok || (process.exitCode = 1);
|
|
62
|
+
}), d.command("test").description("Run an end-to-end embedding and semantic-search smoke test.").option("--json", "Print structured JSON output.").action(async (...e) => {
|
|
63
|
+
let t = f(e), a = await (await n({
|
|
64
|
+
pluginConfig: u.pluginConfig,
|
|
65
|
+
openClawConfig: u.openClawConfig,
|
|
66
|
+
env: process.env,
|
|
67
|
+
resolvePath: u.resolvePath
|
|
68
|
+
})).runSmokeTest();
|
|
69
|
+
t.json ? r(a) : i(a), a.ok || (process.exitCode = 1);
|
|
70
|
+
}), d.command("search").description("Search stored Cloudflare memory.").argument("<query>", "Semantic search query.").option("--namespace <namespace>", "Optional namespace override.").option("--limit <count>", "Maximum number of results.").option("--filter <json>", "Optional metadata filter JSON.").action(async (e, t) => {
|
|
54
71
|
let i = t;
|
|
55
72
|
r(await (await n({
|
|
56
|
-
pluginConfig:
|
|
57
|
-
openClawConfig:
|
|
73
|
+
pluginConfig: u.pluginConfig,
|
|
74
|
+
openClawConfig: u.openClawConfig,
|
|
58
75
|
env: process.env,
|
|
59
|
-
resolvePath:
|
|
76
|
+
resolvePath: u.resolvePath
|
|
60
77
|
})).search({
|
|
61
78
|
query: String(e),
|
|
62
79
|
namespace: i.namespace,
|
|
63
80
|
maxResults: i.limit ? Number(i.limit) : void 0,
|
|
64
|
-
filter:
|
|
81
|
+
filter: o(i.filter)
|
|
65
82
|
}));
|
|
66
|
-
}),
|
|
67
|
-
let
|
|
83
|
+
}), d.command("upsert").description("Insert or update a memory record.").argument("<text>", "Memory text.").option("--id <id>", "Stable logical id.").option("--title <title>", "Optional title.").option("--namespace <namespace>", "Optional namespace override.").option("--source <source>", "Optional source label.").option("--metadata <json>", "Optional metadata JSON object.").action(async (e, t) => {
|
|
84
|
+
let i = t;
|
|
68
85
|
r(await (await n({
|
|
69
|
-
pluginConfig:
|
|
70
|
-
openClawConfig:
|
|
86
|
+
pluginConfig: u.pluginConfig,
|
|
87
|
+
openClawConfig: u.openClawConfig,
|
|
71
88
|
env: process.env,
|
|
72
|
-
resolvePath:
|
|
89
|
+
resolvePath: u.resolvePath
|
|
73
90
|
})).upsert({ input: {
|
|
74
|
-
id:
|
|
75
|
-
title:
|
|
91
|
+
id: i.id,
|
|
92
|
+
title: i.title,
|
|
76
93
|
text: String(e),
|
|
77
|
-
namespace:
|
|
78
|
-
source:
|
|
79
|
-
metadata: i
|
|
94
|
+
namespace: i.namespace,
|
|
95
|
+
source: i.source,
|
|
96
|
+
metadata: a(i.metadata)
|
|
80
97
|
} }));
|
|
81
|
-
}),
|
|
98
|
+
}), d.command("delete").description("Delete a memory record.").argument("<id>", "Logical memory record id.").option("--namespace <namespace>", "Optional namespace override.").action(async (e, t) => {
|
|
82
99
|
let i = t;
|
|
83
100
|
r({
|
|
84
101
|
id: e,
|
|
85
102
|
mutationId: await (await n({
|
|
86
|
-
pluginConfig:
|
|
87
|
-
openClawConfig:
|
|
103
|
+
pluginConfig: u.pluginConfig,
|
|
104
|
+
openClawConfig: u.openClawConfig,
|
|
88
105
|
env: process.env,
|
|
89
|
-
resolvePath:
|
|
106
|
+
resolvePath: u.resolvePath
|
|
90
107
|
})).delete({
|
|
91
108
|
id: String(e),
|
|
92
109
|
namespace: i.namespace
|
|
93
110
|
})
|
|
94
111
|
});
|
|
95
|
-
}),
|
|
96
|
-
let { positionals: a, options: o } =
|
|
112
|
+
}), d.command("migrate").description("Migrate legacy markdown memory into Cloudflare Vectorize.").argument("[sources...]", "Markdown files, directories, or glob patterns. Defaults to the current OpenClaw memory corpus when omitted.").option("--workspace <path>", "Workspace root used for default-provider discovery and relative path normalization.").option("--namespace <namespace>", "Target namespace override.").option("--derive-namespace-from-path", "Derive namespaces from the first relative path segment instead of using a single target namespace.").option("--if-exists <strategy>", "Duplicate handling: overwrite, skip, or fail.").option("--create-index", "Create the Vectorize index if missing.").option("--dry-run", "Plan the migration without writing records.").option("--json", "Print structured JSON output.").action(async (...i) => {
|
|
113
|
+
let { positionals: a, options: o } = c(i), s = a[0], d = a.length === 0 ? [] : Array.isArray(s) ? s.map((e) => String(e)) : a.map((e) => String(e)), f = await t({
|
|
97
114
|
service: await n({
|
|
98
|
-
pluginConfig:
|
|
99
|
-
openClawConfig:
|
|
115
|
+
pluginConfig: u.pluginConfig,
|
|
116
|
+
openClawConfig: u.openClawConfig,
|
|
100
117
|
env: process.env,
|
|
101
|
-
resolvePath:
|
|
118
|
+
resolvePath: u.resolvePath
|
|
102
119
|
}),
|
|
103
120
|
options: {
|
|
104
121
|
sourcePaths: d,
|
|
105
122
|
workspaceDir: o.workspace,
|
|
106
123
|
namespace: o.namespace,
|
|
107
124
|
namespaceStrategy: o.deriveNamespaceFromPath ? "path" : "single-target",
|
|
108
|
-
duplicateStrategy:
|
|
125
|
+
duplicateStrategy: l(o.ifExists),
|
|
109
126
|
dryRun: !!o.dryRun,
|
|
110
127
|
createIndexIfMissing: !!o.createIndex
|
|
111
128
|
}
|
|
@@ -114,6 +131,6 @@ function l(o, l) {
|
|
|
114
131
|
});
|
|
115
132
|
}
|
|
116
133
|
//#endregion
|
|
117
|
-
export {
|
|
134
|
+
export { u as registerCloudflareMemoryCli };
|
|
118
135
|
|
|
119
136
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import type { OpenClawConfig } from \"openclaw/plugin-sdk/config-runtime\";\nimport type { MigrationDuplicateStrategy } from \"./types.js\";\nimport { formatMigrationSummary, runCloudflareMemoryMigration } from \"./migration.js\";\nimport { createCloudflareMemoryService } from \"./service-factory.js\";\nimport type { MetadataFilter } from \"./types.js\";\n\ntype CliCommand = {\n\tcommand: (name: string) => CliCommand;\n\tdescription: (description: string) => CliCommand;\n\targument: (name: string, description: string) => CliCommand;\n\toption: (flags: string, description: string) => CliCommand;\n\taction: (handler: (...args: unknown[]) => Promise<void> | void) => CliCommand;\n\topts?: () => Record<string, unknown>;\n};\n\nfunction printJson(value: unknown): void {\n\tconsole.log(JSON.stringify(value, null, 2));\n}\n\nfunction parseMetadataFlag(value: string | undefined): Record<string, string | number | boolean> | undefined {\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\tconst parsed = JSON.parse(value) as unknown;\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new Error(\"--metadata must be a JSON object.\");\n\t}\n\treturn parsed as Record<string, string | number | boolean>;\n}\n\nfunction parseFilterFlag(value: string | undefined): MetadataFilter | undefined {\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\tconst parsed = JSON.parse(value) as unknown;\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new Error(\"--filter must be a JSON object.\");\n\t}\n\treturn parsed as MetadataFilter;\n}\n\nfunction isCliCommand(value: unknown): value is CliCommand {\n\treturn Boolean(value) && typeof value === \"object\" && typeof (value as CliCommand).opts === \"function\";\n}\n\nfunction resolveInvocation(args: unknown[]): { positionals: unknown[]; options: Record<string, unknown> } {\n\tconst maybeCommand = args.at(-1);\n\tif (!isCliCommand(maybeCommand)) {\n\t\treturn {\n\t\t\tpositionals: args,\n\t\t\toptions: {},\n\t\t};\n\t}\n\treturn {\n\t\tpositionals: args.slice(0, -1),\n\t\toptions: maybeCommand.opts?.() ?? {},\n\t};\n}\n\nfunction parseDuplicateStrategy(value: unknown): MigrationDuplicateStrategy | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"overwrite\" || value === \"skip\" || value === \"fail\") {\n\t\treturn value;\n\t}\n\tthrow new Error(\"--if-exists must be overwrite, skip, or fail.\");\n}\n\nexport function registerCloudflareMemoryCli(\n\tprogram: {\n\t\tcommand: (name: string) => CliCommand;\n\t},\n\tparams: {\n\t\tpluginConfig: unknown;\n\t\topenClawConfig: OpenClawConfig;\n\t\tresolvePath?: (input: string) => string;\n\t},\n): void {\n\tconst root = program.command(\"cf-memory\").description(\"Manage Cloudflare memory records.\");\n\n\tfunction resolveOptions(args: unknown[]): Record<string, unknown> {\n\t\treturn resolveInvocation(args).options;\n\t}\n\n\troot\n\t\t.command(\"doctor\")\n\t\t.description(\"Validate Workers AI and Vectorize configuration.\")\n\t\t.option(\"--create-index\", \"Create the Vectorize index if missing.\")\n\t\t.option(\"--json\", \"Print structured JSON output.\")\n\t\t.action(async (...args) => {\n\t\t\tconst options = resolveOptions(args);\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst report = await service.doctor({\n\t\t\t\tcreateIndexIfMissing: Boolean(options.createIndex),\n\t\t\t});\n\t\t\tif (options.json) {\n\t\t\t\tprintJson(report);\n\t\t\t} else {\n\t\t\t\tfor (const check of report.checks) {\n\t\t\t\t\tconsole.log(`[${check.status}] ${check.name}: ${check.message}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!report.ok) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\n\troot\n\t\t.command(\"search\")\n\t\t.description(\"Search stored Cloudflare memory.\")\n\t\t.argument(\"<query>\", \"Semantic search query.\")\n\t\t.option(\"--namespace <namespace>\", \"Optional namespace override.\")\n\t\t.option(\"--limit <count>\", \"Maximum number of results.\")\n\t\t.option(\"--filter <json>\", \"Optional metadata filter JSON.\")\n\t\t.action(async (query, opts) => {\n\t\t\tconst options = opts as Record<string, unknown>;\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst results = await service.search({\n\t\t\t\tquery: String(query),\n\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t\tmaxResults: options.limit ? Number(options.limit) : undefined,\n\t\t\t\tfilter: parseFilterFlag(options.filter as string | undefined),\n\t\t\t});\n\t\t\tprintJson(results);\n\t\t});\n\n\troot\n\t\t.command(\"upsert\")\n\t\t.description(\"Insert or update a memory record.\")\n\t\t.argument(\"<text>\", \"Memory text.\")\n\t\t.option(\"--id <id>\", \"Stable logical id.\")\n\t\t.option(\"--title <title>\", \"Optional title.\")\n\t\t.option(\"--namespace <namespace>\", \"Optional namespace override.\")\n\t\t.option(\"--source <source>\", \"Optional source label.\")\n\t\t.option(\"--metadata <json>\", \"Optional metadata JSON object.\")\n\t\t.action(async (text, opts) => {\n\t\t\tconst options = opts as Record<string, unknown>;\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst result = await service.upsert({\n\t\t\t\tinput: {\n\t\t\t\t\tid: options.id as string | undefined,\n\t\t\t\t\ttitle: options.title as string | undefined,\n\t\t\t\t\ttext: String(text),\n\t\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t\t\tsource: options.source as string | undefined,\n\t\t\t\t\tmetadata: parseMetadataFlag(options.metadata as string | undefined),\n\t\t\t\t},\n\t\t\t});\n\t\t\tprintJson(result);\n\t\t});\n\n\troot\n\t\t.command(\"delete\")\n\t\t.description(\"Delete a memory record.\")\n\t\t.argument(\"<id>\", \"Logical memory record id.\")\n\t\t.option(\"--namespace <namespace>\", \"Optional namespace override.\")\n\t\t.action(async (id, opts) => {\n\t\t\tconst options = opts as Record<string, unknown>;\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst mutationId = await service.delete({\n\t\t\t\tid: String(id),\n\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t});\n\t\t\tprintJson({ id, mutationId });\n\t\t});\n\n\troot\n\t\t.command(\"migrate\")\n\t\t.description(\"Migrate legacy markdown memory into Cloudflare Vectorize.\")\n\t\t.argument(\"[sources...]\", \"Markdown files, directories, or glob patterns. Defaults to the current OpenClaw memory corpus when omitted.\")\n\t\t.option(\"--workspace <path>\", \"Workspace root used for default-provider discovery and relative path normalization.\")\n\t\t.option(\"--namespace <namespace>\", \"Target namespace override.\")\n\t\t.option(\"--derive-namespace-from-path\", \"Derive namespaces from the first relative path segment instead of using a single target namespace.\")\n\t\t.option(\"--if-exists <strategy>\", \"Duplicate handling: overwrite, skip, or fail.\")\n\t\t.option(\"--create-index\", \"Create the Vectorize index if missing.\")\n\t\t.option(\"--dry-run\", \"Plan the migration without writing records.\")\n\t\t.option(\"--json\", \"Print structured JSON output.\")\n\t\t.action(async (...args) => {\n\t\t\tconst { positionals, options } = resolveInvocation(args);\n\t\t\tconst rawSources = positionals[0];\n\t\t\tconst sourcePaths =\n\t\t\t\tpositionals.length === 0 ? [] : Array.isArray(rawSources) ? rawSources.map((value) => String(value)) : positionals.map((value) => String(value));\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst summary = await runCloudflareMemoryMigration({\n\t\t\t\tservice,\n\t\t\t\toptions: {\n\t\t\t\t\tsourcePaths,\n\t\t\t\t\tworkspaceDir: options.workspace as string | undefined,\n\t\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t\t\tnamespaceStrategy: options.deriveNamespaceFromPath ? \"path\" : \"single-target\",\n\t\t\t\t\tduplicateStrategy: parseDuplicateStrategy(options.ifExists),\n\t\t\t\t\tdryRun: Boolean(options.dryRun),\n\t\t\t\t\tcreateIndexIfMissing: Boolean(options.createIndex),\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (options.json) {\n\t\t\t\tprintJson(summary);\n\t\t\t} else {\n\t\t\t\tconsole.log(formatMigrationSummary(summary));\n\t\t\t}\n\t\t\tif (summary.failed > 0) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n}\n"],"mappings":";;;AAeA,SAAS,EAAU,GAAsB;AACxC,SAAQ,IAAI,KAAK,UAAU,GAAO,MAAM,EAA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,EAAuB,EAAQ,SAAS;IAC3D,QAAQ,EAAQ,EAAQ;IACxB,sBAAsB,EAAQ,EAAQ;IACtC;GACD,CAAC;AAMF,EALI,EAAQ,OACX,EAAU,EAAQ,GAElB,QAAQ,IAAI,EAAuB,EAAQ,CAAC,EAEzC,EAAQ,SAAS,MACpB,QAAQ,WAAW;GAEnB"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import type { OpenClawConfig } from \"openclaw/plugin-sdk/config-runtime\";\nimport type { DoctorReport, IndexInitializationReport, MetadataFilter, MigrationDuplicateStrategy, SmokeTestReport } from \"./types.js\";\nimport { formatMigrationSummary, runCloudflareMemoryMigration } from \"./migration.js\";\nimport { createCloudflareMemoryService } from \"./service-factory.js\";\n\ntype CliCommand = {\n\tcommand: (name: string) => CliCommand;\n\tdescription: (description: string) => CliCommand;\n\targument: (name: string, description: string) => CliCommand;\n\toption: (flags: string, description: string) => CliCommand;\n\taction: (handler: (...args: unknown[]) => Promise<void> | void) => CliCommand;\n\topts?: () => Record<string, unknown>;\n};\n\nfunction printJson(value: unknown): void {\n\tconsole.log(JSON.stringify(value, null, 2));\n}\n\nfunction printCheckReport(report: DoctorReport | IndexInitializationReport | SmokeTestReport): void {\n\tfor (const check of report.checks) {\n\t\tconsole.log(`[${check.status}] ${check.name}: ${check.message}`);\n\t}\n}\n\nfunction parseMetadataFlag(value: string | undefined): Record<string, string | number | boolean> | undefined {\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\tconst parsed = JSON.parse(value) as unknown;\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new Error(\"--metadata must be a JSON object.\");\n\t}\n\treturn parsed as Record<string, string | number | boolean>;\n}\n\nfunction parseFilterFlag(value: string | undefined): MetadataFilter | undefined {\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\tconst parsed = JSON.parse(value) as unknown;\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new Error(\"--filter must be a JSON object.\");\n\t}\n\treturn parsed as MetadataFilter;\n}\n\nfunction isCliCommand(value: unknown): value is CliCommand {\n\treturn Boolean(value) && typeof value === \"object\" && typeof (value as CliCommand).opts === \"function\";\n}\n\nfunction resolveInvocation(args: unknown[]): { positionals: unknown[]; options: Record<string, unknown> } {\n\tconst maybeCommand = args.at(-1);\n\tif (!isCliCommand(maybeCommand)) {\n\t\treturn {\n\t\t\tpositionals: args,\n\t\t\toptions: {},\n\t\t};\n\t}\n\treturn {\n\t\tpositionals: args.slice(0, -1),\n\t\toptions: maybeCommand.opts?.() ?? {},\n\t};\n}\n\nfunction parseDuplicateStrategy(value: unknown): MigrationDuplicateStrategy | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"overwrite\" || value === \"skip\" || value === \"fail\") {\n\t\treturn value;\n\t}\n\tthrow new Error(\"--if-exists must be overwrite, skip, or fail.\");\n}\n\nexport function registerCloudflareMemoryCli(\n\tprogram: {\n\t\tcommand: (name: string) => CliCommand;\n\t},\n\tparams: {\n\t\tpluginConfig: unknown;\n\t\topenClawConfig: OpenClawConfig;\n\t\tresolvePath?: (input: string) => string;\n\t},\n): void {\n\tconst root = program.command(\"cf-memory\").description(\"Manage Cloudflare memory records.\");\n\n\tfunction resolveOptions(args: unknown[]): Record<string, unknown> {\n\t\treturn resolveInvocation(args).options;\n\t}\n\n\troot\n\t\t.command(\"doctor\")\n\t\t.description(\"Validate Workers AI and Vectorize configuration.\")\n\t\t.option(\"--create-index\", \"Create the Vectorize index if missing.\")\n\t\t.option(\"--json\", \"Print structured JSON output.\")\n\t\t.action(async (...args) => {\n\t\t\tconst options = resolveOptions(args);\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst report = await service.doctor({\n\t\t\t\tcreateIndexIfMissing: Boolean(options.createIndex),\n\t\t\t});\n\t\t\tif (options.json) {\n\t\t\t\tprintJson(report);\n\t\t\t} else {\n\t\t\t\tprintCheckReport(report);\n\t\t\t}\n\t\t\tif (!report.ok) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\n\troot\n\t\t.command(\"init\")\n\t\t.description(\"Initialize the Cloudflare Vectorize index for the configured embedding model.\")\n\t\t.option(\"--json\", \"Print structured JSON output.\")\n\t\t.action(async (...args) => {\n\t\t\tconst options = resolveOptions(args);\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst report = await service.initializeIndex();\n\t\t\tif (options.json) {\n\t\t\t\tprintJson(report);\n\t\t\t} else {\n\t\t\t\tprintCheckReport(report);\n\t\t\t}\n\t\t\tif (!report.ok) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\n\troot\n\t\t.command(\"test\")\n\t\t.description(\"Run an end-to-end embedding and semantic-search smoke test.\")\n\t\t.option(\"--json\", \"Print structured JSON output.\")\n\t\t.action(async (...args) => {\n\t\t\tconst options = resolveOptions(args);\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst report = await service.runSmokeTest();\n\t\t\tif (options.json) {\n\t\t\t\tprintJson(report);\n\t\t\t} else {\n\t\t\t\tprintCheckReport(report);\n\t\t\t}\n\t\t\tif (!report.ok) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n\n\troot\n\t\t.command(\"search\")\n\t\t.description(\"Search stored Cloudflare memory.\")\n\t\t.argument(\"<query>\", \"Semantic search query.\")\n\t\t.option(\"--namespace <namespace>\", \"Optional namespace override.\")\n\t\t.option(\"--limit <count>\", \"Maximum number of results.\")\n\t\t.option(\"--filter <json>\", \"Optional metadata filter JSON.\")\n\t\t.action(async (query, opts) => {\n\t\t\tconst options = opts as Record<string, unknown>;\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst results = await service.search({\n\t\t\t\tquery: String(query),\n\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t\tmaxResults: options.limit ? Number(options.limit) : undefined,\n\t\t\t\tfilter: parseFilterFlag(options.filter as string | undefined),\n\t\t\t});\n\t\t\tprintJson(results);\n\t\t});\n\n\troot\n\t\t.command(\"upsert\")\n\t\t.description(\"Insert or update a memory record.\")\n\t\t.argument(\"<text>\", \"Memory text.\")\n\t\t.option(\"--id <id>\", \"Stable logical id.\")\n\t\t.option(\"--title <title>\", \"Optional title.\")\n\t\t.option(\"--namespace <namespace>\", \"Optional namespace override.\")\n\t\t.option(\"--source <source>\", \"Optional source label.\")\n\t\t.option(\"--metadata <json>\", \"Optional metadata JSON object.\")\n\t\t.action(async (text, opts) => {\n\t\t\tconst options = opts as Record<string, unknown>;\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst result = await service.upsert({\n\t\t\t\tinput: {\n\t\t\t\t\tid: options.id as string | undefined,\n\t\t\t\t\ttitle: options.title as string | undefined,\n\t\t\t\t\ttext: String(text),\n\t\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t\t\tsource: options.source as string | undefined,\n\t\t\t\t\tmetadata: parseMetadataFlag(options.metadata as string | undefined),\n\t\t\t\t},\n\t\t\t});\n\t\t\tprintJson(result);\n\t\t});\n\n\troot\n\t\t.command(\"delete\")\n\t\t.description(\"Delete a memory record.\")\n\t\t.argument(\"<id>\", \"Logical memory record id.\")\n\t\t.option(\"--namespace <namespace>\", \"Optional namespace override.\")\n\t\t.action(async (id, opts) => {\n\t\t\tconst options = opts as Record<string, unknown>;\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst mutationId = await service.delete({\n\t\t\t\tid: String(id),\n\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t});\n\t\t\tprintJson({ id, mutationId });\n\t\t});\n\n\troot\n\t\t.command(\"migrate\")\n\t\t.description(\"Migrate legacy markdown memory into Cloudflare Vectorize.\")\n\t\t.argument(\"[sources...]\", \"Markdown files, directories, or glob patterns. Defaults to the current OpenClaw memory corpus when omitted.\")\n\t\t.option(\"--workspace <path>\", \"Workspace root used for default-provider discovery and relative path normalization.\")\n\t\t.option(\"--namespace <namespace>\", \"Target namespace override.\")\n\t\t.option(\"--derive-namespace-from-path\", \"Derive namespaces from the first relative path segment instead of using a single target namespace.\")\n\t\t.option(\"--if-exists <strategy>\", \"Duplicate handling: overwrite, skip, or fail.\")\n\t\t.option(\"--create-index\", \"Create the Vectorize index if missing.\")\n\t\t.option(\"--dry-run\", \"Plan the migration without writing records.\")\n\t\t.option(\"--json\", \"Print structured JSON output.\")\n\t\t.action(async (...args) => {\n\t\t\tconst { positionals, options } = resolveInvocation(args);\n\t\t\tconst rawSources = positionals[0];\n\t\t\tconst sourcePaths =\n\t\t\t\tpositionals.length === 0 ? [] : Array.isArray(rawSources) ? rawSources.map((value) => String(value)) : positionals.map((value) => String(value));\n\t\t\tconst service = await createCloudflareMemoryService({\n\t\t\t\tpluginConfig: params.pluginConfig,\n\t\t\t\topenClawConfig: params.openClawConfig,\n\t\t\t\tenv: process.env,\n\t\t\t\tresolvePath: params.resolvePath,\n\t\t\t});\n\t\t\tconst summary = await runCloudflareMemoryMigration({\n\t\t\t\tservice,\n\t\t\t\toptions: {\n\t\t\t\t\tsourcePaths,\n\t\t\t\t\tworkspaceDir: options.workspace as string | undefined,\n\t\t\t\t\tnamespace: options.namespace as string | undefined,\n\t\t\t\t\tnamespaceStrategy: options.deriveNamespaceFromPath ? \"path\" : \"single-target\",\n\t\t\t\t\tduplicateStrategy: parseDuplicateStrategy(options.ifExists),\n\t\t\t\t\tdryRun: Boolean(options.dryRun),\n\t\t\t\t\tcreateIndexIfMissing: Boolean(options.createIndex),\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (options.json) {\n\t\t\t\tprintJson(summary);\n\t\t\t} else {\n\t\t\t\tconsole.log(formatMigrationSummary(summary));\n\t\t\t}\n\t\t\tif (summary.failed > 0) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t});\n}\n"],"mappings":";;;AAcA,SAAS,EAAU,GAAsB;AACxC,SAAQ,IAAI,KAAK,UAAU,GAAO,MAAM,EAAE,CAAC;;AAG5C,SAAS,EAAiB,GAA0E;AACnG,MAAK,IAAM,KAAS,EAAO,OAC1B,SAAQ,IAAI,IAAI,EAAM,OAAO,IAAI,EAAM,KAAK,IAAI,EAAM,UAAU;;AAIlE,SAAS,EAAkB,GAAkF;AAC5G,KAAI,CAAC,EACJ;CAED,IAAM,IAAS,KAAK,MAAM,EAAM;AAChC,KAAI,CAAC,KAAU,OAAO,KAAW,YAAY,MAAM,QAAQ,EAAO,CACjE,OAAU,MAAM,oCAAoC;AAErD,QAAO;;AAGR,SAAS,EAAgB,GAAuD;AAC/E,KAAI,CAAC,EACJ;CAED,IAAM,IAAS,KAAK,MAAM,EAAM;AAChC,KAAI,CAAC,KAAU,OAAO,KAAW,YAAY,MAAM,QAAQ,EAAO,CACjE,OAA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AAK,MAAU,OAAO,EAAM,CAAC,EAO3I,IAAU,MAAM,EAA6B;GAClD,SAPe,MAAM,EAA8B;IACnD,cAAc,EAAO;IACrB,gBAAgB,EAAO;IACvB,KAAK,QAAQ;IACb,aAAa,EAAO;IACpB,CAAC;GAGD,SAAS;IACR;IACA,cAAc,EAAQ;IACtB,WAAW,EAAQ;IACnB,mBAAmB,EAAQ,0BAA0B,SAAS;IAC9D,mBAAmB,EAAuB,EAAQ,SAAS;IAC3D,QAAQ,EAAQ,EAAQ;IACxB,sBAAsB,EAAQ,EAAQ;IACtC;GACD,CAAC;AAMF,EALI,EAAQ,OACX,EAAU,EAAQ,GAElB,QAAQ,IAAI,EAAuB,EAAQ,CAAC,EAEzC,EAAQ,SAAS,MACpB,QAAQ,WAAW;GAEnB"}
|
package/dist/doctor.js
CHANGED
|
@@ -6,26 +6,46 @@ async function e(e) {
|
|
|
6
6
|
status: "pass",
|
|
7
7
|
message: `Using Cloudflare account ${e.service.config.accountId} and Vectorize index ${e.service.config.indexName}.`
|
|
8
8
|
});
|
|
9
|
-
let n = await e.service.
|
|
9
|
+
let n = await e.service.inspectEmbeddingDimensions();
|
|
10
10
|
t.push({
|
|
11
|
-
name: "
|
|
11
|
+
name: "workers-ai-embeddings",
|
|
12
12
|
status: "pass",
|
|
13
|
-
message:
|
|
13
|
+
message: `Workers AI model ${e.service.config.model} returned ${n.embeddingDimensions} dimensions.`
|
|
14
|
+
}), n.configuredDimensions !== void 0 && t.push({
|
|
15
|
+
name: "create-index-dimensions",
|
|
16
|
+
status: n.configuredDimensionsMatchModel ? "pass" : "warn",
|
|
17
|
+
message: n.configuredDimensionsMatchModel ? `Configured createIndex.dimensions matches the embedding model (${n.embeddingDimensions}).` : `Configured createIndex.dimensions (${n.configuredDimensions}) does not match the embedding model (${n.embeddingDimensions}). Index creation uses the live embedding dimensions.`
|
|
14
18
|
});
|
|
15
|
-
let r
|
|
16
|
-
|
|
17
|
-
|
|
19
|
+
let r;
|
|
20
|
+
if (e.createIndexIfMissing) r = await e.service.ensureIndexExists(!0, n.targetDimensions);
|
|
21
|
+
else {
|
|
22
|
+
let t = await e.service.describeIndexIfExists();
|
|
23
|
+
t && (r = {
|
|
24
|
+
created: !1,
|
|
25
|
+
dimensions: t.config.dimensions
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return r ? (t.push({
|
|
29
|
+
name: "vectorize-index",
|
|
18
30
|
status: "pass",
|
|
19
|
-
message: `
|
|
20
|
-
}),
|
|
31
|
+
message: r.created ? `Created Vectorize index "${e.service.config.indexName}" with ${r.dimensions} dimensions.` : `Vectorize index "${e.service.config.indexName}" is reachable.`
|
|
32
|
+
}), n.embeddingDimensions === r.dimensions ? t.push({
|
|
21
33
|
name: "dimension-match",
|
|
22
34
|
status: "pass",
|
|
23
35
|
message: "Embedding dimensions match the Vectorize index."
|
|
24
36
|
}) : t.push({
|
|
25
37
|
name: "dimension-match",
|
|
26
38
|
status: "fail",
|
|
27
|
-
message: `Embedding dimensions (${
|
|
39
|
+
message: `Embedding dimensions (${n.embeddingDimensions}) do not match the Vectorize index dimensions (${r.dimensions}).`
|
|
40
|
+
})) : (t.push({
|
|
41
|
+
name: "vectorize-index",
|
|
42
|
+
status: "fail",
|
|
43
|
+
message: `Vectorize index "${e.service.config.indexName}" was not found. Run "openclaw cf-memory init" or rerun doctor with --create-index.`
|
|
28
44
|
}), t.push({
|
|
45
|
+
name: "dimension-match",
|
|
46
|
+
status: "warn",
|
|
47
|
+
message: "Skipped dimension comparison because the Vectorize index does not exist yet."
|
|
48
|
+
})), t.push({
|
|
29
49
|
name: "metadata-filters",
|
|
30
50
|
status: e.service.config.metadataIndexedFields.length > 0 ? "pass" : "warn",
|
|
31
51
|
message: e.service.config.metadataIndexedFields.length > 0 ? `Configured metadata-index guidance for: ${e.service.config.metadataIndexedFields.join(", ")}.` : "No metadataIndexedFields configured. Add metadata indexes in Cloudflare before relying on filter-heavy queries."
|
package/dist/doctor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctor.js","names":[],"sources":["../src/doctor.ts"],"sourcesContent":["import type { CloudflareMemoryService } from \"./service.js\";\nimport type { DoctorCheck, DoctorReport } from \"./types.js\";\n\nexport async function runDoctor(params: { service: CloudflareMemoryService; createIndexIfMissing: boolean }): Promise<DoctorReport> {\n\tconst checks: DoctorCheck[] = [];\n\n\tchecks.push({\n\t\tname: \"credentials\",\n\t\tstatus: \"pass\",\n\t\tmessage: `Using Cloudflare account ${params.service.config.accountId} and Vectorize index ${params.service.config.indexName}.`,\n\t});\n\n\tconst
|
|
1
|
+
{"version":3,"file":"doctor.js","names":[],"sources":["../src/doctor.ts"],"sourcesContent":["import type { CloudflareMemoryService } from \"./service.js\";\nimport type { DoctorCheck, DoctorReport } from \"./types.js\";\n\nexport async function runDoctor(params: { service: CloudflareMemoryService; createIndexIfMissing: boolean }): Promise<DoctorReport> {\n\tconst checks: DoctorCheck[] = [];\n\n\tchecks.push({\n\t\tname: \"credentials\",\n\t\tstatus: \"pass\",\n\t\tmessage: `Using Cloudflare account ${params.service.config.accountId} and Vectorize index ${params.service.config.indexName}.`,\n\t});\n\n\tconst embedding = await params.service.inspectEmbeddingDimensions();\n\tchecks.push({\n\t\tname: \"workers-ai-embeddings\",\n\t\tstatus: \"pass\",\n\t\tmessage: `Workers AI model ${params.service.config.model} returned ${embedding.embeddingDimensions} dimensions.`,\n\t});\n\tif (embedding.configuredDimensions !== undefined) {\n\t\tchecks.push({\n\t\t\tname: \"create-index-dimensions\",\n\t\t\tstatus: embedding.configuredDimensionsMatchModel ? \"pass\" : \"warn\",\n\t\t\tmessage: embedding.configuredDimensionsMatchModel\n\t\t\t\t? `Configured createIndex.dimensions matches the embedding model (${embedding.embeddingDimensions}).`\n\t\t\t\t: `Configured createIndex.dimensions (${embedding.configuredDimensions}) does not match the embedding model (${embedding.embeddingDimensions}). Index creation uses the live embedding dimensions.`,\n\t\t});\n\t}\n\n\tlet indexResult:\n\t\t| {\n\t\t\t\tcreated: boolean;\n\t\t\t\tdimensions: number;\n\t\t }\n\t\t| undefined;\n\tif (params.createIndexIfMissing) {\n\t\tindexResult = await params.service.ensureIndexExists(true, embedding.targetDimensions);\n\t} else {\n\t\tconst existingIndex = await params.service.describeIndexIfExists();\n\t\tif (existingIndex) {\n\t\t\tindexResult = {\n\t\t\t\tcreated: false,\n\t\t\t\tdimensions: existingIndex.config.dimensions,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (!indexResult) {\n\t\tchecks.push({\n\t\t\tname: \"vectorize-index\",\n\t\t\tstatus: \"fail\",\n\t\t\tmessage: `Vectorize index \"${params.service.config.indexName}\" was not found. Run \"openclaw cf-memory init\" or rerun doctor with --create-index.`,\n\t\t});\n\t\tchecks.push({\n\t\t\tname: \"dimension-match\",\n\t\t\tstatus: \"warn\",\n\t\t\tmessage: \"Skipped dimension comparison because the Vectorize index does not exist yet.\",\n\t\t});\n\t} else {\n\t\tchecks.push({\n\t\t\tname: \"vectorize-index\",\n\t\t\tstatus: \"pass\",\n\t\t\tmessage: indexResult.created\n\t\t\t\t? `Created Vectorize index \"${params.service.config.indexName}\" with ${indexResult.dimensions} dimensions.`\n\t\t\t\t: `Vectorize index \"${params.service.config.indexName}\" is reachable.`,\n\t\t});\n\t\tif (embedding.embeddingDimensions !== indexResult.dimensions) {\n\t\t\tchecks.push({\n\t\t\t\tname: \"dimension-match\",\n\t\t\t\tstatus: \"fail\",\n\t\t\t\tmessage: `Embedding dimensions (${embedding.embeddingDimensions}) do not match the Vectorize index dimensions (${indexResult.dimensions}).`,\n\t\t\t});\n\t\t} else {\n\t\t\tchecks.push({\n\t\t\t\tname: \"dimension-match\",\n\t\t\t\tstatus: \"pass\",\n\t\t\t\tmessage: \"Embedding dimensions match the Vectorize index.\",\n\t\t\t});\n\t\t}\n\t}\n\n\tchecks.push({\n\t\tname: \"metadata-filters\",\n\t\tstatus: params.service.config.metadataIndexedFields.length > 0 ? \"pass\" : \"warn\",\n\t\tmessage:\n\t\t\tparams.service.config.metadataIndexedFields.length > 0\n\t\t\t\t? `Configured metadata-index guidance for: ${params.service.config.metadataIndexedFields.join(\", \")}.`\n\t\t\t\t: \"No metadataIndexedFields configured. Add metadata indexes in Cloudflare before relying on filter-heavy queries.\",\n\t});\n\n\tconst ok = checks.every((check) => check.status !== \"fail\");\n\treturn { ok, checks };\n}\n"],"mappings":";AAGA,eAAsB,EAAU,GAAoG;CACnI,IAAM,IAAwB,EAAE;AAEhC,GAAO,KAAK;EACX,MAAM;EACN,QAAQ;EACR,SAAS,4BAA4B,EAAO,QAAQ,OAAO,UAAU,uBAAuB,EAAO,QAAQ,OAAO,UAAU;EAC5H,CAAC;CAEF,IAAM,IAAY,MAAM,EAAO,QAAQ,4BAA4B;AAMnE,CALA,EAAO,KAAK;EACX,MAAM;EACN,QAAQ;EACR,SAAS,oBAAoB,EAAO,QAAQ,OAAO,MAAM,YAAY,EAAU,oBAAoB;EACnG,CAAC,EACE,EAAU,yBAAyB,KAAA,KACtC,EAAO,KAAK;EACX,MAAM;EACN,QAAQ,EAAU,iCAAiC,SAAS;EAC5D,SAAS,EAAU,iCAChB,kEAAkE,EAAU,oBAAoB,MAChG,sCAAsC,EAAU,qBAAqB,wCAAwC,EAAU,oBAAoB;EAC9I,CAAC;CAGH,IAAI;AAMJ,KAAI,EAAO,qBACV,KAAc,MAAM,EAAO,QAAQ,kBAAkB,IAAM,EAAU,iBAAiB;MAChF;EACN,IAAM,IAAgB,MAAM,EAAO,QAAQ,uBAAuB;AAClE,EAAI,MACH,IAAc;GACb,SAAS;GACT,YAAY,EAAc,OAAO;GACjC;;AAgDH,QA5CK,KAYJ,EAAO,KAAK;EACX,MAAM;EACN,QAAQ;EACR,SAAS,EAAY,UAClB,4BAA4B,EAAO,QAAQ,OAAO,UAAU,SAAS,EAAY,WAAW,gBAC5F,oBAAoB,EAAO,QAAQ,OAAO,UAAU;EACvD,CAAC,EACE,EAAU,wBAAwB,EAAY,aAOjD,EAAO,KAAK;EACX,MAAM;EACN,QAAQ;EACR,SAAS;EACT,CAAC,GAVF,EAAO,KAAK;EACX,MAAM;EACN,QAAQ;EACR,SAAS,yBAAyB,EAAU,oBAAoB,iDAAiD,EAAY,WAAW;EACxI,CAAC,KAvBH,EAAO,KAAK;EACX,MAAM;EACN,QAAQ;EACR,SAAS,oBAAoB,EAAO,QAAQ,OAAO,UAAU;EAC7D,CAAC,EACF,EAAO,KAAK;EACX,MAAM;EACN,QAAQ;EACR,SAAS;EACT,CAAC,GAwBH,EAAO,KAAK;EACX,MAAM;EACN,QAAQ,EAAO,QAAQ,OAAO,sBAAsB,SAAS,IAAI,SAAS;EAC1E,SACC,EAAO,QAAQ,OAAO,sBAAsB,SAAS,IAClD,2CAA2C,EAAO,QAAQ,OAAO,sBAAsB,KAAK,KAAK,CAAC,KAClG;EACJ,CAAC,EAGK;EAAE,IADE,EAAO,OAAO,MAAU,EAAM,WAAW,OAAO;EAC9C;EAAQ"}
|
package/dist/service.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
import { resolveDefaultNamespace as e } from "./namespace.js";
|
|
2
|
-
import { isCloudflareNotFoundError as
|
|
3
|
-
import { CompanionStore as
|
|
4
|
-
import { runDoctor as
|
|
5
|
-
import { WorkersAiEmbeddingsClient as
|
|
6
|
-
import { hydrateInlineRecord as
|
|
7
|
-
import { VectorizeClient as
|
|
1
|
+
import { resolveDefaultNamespace as e, sanitizeNamespace as t } from "./namespace.js";
|
|
2
|
+
import { isCloudflareNotFoundError as n } from "./cloudflare-api.js";
|
|
3
|
+
import { CompanionStore as r } from "./companion-store.js";
|
|
4
|
+
import { runDoctor as i } from "./doctor.js";
|
|
5
|
+
import { WorkersAiEmbeddingsClient as a } from "./embeddings-client.js";
|
|
6
|
+
import { hydrateInlineRecord as o, mapRecordForUpsert as s } from "./record-mapper.js";
|
|
7
|
+
import { VectorizeClient as c } from "./vectorize-client.js";
|
|
8
|
+
import { randomUUID as l } from "node:crypto";
|
|
8
9
|
//#region src/service.ts
|
|
9
|
-
var
|
|
10
|
+
var u = 12e3, d = 1e3, f = class {
|
|
10
11
|
embeddings;
|
|
11
12
|
vectorize;
|
|
12
13
|
companionStore;
|
|
13
14
|
constructor(e, t) {
|
|
14
|
-
this.config = e, this.openClawConfig = t, this.embeddings = new
|
|
15
|
+
this.config = e, this.openClawConfig = t, this.embeddings = new a(e), this.vectorize = new c(e), this.companionStore = new r(e.companionStorePath);
|
|
15
16
|
}
|
|
16
17
|
resolveNamespace(t) {
|
|
17
18
|
return e({
|
|
@@ -29,7 +30,7 @@ var c = class {
|
|
|
29
30
|
filter: e.filter
|
|
30
31
|
});
|
|
31
32
|
return (await Promise.all(r.map(async (e) => {
|
|
32
|
-
let t =
|
|
33
|
+
let t = o(e), n = t.text ?? (await this.companionStore.get(t.namespace, t.logicalId))?.text ?? "";
|
|
33
34
|
return {
|
|
34
35
|
...t,
|
|
35
36
|
text: n,
|
|
@@ -40,7 +41,7 @@ var c = class {
|
|
|
40
41
|
async get(e) {
|
|
41
42
|
let t = `${this.resolveNamespace(e)}::${e.id}`, [n] = await this.vectorize.getByIds([t]);
|
|
42
43
|
if (!n) return null;
|
|
43
|
-
let r =
|
|
44
|
+
let r = o(n), i = await this.companionStore.get(r.namespace, r.logicalId);
|
|
44
45
|
return {
|
|
45
46
|
...r,
|
|
46
47
|
text: r.text ?? i?.text ?? ""
|
|
@@ -52,7 +53,7 @@ var c = class {
|
|
|
52
53
|
sessionKey: e.sessionKey,
|
|
53
54
|
agentId: e.agentId,
|
|
54
55
|
workspaceDir: e.workspaceDir
|
|
55
|
-
}), n = await this.embeddings.embedQuery(e.input.text), r =
|
|
56
|
+
}), n = await this.embeddings.embedQuery(e.input.text), r = s({
|
|
56
57
|
input: e.input,
|
|
57
58
|
namespace: t,
|
|
58
59
|
embedding: n,
|
|
@@ -73,23 +74,207 @@ var c = class {
|
|
|
73
74
|
return await this.companionStore.delete(t, e.id), this.vectorize.deleteByIds([`${t}::${e.id}`]);
|
|
74
75
|
}
|
|
75
76
|
async doctor(e) {
|
|
76
|
-
return
|
|
77
|
+
return i({
|
|
77
78
|
service: this,
|
|
78
79
|
createIndexIfMissing: e.createIndexIfMissing ?? !1
|
|
79
80
|
});
|
|
80
81
|
}
|
|
81
|
-
async
|
|
82
|
+
async inspectEmbeddingDimensions() {
|
|
83
|
+
let e = await this.embeddings.probeDimensions(), t = this.config.createIndex.dimensions;
|
|
84
|
+
return {
|
|
85
|
+
embeddingDimensions: e,
|
|
86
|
+
configuredDimensions: t,
|
|
87
|
+
configuredDimensionsMatchModel: t === void 0 || t === e,
|
|
88
|
+
targetDimensions: e
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
async describeIndexIfExists() {
|
|
92
|
+
try {
|
|
93
|
+
return await this.vectorize.describeIndex();
|
|
94
|
+
} catch (e) {
|
|
95
|
+
if (n(e)) return null;
|
|
96
|
+
throw e;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
async initializeIndex(e) {
|
|
100
|
+
let t = e?.recreateIfDimensionMismatch ?? !0, n = [];
|
|
101
|
+
n.push({
|
|
102
|
+
name: "credentials",
|
|
103
|
+
status: "pass",
|
|
104
|
+
message: `Using Cloudflare account ${this.config.accountId} and Vectorize index ${this.config.indexName}.`
|
|
105
|
+
});
|
|
106
|
+
let r = await this.inspectEmbeddingDimensions();
|
|
107
|
+
n.push({
|
|
108
|
+
name: "workers-ai-embeddings",
|
|
109
|
+
status: "pass",
|
|
110
|
+
message: `Workers AI model ${this.config.model} returned ${r.embeddingDimensions} dimensions.`
|
|
111
|
+
}), r.configuredDimensions !== void 0 && n.push({
|
|
112
|
+
name: "create-index-dimensions",
|
|
113
|
+
status: r.configuredDimensionsMatchModel ? "pass" : "warn",
|
|
114
|
+
message: r.configuredDimensionsMatchModel ? `Configured createIndex.dimensions matches the embedding model (${r.embeddingDimensions}).` : `Configured createIndex.dimensions (${r.configuredDimensions}) does not match the embedding model (${r.embeddingDimensions}). Using the live embedding dimensions for initialization.`
|
|
115
|
+
});
|
|
116
|
+
let i = await this.describeIndexIfExists(), a = !1, o = !1, s = i?.config.dimensions;
|
|
117
|
+
if (!i) {
|
|
118
|
+
let e = await this.vectorize.createIndex(r.targetDimensions);
|
|
119
|
+
a = !0, s = e.config.dimensions, n.push({
|
|
120
|
+
name: "vectorize-index",
|
|
121
|
+
status: "pass",
|
|
122
|
+
message: `Created Vectorize index "${this.config.indexName}" with ${s} dimensions.`
|
|
123
|
+
});
|
|
124
|
+
} else if (i.config.dimensions === r.targetDimensions) n.push({
|
|
125
|
+
name: "vectorize-index",
|
|
126
|
+
status: "pass",
|
|
127
|
+
message: `Vectorize index "${this.config.indexName}" already uses ${i.config.dimensions} dimensions.`
|
|
128
|
+
});
|
|
129
|
+
else if (!t) n.push({
|
|
130
|
+
name: "vectorize-index",
|
|
131
|
+
status: "fail",
|
|
132
|
+
message: `Vectorize index "${this.config.indexName}" uses ${i.config.dimensions} dimensions, but the embedding model requires ${r.targetDimensions}. Recreate the index or rerun init with recreation enabled.`
|
|
133
|
+
});
|
|
134
|
+
else {
|
|
135
|
+
await this.vectorize.deleteIndex();
|
|
136
|
+
let e = await this.vectorize.createIndex(r.targetDimensions);
|
|
137
|
+
o = !0, s = e.config.dimensions, n.push({
|
|
138
|
+
name: "vectorize-index",
|
|
139
|
+
status: "pass",
|
|
140
|
+
message: `Recreated Vectorize index "${this.config.indexName}" from ${i.config.dimensions} to ${s} dimensions.`
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
return n.push({
|
|
144
|
+
name: "dimension-match",
|
|
145
|
+
status: s === r.embeddingDimensions ? "pass" : "fail",
|
|
146
|
+
message: s === r.embeddingDimensions ? "Embedding dimensions match the Vectorize index." : `Embedding dimensions (${r.embeddingDimensions}) do not match the Vectorize index dimensions (${s ?? "unknown"}).`
|
|
147
|
+
}), n.push({
|
|
148
|
+
name: "metadata-filters",
|
|
149
|
+
status: this.config.metadataIndexedFields.length > 0 ? "pass" : "warn",
|
|
150
|
+
message: this.config.metadataIndexedFields.length > 0 ? `Configured metadata-index guidance for: ${this.config.metadataIndexedFields.join(", ")}.` : "No metadataIndexedFields configured. Add metadata indexes in Cloudflare before relying on filter-heavy queries."
|
|
151
|
+
}), {
|
|
152
|
+
ok: n.every((e) => e.status !== "fail"),
|
|
153
|
+
checks: n,
|
|
154
|
+
created: a,
|
|
155
|
+
recreated: o,
|
|
156
|
+
embeddingDimensions: r.embeddingDimensions,
|
|
157
|
+
indexDimensions: s
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
async runSmokeTest(e) {
|
|
161
|
+
let n = [];
|
|
162
|
+
n.push({
|
|
163
|
+
name: "credentials",
|
|
164
|
+
status: "pass",
|
|
165
|
+
message: `Using Cloudflare account ${this.config.accountId} and Vectorize index ${this.config.indexName}.`
|
|
166
|
+
});
|
|
167
|
+
let r = await this.inspectEmbeddingDimensions();
|
|
168
|
+
n.push({
|
|
169
|
+
name: "workers-ai-embeddings",
|
|
170
|
+
status: "pass",
|
|
171
|
+
message: `Workers AI model ${this.config.model} returned ${r.embeddingDimensions} dimensions.`
|
|
172
|
+
}), r.configuredDimensions !== void 0 && n.push({
|
|
173
|
+
name: "create-index-dimensions",
|
|
174
|
+
status: r.configuredDimensionsMatchModel ? "pass" : "warn",
|
|
175
|
+
message: r.configuredDimensionsMatchModel ? `Configured createIndex.dimensions matches the embedding model (${r.embeddingDimensions}).` : `Configured createIndex.dimensions (${r.configuredDimensions}) does not match the embedding model (${r.embeddingDimensions}). Using the live embedding dimensions for validation.`
|
|
176
|
+
});
|
|
177
|
+
let i = await this.describeIndexIfExists();
|
|
178
|
+
if (!i) return n.push({
|
|
179
|
+
name: "vectorize-index",
|
|
180
|
+
status: "fail",
|
|
181
|
+
message: `Vectorize index "${this.config.indexName}" was not found. Run "openclaw cf-memory init" before rerunning this test.`
|
|
182
|
+
}), {
|
|
183
|
+
ok: !1,
|
|
184
|
+
checks: n,
|
|
185
|
+
namespace: "n/a",
|
|
186
|
+
logicalId: "n/a"
|
|
187
|
+
};
|
|
188
|
+
if (n.push({
|
|
189
|
+
name: "vectorize-index",
|
|
190
|
+
status: "pass",
|
|
191
|
+
message: `Vectorize index "${this.config.indexName}" is reachable.`
|
|
192
|
+
}), i.config.dimensions !== r.embeddingDimensions) return n.push({
|
|
193
|
+
name: "dimension-match",
|
|
194
|
+
status: "fail",
|
|
195
|
+
message: `Embedding dimensions (${r.embeddingDimensions}) do not match the Vectorize index dimensions (${i.config.dimensions}). Run "openclaw cf-memory init" to repair the index.`
|
|
196
|
+
}), {
|
|
197
|
+
ok: !1,
|
|
198
|
+
checks: n,
|
|
199
|
+
namespace: "n/a",
|
|
200
|
+
logicalId: "n/a"
|
|
201
|
+
};
|
|
202
|
+
n.push({
|
|
203
|
+
name: "dimension-match",
|
|
204
|
+
status: "pass",
|
|
205
|
+
message: "Embedding dimensions match the Vectorize index."
|
|
206
|
+
});
|
|
207
|
+
let a = t(`cf-memory-test-${l()}`), o = `cf-memory-test-${l()}`, s = `OpenClaw Cloudflare memory smoke test ${o}`, c = !1;
|
|
208
|
+
try {
|
|
209
|
+
await this.upsert({ input: {
|
|
210
|
+
id: o,
|
|
211
|
+
namespace: a,
|
|
212
|
+
text: s,
|
|
213
|
+
source: "cf-memory-test",
|
|
214
|
+
metadata: {
|
|
215
|
+
probe: !0,
|
|
216
|
+
probeId: o
|
|
217
|
+
}
|
|
218
|
+
} }), c = !0, n.push({
|
|
219
|
+
name: "probe-upsert",
|
|
220
|
+
status: "pass",
|
|
221
|
+
message: `Inserted smoke-test record ${o} in namespace ${a}.`
|
|
222
|
+
});
|
|
223
|
+
let t = await this.waitForSearchHit({
|
|
224
|
+
query: s,
|
|
225
|
+
namespace: a,
|
|
226
|
+
logicalId: o,
|
|
227
|
+
timeoutMs: e?.timeoutMs ?? u,
|
|
228
|
+
pollIntervalMs: e?.pollIntervalMs ?? d
|
|
229
|
+
});
|
|
230
|
+
n.push({
|
|
231
|
+
name: "probe-search",
|
|
232
|
+
status: t ? "pass" : "fail",
|
|
233
|
+
message: t ? "Semantic search returned the smoke-test record." : `Semantic search did not return the smoke-test record within ${(e?.timeoutMs ?? u) / 1e3} seconds.`
|
|
234
|
+
});
|
|
235
|
+
} catch (e) {
|
|
236
|
+
n.push({
|
|
237
|
+
name: c ? "probe-search" : "probe-upsert",
|
|
238
|
+
status: "fail",
|
|
239
|
+
message: e instanceof Error ? e.message : "Smoke test failed with an unknown error."
|
|
240
|
+
});
|
|
241
|
+
} finally {
|
|
242
|
+
try {
|
|
243
|
+
await this.delete({
|
|
244
|
+
id: o,
|
|
245
|
+
namespace: a
|
|
246
|
+
}), n.push({
|
|
247
|
+
name: "probe-cleanup",
|
|
248
|
+
status: "pass",
|
|
249
|
+
message: `Deleted smoke-test record ${o}.`
|
|
250
|
+
});
|
|
251
|
+
} catch (e) {
|
|
252
|
+
n.push({
|
|
253
|
+
name: "probe-cleanup",
|
|
254
|
+
status: "fail",
|
|
255
|
+
message: e instanceof Error ? e.message : `Failed to delete smoke-test record ${o}.`
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
ok: n.every((e) => e.status !== "fail"),
|
|
261
|
+
checks: n,
|
|
262
|
+
namespace: a,
|
|
263
|
+
logicalId: o
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
async ensureIndexExists(e, t) {
|
|
82
267
|
try {
|
|
83
268
|
return {
|
|
84
269
|
created: !1,
|
|
85
270
|
dimensions: (await this.vectorize.describeIndex()).config.dimensions
|
|
86
271
|
};
|
|
87
|
-
} catch (
|
|
88
|
-
if (!e || !
|
|
89
|
-
let
|
|
90
|
-
return
|
|
272
|
+
} catch (r) {
|
|
273
|
+
if (!e || !n(r)) throw r;
|
|
274
|
+
let i = t ?? (await this.inspectEmbeddingDimensions()).targetDimensions;
|
|
275
|
+
return {
|
|
91
276
|
created: !0,
|
|
92
|
-
dimensions:
|
|
277
|
+
dimensions: (await this.vectorize.createIndex(i)).config.dimensions
|
|
93
278
|
};
|
|
94
279
|
}
|
|
95
280
|
}
|
|
@@ -107,8 +292,25 @@ var c = class {
|
|
|
107
292
|
path: r
|
|
108
293
|
};
|
|
109
294
|
}
|
|
295
|
+
async waitForSearchHit(e) {
|
|
296
|
+
let t = Date.now() + e.timeoutMs;
|
|
297
|
+
for (; Date.now() <= t;) {
|
|
298
|
+
if ((await this.search({
|
|
299
|
+
query: e.query,
|
|
300
|
+
namespace: e.namespace,
|
|
301
|
+
maxResults: 5,
|
|
302
|
+
minScore: 0
|
|
303
|
+
})).some((t) => t.logicalId === e.logicalId)) return !0;
|
|
304
|
+
if (Date.now() + e.pollIntervalMs > t) break;
|
|
305
|
+
await this.pause(e.pollIntervalMs);
|
|
306
|
+
}
|
|
307
|
+
return !1;
|
|
308
|
+
}
|
|
309
|
+
async pause(e) {
|
|
310
|
+
await new Promise((t) => setTimeout(t, e));
|
|
311
|
+
}
|
|
110
312
|
};
|
|
111
313
|
//#endregion
|
|
112
|
-
export {
|
|
314
|
+
export { f as CloudflareMemoryService };
|
|
113
315
|
|
|
114
316
|
//# sourceMappingURL=service.js.map
|
package/dist/service.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","names":[],"sources":["../src/service.ts"],"sourcesContent":["import type { OpenClawConfig } from \"openclaw/plugin-sdk/config-runtime\";\nimport { isCloudflareNotFoundError } from \"./cloudflare-api.js\";\nimport { CompanionStore } from \"./companion-store.js\";\nimport { runDoctor } from \"./doctor.js\";\nimport { WorkersAiEmbeddingsClient } from \"./embeddings-client.js\";\nimport { resolveDefaultNamespace } from \"./namespace.js\";\nimport { hydrateInlineRecord, mapRecordForUpsert } from \"./record-mapper.js\";\nimport type {\n\tCompanionRecord,\n\tDoctorReport,\n\tHydratedMemoryRecord,\n\tMemoryRecordInput,\n\tMetadataFilter,\n\tResolvedPluginConfig,\n\tUpsertedMemoryRecord,\n} from \"./types.js\";\nimport { VectorizeClient } from \"./vectorize-client.js\";\n\nexport class CloudflareMemoryService {\n\treadonly embeddings: WorkersAiEmbeddingsClient;\n\treadonly vectorize: VectorizeClient;\n\treadonly companionStore: CompanionStore;\n\n\tconstructor(\n\t\treadonly config: ResolvedPluginConfig,\n\t\treadonly openClawConfig: OpenClawConfig,\n\t) {\n\t\tthis.embeddings = new WorkersAiEmbeddingsClient(config);\n\t\tthis.vectorize = new VectorizeClient(config);\n\t\tthis.companionStore = new CompanionStore(config.companionStorePath);\n\t}\n\n\tresolveNamespace(params: { namespace?: string; sessionKey?: string; agentId?: string; workspaceDir?: string }): string {\n\t\treturn resolveDefaultNamespace({\n\t\t\tfixedNamespace: params.namespace ?? this.config.fixedNamespace,\n\t\t\tsessionKey: params.sessionKey,\n\t\t\tagentId: params.agentId,\n\t\t\tworkspaceDir: params.workspaceDir,\n\t\t});\n\t}\n\n\tasync search(params: {\n\t\tquery: string;\n\t\tnamespace?: string;\n\t\tmaxResults?: number;\n\t\tminScore?: number;\n\t\tfilter?: MetadataFilter;\n\t\tsessionKey?: string;\n\t\tagentId?: string;\n\t\tworkspaceDir?: string;\n\t}): Promise<Array<HydratedMemoryRecord & { score: number }>> {\n\t\tconst namespace = this.resolveNamespace(params);\n\t\tconst vector = await this.embeddings.embedQuery(params.query);\n\t\tconst matches = await this.vectorize.query({\n\t\t\tvector,\n\t\t\tnamespace,\n\t\t\ttopK: params.maxResults ?? this.config.topK,\n\t\t\tfilter: params.filter,\n\t\t});\n\n\t\tconst hydrated = await Promise.all(\n\t\t\tmatches.map(async (match) => {\n\t\t\t\tconst base = hydrateInlineRecord(match);\n\t\t\t\tconst text = base.text ?? (await this.companionStore.get(base.namespace, base.logicalId))?.text ?? \"\";\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttext,\n\t\t\t\t\tscore: match.score ?? 0,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\treturn hydrated.filter((record) => record.score >= (params.minScore ?? this.config.minScore));\n\t}\n\n\tasync get(params: { id: string; namespace?: string; sessionKey?: string; agentId?: string; workspaceDir?: string }): Promise<HydratedMemoryRecord | null> {\n\t\tconst namespace = this.resolveNamespace(params);\n\t\tconst vectorId = `${namespace}::${params.id}`;\n\t\tconst [match] = await this.vectorize.getByIds([vectorId]);\n\t\tif (!match) {\n\t\t\treturn null;\n\t\t}\n\t\tconst base = hydrateInlineRecord(match);\n\t\tconst companion = await this.companionStore.get(base.namespace, base.logicalId);\n\t\treturn {\n\t\t\t...base,\n\t\t\ttext: base.text ?? companion?.text ?? \"\",\n\t\t};\n\t}\n\n\tasync upsert(params: { input: MemoryRecordInput; sessionKey?: string; agentId?: string; workspaceDir?: string }): Promise<UpsertedMemoryRecord> {\n\t\tconst namespace = this.resolveNamespace({\n\t\t\tnamespace: params.input.namespace,\n\t\t\tsessionKey: params.sessionKey,\n\t\t\tagentId: params.agentId,\n\t\t\tworkspaceDir: params.workspaceDir,\n\t\t});\n\t\tconst embedding = await this.embeddings.embedQuery(params.input.text);\n\t\tconst mapped = mapRecordForUpsert({\n\t\t\tinput: params.input,\n\t\t\tnamespace,\n\t\t\tembedding,\n\t\t\tconfig: this.config,\n\t\t});\n\n\t\tif (mapped.companionRecord) {\n\t\t\tawait this.companionStore.upsert(mapped.companionRecord);\n\t\t}\n\n\t\tconst mutationId = await this.vectorize.upsert([mapped.vector]);\n\t\tconst hydrated = await this.get({\n\t\t\tid: mapped.logicalId,\n\t\t\tnamespace,\n\t\t});\n\n\t\treturn {\n\t\t\t...(hydrated ?? this.fromCompanionFallback(mapped.companionRecord, mapped.logicalId, namespace, mapped.path)),\n\t\t\tmutationId,\n\t\t};\n\t}\n\n\tasync delete(params: { id: string; namespace?: string; sessionKey?: string; agentId?: string; workspaceDir?: string }): Promise<string | undefined> {\n\t\tconst namespace = this.resolveNamespace(params);\n\t\tawait this.companionStore.delete(namespace, params.id);\n\t\treturn this.vectorize.deleteByIds([`${namespace}::${params.id}`]);\n\t}\n\n\tasync doctor(options: { createIndexIfMissing?: boolean }): Promise<DoctorReport> {\n\t\treturn runDoctor({\n\t\t\tservice: this,\n\t\t\tcreateIndexIfMissing: options.createIndexIfMissing ?? false,\n\t\t});\n\t}\n\n\tasync ensureIndexExists(createIfMissing: boolean): Promise<{ created: boolean; dimensions: number }> {\n\t\ttry {\n\t\t\tconst description = await this.vectorize.describeIndex();\n\t\t\treturn {\n\t\t\t\tcreated: false,\n\t\t\t\tdimensions: description.config.dimensions,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (!createIfMissing || !isCloudflareNotFoundError(error)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst dimensions = this.config.createIndex.dimensions ?? (await this.embeddings.probeDimensions());\n\t\t\tawait this.vectorize.createIndex(dimensions);\n\t\t\treturn {\n\t\t\t\tcreated: true,\n\t\t\t\tdimensions,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate fromCompanionFallback(companionRecord: CompanionRecord | undefined, logicalId: string, namespace: string, path: string): UpsertedMemoryRecord {\n\t\treturn {\n\t\t\tlogicalId,\n\t\t\tvectorId: `${namespace}::${logicalId}`,\n\t\t\tnamespace,\n\t\t\ttitle: companionRecord?.title,\n\t\t\ttext: companionRecord?.text ?? \"\",\n\t\t\tmetadata: companionRecord?.metadata ?? {},\n\t\t\tsource: companionRecord?.source,\n\t\t\tcreatedAt: companionRecord?.createdAt,\n\t\t\tupdatedAt: companionRecord?.updatedAt,\n\t\t\tpath,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;AAkBA,IAAa,IAAb,MAAqC;CACpC;CACA;CACA;CAEA,YACC,GACA,GACC;AAGD,EALS,KAAA,SAAA,GACA,KAAA,iBAAA,GAET,KAAK,aAAa,IAAI,EAA0B,EAAO,EACvD,KAAK,YAAY,IAAI,EAAgB,EAAO,EAC5C,KAAK,iBAAiB,IAAI,EAAe,EAAO,mBAAmB;;CAGpE,iBAAiB,GAAsG;AACtH,SAAO,EAAwB;GAC9B,gBAAgB,EAAO,aAAa,KAAK,OAAO;GAChD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BACV,MAAM,KAAK,eAAe,OAAO,EAAO,gBAAgB;EAGzD,IAAM,IAAa,MAAM,KAAK,UAAU,OAAO,CAAC,EAAO,OAAO,CAAC;AAM/D,SAAO;GACN,GANgB,MAAM,KAAK,IAAI;IAC/B,IAAI,EAAO;IACX;IACA,CAAC,IAGe,KAAK,sBAAsB,EAAO,iBAAiB,EAAO,WAAW,GAAW,EAAO,KAAK;GAC5G;GACA;;CAGF,MAAM,OAAO,GAAuI;EACnJ,IAAM,IAAY,KAAK,iBAAiB,EAAO;AAE/C,SADA,MAAM,KAAK,eAAe,OAAO,GAAW,EAAO,GAAG,EAC/C,KAAK,UAAU,YAAY,CAAC,GAAG,EAAU,IAAI,EAAO,KAAK,CAAC;;CAGlE,MAAM,OAAO,GAAoE;AAChF,SAAO,EAAU;GAChB,SAAS;GACT,sBAAsB,EAAQ,wBAAwB;GACtD,CAAC;;CAGH,MAAM,kBAAkB,GAA6E;AACpG,MAAI;AAEH,UAAO;IACN,SAAS;IACT,aAHmB,MAAM,KAAK,UAAU,eAAe,EAG/B,OAAO;IAC/B;WACO,GAAO;AACf,OAAI,CAAC,KAAmB,CAAC,EAA0B,EAAM,CACxD,OAAM;GAEP,IAAM,IAAa,KAAK,OAAO,YAAY,cAAe,MAAM,KAAK,WAAW,iBAAiB;AAEjG,UADA,MAAM,KAAK,UAAU,YAAY,EAAW,EACrC;IACN,SAAS;IACT;IACA;;;CAIH,sBAA8B,GAA8C,GAAmB,GAAmB,GAAoC;AACrJ,SAAO;GACN;GACA,UAAU,GAAG,EAAU,IAAI;GAC3B;GACA,OAAO,GAAiB;GACxB,MAAM,GAAiB,QAAQ;GAC/B,UAAU,GAAiB,YAAY,EAAE;GACzC,QAAQ,GAAiB;GACzB,WAAW,GAAiB;GAC5B,WAAW,GAAiB;GAC5B;GACA"}
|
|
1
|
+
{"version":3,"file":"service.js","names":[],"sources":["../src/service.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { OpenClawConfig } from \"openclaw/plugin-sdk/config-runtime\";\nimport { isCloudflareNotFoundError } from \"./cloudflare-api.js\";\nimport { CompanionStore } from \"./companion-store.js\";\nimport { runDoctor } from \"./doctor.js\";\nimport { WorkersAiEmbeddingsClient } from \"./embeddings-client.js\";\nimport { sanitizeNamespace, resolveDefaultNamespace } from \"./namespace.js\";\nimport { hydrateInlineRecord, mapRecordForUpsert } from \"./record-mapper.js\";\nimport type {\n\tCompanionRecord,\n\tDoctorCheck,\n\tDoctorReport,\n\tEmbeddingDimensionsInspection,\n\tHydratedMemoryRecord,\n\tIndexInitializationReport,\n\tMemoryRecordInput,\n\tMetadataFilter,\n\tResolvedPluginConfig,\n\tSmokeTestReport,\n\tUpsertedMemoryRecord,\n\tVectorizeIndexDescription,\n} from \"./types.js\";\nimport { VectorizeClient } from \"./vectorize-client.js\";\n\nconst SMOKE_TEST_TIMEOUT_MS = 12_000;\nconst SMOKE_TEST_POLL_INTERVAL_MS = 1_000;\n\nexport class CloudflareMemoryService {\n\treadonly embeddings: WorkersAiEmbeddingsClient;\n\treadonly vectorize: VectorizeClient;\n\treadonly companionStore: CompanionStore;\n\n\tconstructor(\n\t\treadonly config: ResolvedPluginConfig,\n\t\treadonly openClawConfig: OpenClawConfig,\n\t) {\n\t\tthis.embeddings = new WorkersAiEmbeddingsClient(config);\n\t\tthis.vectorize = new VectorizeClient(config);\n\t\tthis.companionStore = new CompanionStore(config.companionStorePath);\n\t}\n\n\tresolveNamespace(params: { namespace?: string; sessionKey?: string; agentId?: string; workspaceDir?: string }): string {\n\t\treturn resolveDefaultNamespace({\n\t\t\tfixedNamespace: params.namespace ?? this.config.fixedNamespace,\n\t\t\tsessionKey: params.sessionKey,\n\t\t\tagentId: params.agentId,\n\t\t\tworkspaceDir: params.workspaceDir,\n\t\t});\n\t}\n\n\tasync search(params: {\n\t\tquery: string;\n\t\tnamespace?: string;\n\t\tmaxResults?: number;\n\t\tminScore?: number;\n\t\tfilter?: MetadataFilter;\n\t\tsessionKey?: string;\n\t\tagentId?: string;\n\t\tworkspaceDir?: string;\n\t}): Promise<Array<HydratedMemoryRecord & { score: number }>> {\n\t\tconst namespace = this.resolveNamespace(params);\n\t\tconst vector = await this.embeddings.embedQuery(params.query);\n\t\tconst matches = await this.vectorize.query({\n\t\t\tvector,\n\t\t\tnamespace,\n\t\t\ttopK: params.maxResults ?? this.config.topK,\n\t\t\tfilter: params.filter,\n\t\t});\n\n\t\tconst hydrated = await Promise.all(\n\t\t\tmatches.map(async (match) => {\n\t\t\t\tconst base = hydrateInlineRecord(match);\n\t\t\t\tconst text = base.text ?? (await this.companionStore.get(base.namespace, base.logicalId))?.text ?? \"\";\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttext,\n\t\t\t\t\tscore: match.score ?? 0,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\treturn hydrated.filter((record) => record.score >= (params.minScore ?? this.config.minScore));\n\t}\n\n\tasync get(params: { id: string; namespace?: string; sessionKey?: string; agentId?: string; workspaceDir?: string }): Promise<HydratedMemoryRecord | null> {\n\t\tconst namespace = this.resolveNamespace(params);\n\t\tconst vectorId = `${namespace}::${params.id}`;\n\t\tconst [match] = await this.vectorize.getByIds([vectorId]);\n\t\tif (!match) {\n\t\t\treturn null;\n\t\t}\n\t\tconst base = hydrateInlineRecord(match);\n\t\tconst companion = await this.companionStore.get(base.namespace, base.logicalId);\n\t\treturn {\n\t\t\t...base,\n\t\t\ttext: base.text ?? companion?.text ?? \"\",\n\t\t};\n\t}\n\n\tasync upsert(params: { input: MemoryRecordInput; sessionKey?: string; agentId?: string; workspaceDir?: string }): Promise<UpsertedMemoryRecord> {\n\t\tconst namespace = this.resolveNamespace({\n\t\t\tnamespace: params.input.namespace,\n\t\t\tsessionKey: params.sessionKey,\n\t\t\tagentId: params.agentId,\n\t\t\tworkspaceDir: params.workspaceDir,\n\t\t});\n\t\tconst embedding = await this.embeddings.embedQuery(params.input.text);\n\t\tconst mapped = mapRecordForUpsert({\n\t\t\tinput: params.input,\n\t\t\tnamespace,\n\t\t\tembedding,\n\t\t\tconfig: this.config,\n\t\t});\n\n\t\tif (mapped.companionRecord) {\n\t\t\tawait this.companionStore.upsert(mapped.companionRecord);\n\t\t}\n\n\t\tconst mutationId = await this.vectorize.upsert([mapped.vector]);\n\t\tconst hydrated = await this.get({\n\t\t\tid: mapped.logicalId,\n\t\t\tnamespace,\n\t\t});\n\n\t\treturn {\n\t\t\t...(hydrated ?? this.fromCompanionFallback(mapped.companionRecord, mapped.logicalId, namespace, mapped.path)),\n\t\t\tmutationId,\n\t\t};\n\t}\n\n\tasync delete(params: { id: string; namespace?: string; sessionKey?: string; agentId?: string; workspaceDir?: string }): Promise<string | undefined> {\n\t\tconst namespace = this.resolveNamespace(params);\n\t\tawait this.companionStore.delete(namespace, params.id);\n\t\treturn this.vectorize.deleteByIds([`${namespace}::${params.id}`]);\n\t}\n\n\tasync doctor(options: { createIndexIfMissing?: boolean }): Promise<DoctorReport> {\n\t\treturn runDoctor({\n\t\t\tservice: this,\n\t\t\tcreateIndexIfMissing: options.createIndexIfMissing ?? false,\n\t\t});\n\t}\n\n\tasync inspectEmbeddingDimensions(): Promise<EmbeddingDimensionsInspection> {\n\t\tconst embeddingDimensions = await this.embeddings.probeDimensions();\n\t\tconst configuredDimensions = this.config.createIndex.dimensions;\n\t\treturn {\n\t\t\tembeddingDimensions,\n\t\t\tconfiguredDimensions,\n\t\t\tconfiguredDimensionsMatchModel: configuredDimensions === undefined || configuredDimensions === embeddingDimensions,\n\t\t\ttargetDimensions: embeddingDimensions,\n\t\t};\n\t}\n\n\tasync describeIndexIfExists(): Promise<VectorizeIndexDescription | null> {\n\t\ttry {\n\t\t\treturn await this.vectorize.describeIndex();\n\t\t} catch (error) {\n\t\t\tif (isCloudflareNotFoundError(error)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync initializeIndex(options?: { recreateIfDimensionMismatch?: boolean }): Promise<IndexInitializationReport> {\n\t\tconst recreateIfDimensionMismatch = options?.recreateIfDimensionMismatch ?? true;\n\t\tconst checks: DoctorCheck[] = [];\n\t\tchecks.push({\n\t\t\tname: \"credentials\",\n\t\t\tstatus: \"pass\",\n\t\t\tmessage: `Using Cloudflare account ${this.config.accountId} and Vectorize index ${this.config.indexName}.`,\n\t\t});\n\n\t\tconst embedding = await this.inspectEmbeddingDimensions();\n\t\tchecks.push({\n\t\t\tname: \"workers-ai-embeddings\",\n\t\t\tstatus: \"pass\",\n\t\t\tmessage: `Workers AI model ${this.config.model} returned ${embedding.embeddingDimensions} dimensions.`,\n\t\t});\n\t\tif (embedding.configuredDimensions !== undefined) {\n\t\t\tchecks.push({\n\t\t\t\tname: \"create-index-dimensions\",\n\t\t\t\tstatus: embedding.configuredDimensionsMatchModel ? \"pass\" : \"warn\",\n\t\t\t\tmessage: embedding.configuredDimensionsMatchModel\n\t\t\t\t\t? `Configured createIndex.dimensions matches the embedding model (${embedding.embeddingDimensions}).`\n\t\t\t\t\t: `Configured createIndex.dimensions (${embedding.configuredDimensions}) does not match the embedding model (${embedding.embeddingDimensions}). Using the live embedding dimensions for initialization.`,\n\t\t\t});\n\t\t}\n\n\t\tconst existingIndex = await this.describeIndexIfExists();\n\t\tlet created = false;\n\t\tlet recreated = false;\n\t\tlet indexDimensions = existingIndex?.config.dimensions;\n\n\t\tif (!existingIndex) {\n\t\t\tconst createdIndex = await this.vectorize.createIndex(embedding.targetDimensions);\n\t\t\tcreated = true;\n\t\t\tindexDimensions = createdIndex.config.dimensions;\n\t\t\tchecks.push({\n\t\t\t\tname: \"vectorize-index\",\n\t\t\t\tstatus: \"pass\",\n\t\t\t\tmessage: `Created Vectorize index \"${this.config.indexName}\" with ${indexDimensions} dimensions.`,\n\t\t\t});\n\t\t} else if (existingIndex.config.dimensions === embedding.targetDimensions) {\n\t\t\tchecks.push({\n\t\t\t\tname: \"vectorize-index\",\n\t\t\t\tstatus: \"pass\",\n\t\t\t\tmessage: `Vectorize index \"${this.config.indexName}\" already uses ${existingIndex.config.dimensions} dimensions.`,\n\t\t\t});\n\t\t} else if (!recreateIfDimensionMismatch) {\n\t\t\tchecks.push({\n\t\t\t\tname: \"vectorize-index\",\n\t\t\t\tstatus: \"fail\",\n\t\t\t\tmessage: `Vectorize index \"${this.config.indexName}\" uses ${existingIndex.config.dimensions} dimensions, but the embedding model requires ${embedding.targetDimensions}. Recreate the index or rerun init with recreation enabled.`,\n\t\t\t});\n\t\t} else {\n\t\t\tawait this.vectorize.deleteIndex();\n\t\t\tconst recreatedIndex = await this.vectorize.createIndex(embedding.targetDimensions);\n\t\t\trecreated = true;\n\t\t\tindexDimensions = recreatedIndex.config.dimensions;\n\t\t\tchecks.push({\n\t\t\t\tname: \"vectorize-index\",\n\t\t\t\tstatus: \"pass\",\n\t\t\t\tmessage: `Recreated Vectorize index \"${this.config.indexName}\" from ${existingIndex.config.dimensions} to ${indexDimensions} dimensions.`,\n\t\t\t});\n\t\t}\n\n\t\tchecks.push({\n\t\t\tname: \"dimension-match\",\n\t\t\tstatus: indexDimensions === embedding.embeddingDimensions ? \"pass\" : \"fail\",\n\t\t\tmessage:\n\t\t\t\tindexDimensions === embedding.embeddingDimensions\n\t\t\t\t\t? \"Embedding dimensions match the Vectorize index.\"\n\t\t\t\t\t: `Embedding dimensions (${embedding.embeddingDimensions}) do not match the Vectorize index dimensions (${indexDimensions ?? \"unknown\"}).`,\n\t\t});\n\t\tchecks.push({\n\t\t\tname: \"metadata-filters\",\n\t\t\tstatus: this.config.metadataIndexedFields.length > 0 ? \"pass\" : \"warn\",\n\t\t\tmessage:\n\t\t\t\tthis.config.metadataIndexedFields.length > 0\n\t\t\t\t\t? `Configured metadata-index guidance for: ${this.config.metadataIndexedFields.join(\", \")}.`\n\t\t\t\t\t: \"No metadataIndexedFields configured. Add metadata indexes in Cloudflare before relying on filter-heavy queries.\",\n\t\t});\n\n\t\treturn {\n\t\t\tok: checks.every((check) => check.status !== \"fail\"),\n\t\t\tchecks,\n\t\t\tcreated,\n\t\t\trecreated,\n\t\t\tembeddingDimensions: embedding.embeddingDimensions,\n\t\t\tindexDimensions,\n\t\t};\n\t}\n\n\tasync runSmokeTest(options?: { timeoutMs?: number; pollIntervalMs?: number }): Promise<SmokeTestReport> {\n\t\tconst checks: DoctorCheck[] = [];\n\t\tchecks.push({\n\t\t\tname: \"credentials\",\n\t\t\tstatus: \"pass\",\n\t\t\tmessage: `Using Cloudflare account ${this.config.accountId} and Vectorize index ${this.config.indexName}.`,\n\t\t});\n\n\t\tconst embedding = await this.inspectEmbeddingDimensions();\n\t\tchecks.push({\n\t\t\tname: \"workers-ai-embeddings\",\n\t\t\tstatus: \"pass\",\n\t\t\tmessage: `Workers AI model ${this.config.model} returned ${embedding.embeddingDimensions} dimensions.`,\n\t\t});\n\t\tif (embedding.configuredDimensions !== undefined) {\n\t\t\tchecks.push({\n\t\t\t\tname: \"create-index-dimensions\",\n\t\t\t\tstatus: embedding.configuredDimensionsMatchModel ? \"pass\" : \"warn\",\n\t\t\t\tmessage: embedding.configuredDimensionsMatchModel\n\t\t\t\t\t? `Configured createIndex.dimensions matches the embedding model (${embedding.embeddingDimensions}).`\n\t\t\t\t\t: `Configured createIndex.dimensions (${embedding.configuredDimensions}) does not match the embedding model (${embedding.embeddingDimensions}). Using the live embedding dimensions for validation.`,\n\t\t\t});\n\t\t}\n\n\t\tconst existingIndex = await this.describeIndexIfExists();\n\t\tif (!existingIndex) {\n\t\t\tchecks.push({\n\t\t\t\tname: \"vectorize-index\",\n\t\t\t\tstatus: \"fail\",\n\t\t\t\tmessage: `Vectorize index \"${this.config.indexName}\" was not found. Run \"openclaw cf-memory init\" before rerunning this test.`,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tchecks,\n\t\t\t\tnamespace: \"n/a\",\n\t\t\t\tlogicalId: \"n/a\",\n\t\t\t};\n\t\t}\n\n\t\tchecks.push({\n\t\t\tname: \"vectorize-index\",\n\t\t\tstatus: \"pass\",\n\t\t\tmessage: `Vectorize index \"${this.config.indexName}\" is reachable.`,\n\t\t});\n\t\tif (existingIndex.config.dimensions !== embedding.embeddingDimensions) {\n\t\t\tchecks.push({\n\t\t\t\tname: \"dimension-match\",\n\t\t\t\tstatus: \"fail\",\n\t\t\t\tmessage: `Embedding dimensions (${embedding.embeddingDimensions}) do not match the Vectorize index dimensions (${existingIndex.config.dimensions}). Run \"openclaw cf-memory init\" to repair the index.`,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tchecks,\n\t\t\t\tnamespace: \"n/a\",\n\t\t\t\tlogicalId: \"n/a\",\n\t\t\t};\n\t\t}\n\n\t\tchecks.push({\n\t\t\tname: \"dimension-match\",\n\t\t\tstatus: \"pass\",\n\t\t\tmessage: \"Embedding dimensions match the Vectorize index.\",\n\t\t});\n\n\t\tconst namespace = sanitizeNamespace(`cf-memory-test-${randomUUID()}`);\n\t\tconst logicalId = `cf-memory-test-${randomUUID()}`;\n\t\tconst probeText = `OpenClaw Cloudflare memory smoke test ${logicalId}`;\n\t\tlet probeUpserted = false;\n\n\t\ttry {\n\t\t\tawait this.upsert({\n\t\t\t\tinput: {\n\t\t\t\t\tid: logicalId,\n\t\t\t\t\tnamespace,\n\t\t\t\t\ttext: probeText,\n\t\t\t\t\tsource: \"cf-memory-test\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tprobe: true,\n\t\t\t\t\t\tprobeId: logicalId,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t});\n\t\t\tprobeUpserted = true;\n\t\t\tchecks.push({\n\t\t\t\tname: \"probe-upsert\",\n\t\t\t\tstatus: \"pass\",\n\t\t\t\tmessage: `Inserted smoke-test record ${logicalId} in namespace ${namespace}.`,\n\t\t\t});\n\n\t\t\tconst found = await this.waitForSearchHit({\n\t\t\t\tquery: probeText,\n\t\t\t\tnamespace,\n\t\t\t\tlogicalId,\n\t\t\t\ttimeoutMs: options?.timeoutMs ?? SMOKE_TEST_TIMEOUT_MS,\n\t\t\t\tpollIntervalMs: options?.pollIntervalMs ?? SMOKE_TEST_POLL_INTERVAL_MS,\n\t\t\t});\n\t\t\tchecks.push({\n\t\t\t\tname: \"probe-search\",\n\t\t\t\tstatus: found ? \"pass\" : \"fail\",\n\t\t\t\tmessage: found\n\t\t\t\t\t? \"Semantic search returned the smoke-test record.\"\n\t\t\t\t\t: `Semantic search did not return the smoke-test record within ${(options?.timeoutMs ?? SMOKE_TEST_TIMEOUT_MS) / 1000} seconds.`,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tchecks.push({\n\t\t\t\tname: probeUpserted ? \"probe-search\" : \"probe-upsert\",\n\t\t\t\tstatus: \"fail\",\n\t\t\t\tmessage: error instanceof Error ? error.message : \"Smoke test failed with an unknown error.\",\n\t\t\t});\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait this.delete({ id: logicalId, namespace });\n\t\t\t\tchecks.push({\n\t\t\t\t\tname: \"probe-cleanup\",\n\t\t\t\t\tstatus: \"pass\",\n\t\t\t\t\tmessage: `Deleted smoke-test record ${logicalId}.`,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tchecks.push({\n\t\t\t\t\tname: \"probe-cleanup\",\n\t\t\t\t\tstatus: \"fail\",\n\t\t\t\t\tmessage: error instanceof Error ? error.message : `Failed to delete smoke-test record ${logicalId}.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tok: checks.every((check) => check.status !== \"fail\"),\n\t\t\tchecks,\n\t\t\tnamespace,\n\t\t\tlogicalId,\n\t\t};\n\t}\n\n\tasync ensureIndexExists(createIfMissing: boolean, targetDimensions?: number): Promise<{ created: boolean; dimensions: number }> {\n\t\ttry {\n\t\t\tconst description = await this.vectorize.describeIndex();\n\t\t\treturn {\n\t\t\t\tcreated: false,\n\t\t\t\tdimensions: description.config.dimensions,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (!createIfMissing || !isCloudflareNotFoundError(error)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst dimensions = targetDimensions ?? (await this.inspectEmbeddingDimensions()).targetDimensions;\n\t\t\tconst createdIndex = await this.vectorize.createIndex(dimensions);\n\t\t\treturn {\n\t\t\t\tcreated: true,\n\t\t\t\tdimensions: createdIndex.config.dimensions,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate fromCompanionFallback(companionRecord: CompanionRecord | undefined, logicalId: string, namespace: string, path: string): UpsertedMemoryRecord {\n\t\treturn {\n\t\t\tlogicalId,\n\t\t\tvectorId: `${namespace}::${logicalId}`,\n\t\t\tnamespace,\n\t\t\ttitle: companionRecord?.title,\n\t\t\ttext: companionRecord?.text ?? \"\",\n\t\t\tmetadata: companionRecord?.metadata ?? {},\n\t\t\tsource: companionRecord?.source,\n\t\t\tcreatedAt: companionRecord?.createdAt,\n\t\t\tupdatedAt: companionRecord?.updatedAt,\n\t\t\tpath,\n\t\t};\n\t}\n\n\tprivate async waitForSearchHit(params: { query: string; namespace: string; logicalId: string; timeoutMs: number; pollIntervalMs: number }): Promise<boolean> {\n\t\tconst deadline = Date.now() + params.timeoutMs;\n\t\twhile (Date.now() <= deadline) {\n\t\t\tconst results = await this.search({\n\t\t\t\tquery: params.query,\n\t\t\t\tnamespace: params.namespace,\n\t\t\t\tmaxResults: 5,\n\t\t\t\tminScore: 0,\n\t\t\t});\n\t\t\tif (results.some((record) => record.logicalId === params.logicalId)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (Date.now() + params.pollIntervalMs > deadline) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tawait this.pause(params.pollIntervalMs);\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate async pause(ms: number): Promise<void> {\n\t\tawait new Promise((resolve) => setTimeout(resolve, ms));\n\t}\n}\n"],"mappings":";;;;;;;;;AAwBA,IAAM,IAAwB,MACxB,IAA8B,KAEvB,IAAb,MAAqC;CACpC;CACA;CACA;CAEA,YACC,GACA,GACC;AA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AY,WAAW,GAAS,EAAG,CAAC"}
|
package/dist/types/service.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-runtime";
|
|
2
2
|
import { CompanionStore } from "./companion-store.js";
|
|
3
3
|
import { WorkersAiEmbeddingsClient } from "./embeddings-client.js";
|
|
4
|
-
import type { DoctorReport, HydratedMemoryRecord, MemoryRecordInput, MetadataFilter, ResolvedPluginConfig, UpsertedMemoryRecord } from "./types.js";
|
|
4
|
+
import type { DoctorReport, EmbeddingDimensionsInspection, HydratedMemoryRecord, IndexInitializationReport, MemoryRecordInput, MetadataFilter, ResolvedPluginConfig, SmokeTestReport, UpsertedMemoryRecord, VectorizeIndexDescription } from "./types.js";
|
|
5
5
|
import { VectorizeClient } from "./vectorize-client.js";
|
|
6
6
|
export declare class CloudflareMemoryService {
|
|
7
7
|
readonly config: ResolvedPluginConfig;
|
|
@@ -51,9 +51,20 @@ export declare class CloudflareMemoryService {
|
|
|
51
51
|
doctor(options: {
|
|
52
52
|
createIndexIfMissing?: boolean;
|
|
53
53
|
}): Promise<DoctorReport>;
|
|
54
|
-
|
|
54
|
+
inspectEmbeddingDimensions(): Promise<EmbeddingDimensionsInspection>;
|
|
55
|
+
describeIndexIfExists(): Promise<VectorizeIndexDescription | null>;
|
|
56
|
+
initializeIndex(options?: {
|
|
57
|
+
recreateIfDimensionMismatch?: boolean;
|
|
58
|
+
}): Promise<IndexInitializationReport>;
|
|
59
|
+
runSmokeTest(options?: {
|
|
60
|
+
timeoutMs?: number;
|
|
61
|
+
pollIntervalMs?: number;
|
|
62
|
+
}): Promise<SmokeTestReport>;
|
|
63
|
+
ensureIndexExists(createIfMissing: boolean, targetDimensions?: number): Promise<{
|
|
55
64
|
created: boolean;
|
|
56
65
|
dimensions: number;
|
|
57
66
|
}>;
|
|
58
67
|
private fromCompanionFallback;
|
|
68
|
+
private waitForSearchHit;
|
|
69
|
+
private pause;
|
|
59
70
|
}
|
package/dist/types/types.d.ts
CHANGED
|
@@ -130,6 +130,26 @@ export type DoctorReport = {
|
|
|
130
130
|
ok: boolean;
|
|
131
131
|
checks: DoctorCheck[];
|
|
132
132
|
};
|
|
133
|
+
export type EmbeddingDimensionsInspection = {
|
|
134
|
+
embeddingDimensions: number;
|
|
135
|
+
configuredDimensions?: number;
|
|
136
|
+
configuredDimensionsMatchModel: boolean;
|
|
137
|
+
targetDimensions: number;
|
|
138
|
+
};
|
|
139
|
+
export type IndexInitializationReport = {
|
|
140
|
+
ok: boolean;
|
|
141
|
+
checks: DoctorCheck[];
|
|
142
|
+
created: boolean;
|
|
143
|
+
recreated: boolean;
|
|
144
|
+
embeddingDimensions: number;
|
|
145
|
+
indexDimensions?: number;
|
|
146
|
+
};
|
|
147
|
+
export type SmokeTestReport = {
|
|
148
|
+
ok: boolean;
|
|
149
|
+
checks: DoctorCheck[];
|
|
150
|
+
namespace: string;
|
|
151
|
+
logicalId: string;
|
|
152
|
+
};
|
|
133
153
|
export type MigrationSourceMode = "paths" | "default-provider";
|
|
134
154
|
export type MigrationDuplicateStrategy = "overwrite" | "skip" | "fail";
|
|
135
155
|
export type MigrationNamespaceStrategy = "single-target" | "path";
|
|
@@ -4,6 +4,7 @@ export declare class VectorizeClient {
|
|
|
4
4
|
constructor(config: ResolvedPluginConfig);
|
|
5
5
|
describeIndex(): Promise<VectorizeIndexDescription>;
|
|
6
6
|
createIndex(dimensions: number, metric?: import("./types.js").VectorizeMetric): Promise<VectorizeIndexDescription>;
|
|
7
|
+
deleteIndex(): Promise<void>;
|
|
7
8
|
upsert(vectors: VectorizeVector[]): Promise<string | undefined>;
|
|
8
9
|
query(params: {
|
|
9
10
|
vector: number[];
|
package/dist/vectorize-client.js
CHANGED
|
@@ -25,6 +25,13 @@ var t = class {
|
|
|
25
25
|
})
|
|
26
26
|
});
|
|
27
27
|
}
|
|
28
|
+
async deleteIndex() {
|
|
29
|
+
await e({
|
|
30
|
+
url: this.config.vectorizeBaseUrl,
|
|
31
|
+
apiToken: this.config.apiToken,
|
|
32
|
+
method: "DELETE"
|
|
33
|
+
});
|
|
34
|
+
}
|
|
28
35
|
async upsert(t) {
|
|
29
36
|
let n = t.map((e) => JSON.stringify(e)).join("\n");
|
|
30
37
|
return (await e({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vectorize-client.js","names":[],"sources":["../src/vectorize-client.ts"],"sourcesContent":["import { requestCloudflare } from \"./cloudflare-api.js\";\nimport type { MetadataFilter, ResolvedPluginConfig, VectorizeIndexDescription, VectorizeQueryMatch, VectorizeVector } from \"./types.js\";\n\ntype MutationResponse = {\n\tmutationId?: string;\n};\n\ntype QueryResponse = {\n\tcount?: number;\n\tmatches?: VectorizeQueryMatch[];\n};\n\nexport class VectorizeClient {\n\tconstructor(private readonly config: ResolvedPluginConfig) {}\n\n\tasync describeIndex(): Promise<VectorizeIndexDescription> {\n\t\treturn requestCloudflare<VectorizeIndexDescription>({\n\t\t\turl: this.config.vectorizeBaseUrl,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tmethod: \"GET\",\n\t\t});\n\t}\n\n\tasync createIndex(dimensions: number, metric = this.config.createIndex.metric): Promise<VectorizeIndexDescription> {\n\t\treturn requestCloudflare<VectorizeIndexDescription>({\n\t\t\turl: `${this.config.apiBaseUrl}/accounts/${this.config.accountId}/vectorize/v2/indexes`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({\n\t\t\t\tname: this.config.indexName,\n\t\t\t\tdescription: this.config.createIndex.description,\n\t\t\t\tconfig: {\n\t\t\t\t\tdimensions,\n\t\t\t\t\tmetric,\n\t\t\t\t},\n\t\t\t}),\n\t\t});\n\t}\n\n\tasync upsert(vectors: VectorizeVector[]): Promise<string | undefined> {\n\t\tconst body = vectors.map((vector) => JSON.stringify(vector)).join(\"\\n\");\n\t\tconst result = await requestCloudflare<MutationResponse>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/upsert`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"application/x-ndjson\",\n\t\t\t},\n\t\t\tbody,\n\t\t});\n\t\treturn result.mutationId;\n\t}\n\n\tasync query(params: {\n\t\tvector: number[];\n\t\tnamespace?: string;\n\t\ttopK?: number;\n\t\tfilter?: MetadataFilter;\n\t\treturnValues?: boolean;\n\t}): Promise<VectorizeQueryMatch[]> {\n\t\tconst result = await requestCloudflare<QueryResponse>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/query`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({\n\t\t\t\tvector: params.vector,\n\t\t\t\ttopK: params.topK ?? this.config.topK,\n\t\t\t\tfilter: params.filter,\n\t\t\t\tnamespace: params.namespace,\n\t\t\t\treturnValues: params.returnValues ?? false,\n\t\t\t}),\n\t\t});\n\t\treturn result.matches ?? [];\n\t}\n\n\tasync getByIds(ids: string[]): Promise<VectorizeQueryMatch[]> {\n\t\tif (ids.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\treturn requestCloudflare<VectorizeQueryMatch[]>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/get_by_ids`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({ ids }),\n\t\t});\n\t}\n\n\tasync deleteByIds(ids: string[]): Promise<string | undefined> {\n\t\tif (ids.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst result = await requestCloudflare<MutationResponse>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/delete_by_ids`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({ ids }),\n\t\t});\n\t\treturn result.mutationId;\n\t}\n}\n"],"mappings":";;AAYA,IAAa,IAAb,MAA6B;CAC5B,YAAY,GAA+C;AAA9B,OAAA,SAAA;;CAE7B,MAAM,gBAAoD;AACzD,SAAO,EAA6C;GACnD,KAAK,KAAK,OAAO;GACjB,UAAU,KAAK,OAAO;GACtB,QA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ACY"}
|
|
1
|
+
{"version":3,"file":"vectorize-client.js","names":[],"sources":["../src/vectorize-client.ts"],"sourcesContent":["import { requestCloudflare } from \"./cloudflare-api.js\";\nimport type { MetadataFilter, ResolvedPluginConfig, VectorizeIndexDescription, VectorizeQueryMatch, VectorizeVector } from \"./types.js\";\n\ntype MutationResponse = {\n\tmutationId?: string;\n};\n\ntype QueryResponse = {\n\tcount?: number;\n\tmatches?: VectorizeQueryMatch[];\n};\n\nexport class VectorizeClient {\n\tconstructor(private readonly config: ResolvedPluginConfig) {}\n\n\tasync describeIndex(): Promise<VectorizeIndexDescription> {\n\t\treturn requestCloudflare<VectorizeIndexDescription>({\n\t\t\turl: this.config.vectorizeBaseUrl,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tmethod: \"GET\",\n\t\t});\n\t}\n\n\tasync createIndex(dimensions: number, metric = this.config.createIndex.metric): Promise<VectorizeIndexDescription> {\n\t\treturn requestCloudflare<VectorizeIndexDescription>({\n\t\t\turl: `${this.config.apiBaseUrl}/accounts/${this.config.accountId}/vectorize/v2/indexes`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({\n\t\t\t\tname: this.config.indexName,\n\t\t\t\tdescription: this.config.createIndex.description,\n\t\t\t\tconfig: {\n\t\t\t\t\tdimensions,\n\t\t\t\t\tmetric,\n\t\t\t\t},\n\t\t\t}),\n\t\t});\n\t}\n\n\tasync deleteIndex(): Promise<void> {\n\t\tawait requestCloudflare<unknown>({\n\t\t\turl: this.config.vectorizeBaseUrl,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tmethod: \"DELETE\",\n\t\t});\n\t}\n\n\tasync upsert(vectors: VectorizeVector[]): Promise<string | undefined> {\n\t\tconst body = vectors.map((vector) => JSON.stringify(vector)).join(\"\\n\");\n\t\tconst result = await requestCloudflare<MutationResponse>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/upsert`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"application/x-ndjson\",\n\t\t\t},\n\t\t\tbody,\n\t\t});\n\t\treturn result.mutationId;\n\t}\n\n\tasync query(params: {\n\t\tvector: number[];\n\t\tnamespace?: string;\n\t\ttopK?: number;\n\t\tfilter?: MetadataFilter;\n\t\treturnValues?: boolean;\n\t}): Promise<VectorizeQueryMatch[]> {\n\t\tconst result = await requestCloudflare<QueryResponse>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/query`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({\n\t\t\t\tvector: params.vector,\n\t\t\t\ttopK: params.topK ?? this.config.topK,\n\t\t\t\tfilter: params.filter,\n\t\t\t\tnamespace: params.namespace,\n\t\t\t\treturnValues: params.returnValues ?? false,\n\t\t\t}),\n\t\t});\n\t\treturn result.matches ?? [];\n\t}\n\n\tasync getByIds(ids: string[]): Promise<VectorizeQueryMatch[]> {\n\t\tif (ids.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\treturn requestCloudflare<VectorizeQueryMatch[]>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/get_by_ids`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({ ids }),\n\t\t});\n\t}\n\n\tasync deleteByIds(ids: string[]): Promise<string | undefined> {\n\t\tif (ids.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst result = await requestCloudflare<MutationResponse>({\n\t\t\turl: `${this.config.vectorizeBaseUrl}/delete_by_ids`,\n\t\t\tapiToken: this.config.apiToken,\n\t\t\tbody: JSON.stringify({ ids }),\n\t\t});\n\t\treturn result.mutationId;\n\t}\n}\n"],"mappings":";;AAYA,IAAa,IAAb,MAA6B;CAC5B,YAAY,GAA+C;AAA9B,OAAA,SAAA;;CAE7B,MAAM,gBAAoD;AACzD,SAAO,EAA6C;GACnD,KAAK,KAAK,OAAO;GACjB,UAAU,KAAK,OAAO;GACtB,QAAQ;GACR,CAAC;;CAGH,MAAM,YAAY,G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