metainsight-context-engine 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,219 @@
1
+ /**
2
+ * COS Operations — Unified CRUD Operations Layer
3
+ *
4
+ * Provides all data operations (upload / search / download / delete) for the
5
+ * Cloud Context Engine. Built on top of the bootstrap layer (`cos-bootstrap.ts`)
6
+ * and routes requests to the correct dataset / COS prefix based on `category`.
7
+ *
8
+ * Architecture:
9
+ * cos-bootstrap.ts → cos-operations.ts → engine.ts / index.ts
10
+ * (init + low-level) (CRUD operations) (business logic)
11
+ *
12
+ * The constructor accepts a `BootstrapOutcome`, so consumers only need to call
13
+ * `bootstrap()` once and pass the result here — no duplicate initialization.
14
+ *
15
+ * Multimodal retrieval:
16
+ * - Text/memory queries route to DocSearch datasets (category="memory")
17
+ * - Image queries route to ImageSearch datasets (category="image")
18
+ * - The search template is automatically selected per-dataset based on
19
+ * the dataset's `templateId` (Official:ImageSearch → "ImageSearch").
20
+ *
21
+ * Key improvements over the old `cloud-client.ts`:
22
+ * - Upload path uses the dataset's `cosPrefix` (not hardcoded `uploads/`)
23
+ * - Search routes to the correct dataset name based on category
24
+ * - Automatic template selection for multimodal (DocSearch / ImageSearch)
25
+ * - Download support (getObject from COS)
26
+ * - Delete support (deleteObject from COS)
27
+ */
28
+ import type { BootstrapOutcome, ResolvedCosConfig } from './cos-bootstrap.js';
29
+ export interface CloudSearchResult {
30
+ snippet: string;
31
+ score: number;
32
+ docId?: string;
33
+ category?: 'memory' | 'document';
34
+ /** Signed HTTPS URL for image results (only present for ImageSearch results). */
35
+ imageUrl?: string;
36
+ metadata?: Record<string, unknown>;
37
+ }
38
+ export interface CloudUploadResult {
39
+ docId: string;
40
+ key: string;
41
+ status: string;
42
+ /** Error message when status === 'error'. */
43
+ error?: string;
44
+ }
45
+ export interface CloudDownloadResult {
46
+ content: string;
47
+ key: string;
48
+ metadata?: Record<string, unknown>;
49
+ }
50
+ export interface CloudSearchOptions {
51
+ category?: string;
52
+ maxResults?: number;
53
+ minScore?: number;
54
+ }
55
+ export interface CloudUploadOptions {
56
+ category?: string;
57
+ docId?: string;
58
+ metadata?: Record<string, unknown>;
59
+ /**
60
+ * When set, overrides the default COS key construction
61
+ * (`{cosPrefix}{docId}.md`) and uses this value as the full COS key.
62
+ *
63
+ * Useful for placing files outside the dataset's cosPrefix directory,
64
+ * e.g. workspace identity files that should live at
65
+ * `openclaw-{agentId}/agents.md` instead of
66
+ * `openclaw-{agentId}/workspace/agents.md`.
67
+ */
68
+ customKey?: string;
69
+ }
70
+ export interface CloudDownloadOptions {
71
+ category?: string;
72
+ }
73
+ export declare class CosOperations {
74
+ private readonly cos;
75
+ private readonly config;
76
+ /** Search template — DocSearch or ImageSearch. Default: DocSearch. */
77
+ private readonly template;
78
+ /** Default match threshold (0-100). CI recommends 80, we default to 60. */
79
+ private readonly matchThreshold;
80
+ /**
81
+ * Create a CosOperations instance from a successful bootstrap outcome.
82
+ *
83
+ * @throws if the bootstrap outcome indicates failure
84
+ */
85
+ constructor(outcome: BootstrapOutcome, opts?: {
86
+ template?: string;
87
+ matchThreshold?: number;
88
+ });
89
+ /**
90
+ * Resolve the dataset definition for a given category.
91
+ *
92
+ * Routing rules:
93
+ * 1. If a dataset's `cosPrefix` starts with `{category}/`, use it.
94
+ * (legacy layout: cosPrefix="memory/" matches category="memory")
95
+ * 2. If a dataset's `cosPrefix` contains `/{category}/`, use it.
96
+ * (multi-agent layout: cosPrefix="openclaw-xxx/workspace/memory/" matches category="memory")
97
+ * 3. If a dataset's `name` contains the category, use it.
98
+ * 4. Otherwise, fall back to the first dataset in config.
99
+ */
100
+ private resolveDataset;
101
+ /**
102
+ * Semantic / hybrid search against the CI dataset.
103
+ *
104
+ * Routing:
105
+ * - Image datasets (Official:ImageSearch) → `POST /datasetquery/imagesearch`
106
+ * with only `DatasetName` + `Mode: "text"` (simplified temporary API).
107
+ * - All other datasets → `POST /datasetquery/hybridsearch` with full params.
108
+ *
109
+ * DocSearch: SearchText is truncated to 60 UTF-8 chars (CI API limit).
110
+ */
111
+ search(query: string, opts?: CloudSearchOptions): Promise<CloudSearchResult[]>;
112
+ /**
113
+ * Upload content to the COS bucket for CI indexing.
114
+ *
115
+ * Content is stored as a Markdown file under `{cosPrefix}{docId}.md`.
116
+ * CI will pick it up via the dataset binding and index it automatically.
117
+ * Metadata is stored in COS custom headers (`x-cos-meta-*`).
118
+ *
119
+ * The upload path is derived from the dataset's `cosPrefix` — not hardcoded.
120
+ * Category routing is handled by `resolveDataset()` which selects the
121
+ * correct dataset (and thus the correct cosPrefix). We do NOT append
122
+ * `{category}/` again — that would create nested directories like
123
+ * `memory/memory/`.
124
+ */
125
+ upload(content: string, opts?: CloudUploadOptions): Promise<CloudUploadResult>;
126
+ /**
127
+ * Batch upload multiple items in parallel (with concurrency limit).
128
+ *
129
+ * Individual upload failures are captured per-item (status='error')
130
+ * instead of aborting the entire batch — this prevents one bad item
131
+ * from causing all remaining items to be dropped.
132
+ */
133
+ uploadBatch(items: Array<{
134
+ content: string;
135
+ opts?: CloudUploadOptions;
136
+ }>, concurrency?: number): Promise<CloudUploadResult[]>;
137
+ /**
138
+ * Upload a binary file (e.g. image) to the COS bucket.
139
+ *
140
+ * Unlike `upload()` which stores text content as Markdown, this method
141
+ * accepts a Buffer and stores the file with its original content type.
142
+ * The file is placed under the provided COS key path.
143
+ *
144
+ * @param buffer Raw file content as a Buffer.
145
+ * @param key Full COS key (e.g. "openclaw-main/asset/photo.png").
146
+ * @param contentType MIME type (e.g. "image/png"). Default: "application/octet-stream".
147
+ * @param metadata Optional metadata to attach as COS custom headers.
148
+ * @returns Upload result with the COS key.
149
+ */
150
+ uploadBinary(buffer: Buffer, key: string, contentType?: string, metadata?: Record<string, unknown>): Promise<CloudUploadResult>;
151
+ /**
152
+ * Check whether a COS object exists at the given key.
153
+ *
154
+ * Uses `headObject` which returns metadata without downloading the body.
155
+ * Returns true if the object exists, false otherwise.
156
+ */
157
+ objectExists(key: string): Promise<boolean>;
158
+ /**
159
+ * Download a document from the COS bucket by its key.
160
+ *
161
+ * @param docKey Full COS key (e.g. "memory/memory/abc.md") or a short docId.
162
+ * If a short docId is provided, it will be resolved via the dataset cosPrefix.
163
+ */
164
+ download(docKey: string, opts?: CloudDownloadOptions): Promise<CloudDownloadResult>;
165
+ /**
166
+ * Delete a document from the COS bucket.
167
+ *
168
+ * @param docKey Full COS key or short docId (resolved via dataset cosPrefix).
169
+ */
170
+ deleteDoc(docKey: string, opts?: CloudDownloadOptions): Promise<{
171
+ deleted: boolean;
172
+ key: string;
173
+ }>;
174
+ /** Get the resolved COS config (useful for diagnostics). */
175
+ getConfig(): ResolvedCosConfig;
176
+ /** Get all available dataset names. */
177
+ getDatasetNames(): string[];
178
+ /**
179
+ * Get the agent-level COS key prefix (without trailing "/workspace/").
180
+ *
181
+ * For multi-agent setups (agentId set), this returns `openclaw-{agentId}/`.
182
+ * For legacy setups (no agentId), this returns an empty string.
183
+ *
184
+ * Useful for placing files alongside the workspace directory rather than
185
+ * inside it. E.g. workspace files like AGENTS.md should go to
186
+ * `openclaw-{agentId}/agents.md` (agent root) instead of
187
+ * `openclaw-{agentId}/workspace/agents.md` (inside workspace).
188
+ */
189
+ getAgentPrefix(): string;
190
+ /**
191
+ * Generate a signed (temporary) download URL for a COS object.
192
+ *
193
+ * @param cosUri Full COS URI (e.g. `cos://bucket-123/image/photo.jpg`)
194
+ * or a plain COS key (e.g. `image/photo.jpg`).
195
+ * @param expiresInSeconds URL validity duration. Default: 3600 (1 hour).
196
+ * @returns A signed HTTPS URL that can be used to access the object.
197
+ */
198
+ getSignedUrl(cosUri: string, expiresInSeconds?: number): string;
199
+ /**
200
+ * Map CI DocSearch results to CloudSearchResult[].
201
+ */
202
+ private mapDocResults;
203
+ /**
204
+ * Map CI ImageSearch results to CloudSearchResult[].
205
+ * Each result includes a signed URL for direct image access.
206
+ */
207
+ private mapImageResults;
208
+ /**
209
+ * Extract a short doc ID from a COS URI.
210
+ * e.g. `cos://bucket-123/memory/abc.md` → `abc.md`
211
+ * e.g. `cos://bucket-123/memory/IMAP__SMTP Email Tool.md`
212
+ * → `IMAP/SMTP Email Tool.md`
213
+ *
214
+ * Note: docIds stored on COS have `/` replaced with `__` (see `sanitizeDocId`).
215
+ * This method reverses that transformation so callers see the original name.
216
+ */
217
+ private cosUriToDocId;
218
+ }
219
+ //# sourceMappingURL=cos-operations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cos-operations.d.ts","sourceRoot":"","sources":["../cos-operations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAIH,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAmB,MAAM,oBAAoB,CAAC;AAO/F,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,QAAQ,GAAG,UAAU,CAAC;IACjC,iFAAiF;IACjF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,6CAA6C;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC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