@khanglvm/outline-cli 0.1.7 → 0.1.8
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/CHANGELOG.md +5 -0
- package/README.md +262 -12
- package/package.json +1 -1
- package/src/agent-skills.js +70 -27
- package/src/cli.js +2 -0
- package/src/entry-integrity-manifest.generated.js +13 -9
- package/src/memory-store.js +2368 -0
- package/src/tool-arg-schemas.js +1646 -90
- package/src/tools.extended.js +2160 -173
- package/src/tools.js +224 -7
- package/src/tools.mutation.js +496 -90
- package/src/tools.navigation.js +547 -26
|
@@ -0,0 +1,2368 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
import { assertPerformAction } from "./action-gate.js";
|
|
5
|
+
import { defaultTmpDir } from "./config-store.js";
|
|
6
|
+
import { ApiError, CliError } from "./errors.js";
|
|
7
|
+
import { compactValue, ensureStringArray, mapLimit, toInteger } from "./utils.js";
|
|
8
|
+
|
|
9
|
+
const STORE_VERSION = 1;
|
|
10
|
+
const DEFAULT_MAX_ENTRIES_PER_PROFILE = 1000;
|
|
11
|
+
const MAX_SOURCE_TOOLS = 8;
|
|
12
|
+
const OBSERVED_TOOL_PREFIXES = [
|
|
13
|
+
"documents.",
|
|
14
|
+
"collections.",
|
|
15
|
+
"users.",
|
|
16
|
+
"groups.",
|
|
17
|
+
"templates.",
|
|
18
|
+
"search.",
|
|
19
|
+
"federated.",
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
function defaultMemoryFile() {
|
|
23
|
+
if (process.env.OUTLINE_CLI_MEMORY_FILE) {
|
|
24
|
+
return path.resolve(process.env.OUTLINE_CLI_MEMORY_FILE);
|
|
25
|
+
}
|
|
26
|
+
if (process.env.OUTLINE_AGENT_MEMORY_FILE) {
|
|
27
|
+
return path.resolve(process.env.OUTLINE_AGENT_MEMORY_FILE);
|
|
28
|
+
}
|
|
29
|
+
return path.join(path.dirname(defaultTmpDir()), "memory", "observations.json");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function blankStore() {
|
|
33
|
+
return {
|
|
34
|
+
version: STORE_VERSION,
|
|
35
|
+
profiles: {},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function loadStore(file = defaultMemoryFile()) {
|
|
40
|
+
try {
|
|
41
|
+
const raw = await fs.readFile(file, "utf8");
|
|
42
|
+
const parsed = JSON.parse(raw);
|
|
43
|
+
if (!parsed || typeof parsed !== "object") {
|
|
44
|
+
return blankStore();
|
|
45
|
+
}
|
|
46
|
+
if (!parsed.profiles || typeof parsed.profiles !== "object") {
|
|
47
|
+
parsed.profiles = {};
|
|
48
|
+
}
|
|
49
|
+
if (!parsed.version) {
|
|
50
|
+
parsed.version = STORE_VERSION;
|
|
51
|
+
}
|
|
52
|
+
return parsed;
|
|
53
|
+
} catch (err) {
|
|
54
|
+
if (err?.code === "ENOENT") {
|
|
55
|
+
return blankStore();
|
|
56
|
+
}
|
|
57
|
+
throw new Error(`Failed to read memory store ${file}: ${err.message}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function saveStore(store, file = defaultMemoryFile()) {
|
|
62
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
63
|
+
await fs.writeFile(file, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function profileBucket(store, profileId) {
|
|
67
|
+
if (!store.profiles[profileId] || typeof store.profiles[profileId] !== "object") {
|
|
68
|
+
store.profiles[profileId] = {
|
|
69
|
+
entries: {},
|
|
70
|
+
updatedAt: null,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
if (!store.profiles[profileId].entries || typeof store.profiles[profileId].entries !== "object") {
|
|
74
|
+
store.profiles[profileId].entries = {};
|
|
75
|
+
}
|
|
76
|
+
return store.profiles[profileId];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function normalizeText(value) {
|
|
80
|
+
return String(value || "")
|
|
81
|
+
.trim()
|
|
82
|
+
.toLowerCase()
|
|
83
|
+
.replace(/[\W_]+/g, " ")
|
|
84
|
+
.replace(/\s+/g, " ")
|
|
85
|
+
.trim();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function tokenize(value) {
|
|
89
|
+
return normalizeText(value).split(" ").filter((token) => token.length >= 2);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function addReferenceAliases(set, value) {
|
|
93
|
+
const raw = String(value || "").trim();
|
|
94
|
+
if (!raw) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const parsed = new URL(raw, raw.startsWith("/") ? "https://outline.local" : undefined);
|
|
100
|
+
const segments = parsed.pathname.split("/").filter(Boolean);
|
|
101
|
+
const lowerSegments = segments.map((segment) => segment.toLowerCase());
|
|
102
|
+
const docIndex = lowerSegments.indexOf("doc");
|
|
103
|
+
const collectionIndex = lowerSegments.indexOf("collection");
|
|
104
|
+
const shareIndex = lowerSegments.indexOf("share");
|
|
105
|
+
const docSegment = docIndex >= 0 && segments[docIndex + 1] ? segments[docIndex + 1] : "";
|
|
106
|
+
const collectionSegment = collectionIndex >= 0 && segments[collectionIndex + 1] ? segments[collectionIndex + 1] : "";
|
|
107
|
+
const shareSegment = shareIndex >= 0 && segments[shareIndex + 1] ? segments[shareIndex + 1] : "";
|
|
108
|
+
const hashUrlId = String(parsed.hash || "").match(/(?:^#|[#/])d-([A-Za-z0-9_-]{6,})/i)?.[1] || "";
|
|
109
|
+
const urlSegment = docSegment || collectionSegment;
|
|
110
|
+
const docSuffix = String(urlSegment || "").match(/-([A-Za-z0-9]{6,})$/)?.[1] || "";
|
|
111
|
+
|
|
112
|
+
for (const candidate of [docSegment, collectionSegment, shareSegment, hashUrlId, docSuffix]) {
|
|
113
|
+
if (candidate) {
|
|
114
|
+
set.add(candidate);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (urlSegment) {
|
|
118
|
+
const titleAlias = urlSegment
|
|
119
|
+
.replace(docSuffix ? new RegExp(`-${docSuffix}$`) : /$/, "")
|
|
120
|
+
.replace(/[-_]+/g, " ")
|
|
121
|
+
.trim();
|
|
122
|
+
if (titleAlias) {
|
|
123
|
+
set.add(titleAlias);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
} catch {
|
|
127
|
+
// Non-URL references are handled by the caller's raw/normalized aliases.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function addAlias(set, value) {
|
|
132
|
+
const raw = String(value || "").trim();
|
|
133
|
+
if (!raw) {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
set.add(raw);
|
|
137
|
+
addReferenceAliases(set, raw);
|
|
138
|
+
const normalized = normalizeText(raw);
|
|
139
|
+
if (normalized && normalized !== raw) {
|
|
140
|
+
set.add(normalized);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function aliasesForQuery(value) {
|
|
145
|
+
const aliases = new Set();
|
|
146
|
+
addAlias(aliases, value);
|
|
147
|
+
return [...aliases].map((item) => String(item || "").trim()).filter(Boolean);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function fallbackQueryForReference(value) {
|
|
151
|
+
const aliases = aliasesForQuery(value);
|
|
152
|
+
const candidates = aliases.filter((item) =>
|
|
153
|
+
normalizeText(item) && !/^https?:\/\//i.test(item) && !item.startsWith("/")
|
|
154
|
+
);
|
|
155
|
+
return candidates.find((item) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(item))
|
|
156
|
+
|| candidates.find((item) => /\s/.test(item))
|
|
157
|
+
|| candidates[0]
|
|
158
|
+
|| String(value || "");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function normalizeQueryArgs(args = {}, output = {}) {
|
|
162
|
+
const bucket = [];
|
|
163
|
+
if (args.query) {
|
|
164
|
+
bucket.push(String(args.query));
|
|
165
|
+
}
|
|
166
|
+
if (args.question) {
|
|
167
|
+
bucket.push(String(args.question));
|
|
168
|
+
}
|
|
169
|
+
if (args.queries) {
|
|
170
|
+
bucket.push(...ensureStringArray(args.queries, "queries"));
|
|
171
|
+
}
|
|
172
|
+
if (args.questions) {
|
|
173
|
+
for (const question of args.questions) {
|
|
174
|
+
if (typeof question === "string") {
|
|
175
|
+
bucket.push(question);
|
|
176
|
+
} else if (question?.question || question?.query) {
|
|
177
|
+
bucket.push(String(question.question || question.query));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (output.query) {
|
|
182
|
+
bucket.push(String(output.query));
|
|
183
|
+
}
|
|
184
|
+
if (Array.isArray(output.result?.queries)) {
|
|
185
|
+
bucket.push(...output.result.queries.map((item) => String(item)));
|
|
186
|
+
}
|
|
187
|
+
return [...new Set(bucket.map((item) => item.trim()).filter(Boolean))];
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function normalizeDocumentEntity(row, meta) {
|
|
191
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
const source = row.document && typeof row.document === "object" ? row.document : row;
|
|
195
|
+
if (!source.id || !source.title) {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const aliases = new Set();
|
|
200
|
+
addAlias(aliases, source.id);
|
|
201
|
+
addAlias(aliases, source.title);
|
|
202
|
+
addAlias(aliases, source.urlId);
|
|
203
|
+
addAlias(aliases, source.url);
|
|
204
|
+
|
|
205
|
+
return compactValue({
|
|
206
|
+
type: "document",
|
|
207
|
+
id: String(source.id),
|
|
208
|
+
title: source.title,
|
|
209
|
+
collectionId: source.collectionId,
|
|
210
|
+
parentDocumentId: source.parentDocumentId,
|
|
211
|
+
revision: source.revision,
|
|
212
|
+
updatedAt: source.updatedAt,
|
|
213
|
+
publishedAt: source.publishedAt,
|
|
214
|
+
urlId: source.urlId,
|
|
215
|
+
url: source.url,
|
|
216
|
+
aliases: [...aliases],
|
|
217
|
+
score: row.score,
|
|
218
|
+
ranking: row.ranking,
|
|
219
|
+
queries: Array.isArray(row.queries) ? row.queries.map((item) => String(item)) : meta.queries,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function normalizeCollectionEntity(row) {
|
|
224
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
if (!row.id || !row.name) {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const aliases = new Set();
|
|
232
|
+
addAlias(aliases, row.id);
|
|
233
|
+
addAlias(aliases, row.name);
|
|
234
|
+
addAlias(aliases, row.urlId);
|
|
235
|
+
addAlias(aliases, row.url);
|
|
236
|
+
|
|
237
|
+
return compactValue({
|
|
238
|
+
type: "collection",
|
|
239
|
+
id: String(row.id),
|
|
240
|
+
name: row.name,
|
|
241
|
+
description: row.description,
|
|
242
|
+
permission: row.permission,
|
|
243
|
+
sharing: row.sharing,
|
|
244
|
+
updatedAt: row.updatedAt,
|
|
245
|
+
color: row.color,
|
|
246
|
+
icon: row.icon,
|
|
247
|
+
urlId: row.urlId,
|
|
248
|
+
url: row.url,
|
|
249
|
+
aliases: [...aliases],
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function normalizeUserEntity(row) {
|
|
254
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
const source = row.user && typeof row.user === "object" ? row.user : row;
|
|
258
|
+
if (!source.id || (!source.name && !source.email)) {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const aliases = new Set();
|
|
263
|
+
addAlias(aliases, source.id);
|
|
264
|
+
addAlias(aliases, source.name);
|
|
265
|
+
addAlias(aliases, source.email);
|
|
266
|
+
|
|
267
|
+
return compactValue({
|
|
268
|
+
type: "user",
|
|
269
|
+
id: String(source.id),
|
|
270
|
+
name: source.name,
|
|
271
|
+
email: source.email,
|
|
272
|
+
avatarUrl: source.avatarUrl,
|
|
273
|
+
role: source.role,
|
|
274
|
+
isAdmin: source.isAdmin,
|
|
275
|
+
isSuspended: source.isSuspended,
|
|
276
|
+
lastActiveAt: source.lastActiveAt,
|
|
277
|
+
updatedAt: source.updatedAt,
|
|
278
|
+
aliases: [...aliases],
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function normalizeGroupEntity(row) {
|
|
283
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) {
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
const source = row.group && typeof row.group === "object" ? row.group : row;
|
|
287
|
+
if (!source.id || !source.name) {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const aliases = new Set();
|
|
292
|
+
addAlias(aliases, source.id);
|
|
293
|
+
addAlias(aliases, source.name);
|
|
294
|
+
|
|
295
|
+
return compactValue({
|
|
296
|
+
type: "group",
|
|
297
|
+
id: String(source.id),
|
|
298
|
+
name: source.name,
|
|
299
|
+
memberCount: source.memberCount,
|
|
300
|
+
createdAt: source.createdAt,
|
|
301
|
+
updatedAt: source.updatedAt,
|
|
302
|
+
aliases: [...aliases],
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function normalizeTemplateEntity(row) {
|
|
307
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
const source = row.template && typeof row.template === "object" ? row.template : row;
|
|
311
|
+
if (!source.id || !source.title) {
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const aliases = new Set();
|
|
316
|
+
addAlias(aliases, source.id);
|
|
317
|
+
addAlias(aliases, source.title);
|
|
318
|
+
addAlias(aliases, source.name);
|
|
319
|
+
|
|
320
|
+
return compactValue({
|
|
321
|
+
type: "template",
|
|
322
|
+
id: String(source.id),
|
|
323
|
+
title: source.title,
|
|
324
|
+
name: source.name,
|
|
325
|
+
collectionId: source.collectionId,
|
|
326
|
+
createdAt: source.createdAt,
|
|
327
|
+
updatedAt: source.updatedAt,
|
|
328
|
+
aliases: [...aliases],
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function collectEntities(value, meta, out = [], depth = 0) {
|
|
333
|
+
if (depth > 7 || value === null || value === undefined) {
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
if (Array.isArray(value)) {
|
|
337
|
+
for (const item of value) {
|
|
338
|
+
collectEntities(item, meta, out, depth + 1);
|
|
339
|
+
}
|
|
340
|
+
return out;
|
|
341
|
+
}
|
|
342
|
+
if (typeof value !== "object") {
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (meta.kind === "document") {
|
|
347
|
+
const doc = normalizeDocumentEntity(value, meta);
|
|
348
|
+
if (doc) {
|
|
349
|
+
out.push(doc);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (meta.kind === "collection") {
|
|
353
|
+
const collection = normalizeCollectionEntity(value);
|
|
354
|
+
if (collection) {
|
|
355
|
+
out.push(collection);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (meta.kind === "user") {
|
|
359
|
+
const user = normalizeUserEntity(value);
|
|
360
|
+
if (user) {
|
|
361
|
+
out.push(user);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (meta.kind === "group") {
|
|
365
|
+
const group = normalizeGroupEntity(value);
|
|
366
|
+
if (group) {
|
|
367
|
+
out.push(group);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (meta.kind === "template") {
|
|
371
|
+
const template = normalizeTemplateEntity(value);
|
|
372
|
+
if (template) {
|
|
373
|
+
out.push(template);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
for (const key of ["data", "items", "merged", "expanded", "candidates", "documents", "nodes", "perQuery", "result"]) {
|
|
378
|
+
if (Object.prototype.hasOwnProperty.call(value, key)) {
|
|
379
|
+
collectEntities(value[key], meta, out, depth + 1);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (value.document && typeof value.document === "object") {
|
|
383
|
+
collectEntities(value.document, { ...meta, kind: "document" }, out, depth + 1);
|
|
384
|
+
}
|
|
385
|
+
if (value.user && typeof value.user === "object") {
|
|
386
|
+
collectEntities(value.user, { ...meta, kind: "user" }, out, depth + 1);
|
|
387
|
+
}
|
|
388
|
+
if (value.group && typeof value.group === "object") {
|
|
389
|
+
collectEntities(value.group, { ...meta, kind: "group" }, out, depth + 1);
|
|
390
|
+
}
|
|
391
|
+
if (value.template && typeof value.template === "object") {
|
|
392
|
+
collectEntities(value.template, { ...meta, kind: "template" }, out, depth + 1);
|
|
393
|
+
}
|
|
394
|
+
return out;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function observationKind(toolName, output) {
|
|
398
|
+
const method = output?.method || "";
|
|
399
|
+
if (String(toolName).startsWith("templates.") || String(method).startsWith("templates.")) {
|
|
400
|
+
return "template";
|
|
401
|
+
}
|
|
402
|
+
if (String(toolName).startsWith("users.") || String(method).startsWith("users.")) {
|
|
403
|
+
return "user";
|
|
404
|
+
}
|
|
405
|
+
if (String(toolName).startsWith("groups.") || String(method).startsWith("groups.")) {
|
|
406
|
+
return "group";
|
|
407
|
+
}
|
|
408
|
+
if (String(toolName).startsWith("collections.") || String(method).startsWith("collections.")) {
|
|
409
|
+
return "collection";
|
|
410
|
+
}
|
|
411
|
+
if (
|
|
412
|
+
String(toolName).startsWith("documents.") ||
|
|
413
|
+
String(toolName).startsWith("search.") ||
|
|
414
|
+
String(toolName).startsWith("federated.") ||
|
|
415
|
+
String(method).startsWith("documents.")
|
|
416
|
+
) {
|
|
417
|
+
return "document";
|
|
418
|
+
}
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function observationName(toolName, output = {}) {
|
|
423
|
+
return String(output?.method || toolName || "");
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function isAuthoritativeObservation(toolName, output = {}) {
|
|
427
|
+
const name = observationName(toolName, output);
|
|
428
|
+
return /(^|\.)(info|create|update|safe_update|restore|apply_patch|apply_patch_safe|create_from_template)$/.test(name);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function isDeleteObservation(toolName, output = {}) {
|
|
432
|
+
const name = observationName(toolName, output);
|
|
433
|
+
return /(^|\.)(delete|permanent_delete|empty_trash)$/.test(name);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function shouldObserve(ctx, toolName) {
|
|
437
|
+
if (ctx?.memory?.enabled !== true) {
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
if (!ctx?.profile?.id) {
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
if (String(toolName || "").startsWith("memory.")) {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
return OBSERVED_TOOL_PREFIXES.some((prefix) => String(toolName || "").startsWith(prefix)) || toolName === "api.call";
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function mergeEntry(existing = {}, next, meta) {
|
|
450
|
+
const now = meta.observedAt;
|
|
451
|
+
const aliases = new Set([...(existing.aliases || []), ...(next.aliases || [])]);
|
|
452
|
+
const queries = new Set([...(existing.queries || []), ...(next.queries || []), ...meta.queries]);
|
|
453
|
+
const sourceTools = [
|
|
454
|
+
{
|
|
455
|
+
tool: meta.tool,
|
|
456
|
+
observedAt: now,
|
|
457
|
+
...(meta.method ? { method: meta.method } : {}),
|
|
458
|
+
},
|
|
459
|
+
...(existing.sourceTools || []),
|
|
460
|
+
];
|
|
461
|
+
|
|
462
|
+
return compactValue({
|
|
463
|
+
...existing,
|
|
464
|
+
...next,
|
|
465
|
+
aliases: [...aliases].slice(0, 40),
|
|
466
|
+
queries: [...queries].slice(0, 40),
|
|
467
|
+
sourceTools: sourceTools
|
|
468
|
+
.filter((item, index, arr) => arr.findIndex((candidate) => candidate.tool === item.tool && candidate.method === item.method) === index)
|
|
469
|
+
.slice(0, MAX_SOURCE_TOOLS),
|
|
470
|
+
firstObservedAt: existing.firstObservedAt || now,
|
|
471
|
+
lastObservedAt: now,
|
|
472
|
+
observedCount: Number(existing.observedCount || 0) + 1,
|
|
473
|
+
deletedAt: existing.deletedAt && !meta.authoritative ? existing.deletedAt : undefined,
|
|
474
|
+
deletedBy: existing.deletedAt && !meta.authoritative ? existing.deletedBy : undefined,
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function pruneProfile(bucket, maxEntries = DEFAULT_MAX_ENTRIES_PER_PROFILE) {
|
|
479
|
+
const entries = Object.entries(bucket.entries || {});
|
|
480
|
+
if (entries.length <= maxEntries) {
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
entries.sort((a, b) => String(b[1].lastObservedAt || "").localeCompare(String(a[1].lastObservedAt || "")));
|
|
484
|
+
bucket.entries = Object.fromEntries(entries.slice(0, maxEntries));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function operationSucceeded(output = {}) {
|
|
488
|
+
const result = output.result && typeof output.result === "object" ? output.result : {};
|
|
489
|
+
if (result.success === false || result.ok === false) {
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
if (output.result?.deleted === false) {
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
return true;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function deletedObservationIds(args = {}, output = {}) {
|
|
499
|
+
const ids = [];
|
|
500
|
+
if (args.id) {
|
|
501
|
+
ids.push(String(args.id));
|
|
502
|
+
}
|
|
503
|
+
if (args.ids) {
|
|
504
|
+
ids.push(...ensureStringArray(args.ids, "ids"));
|
|
505
|
+
}
|
|
506
|
+
if (args.body?.id) {
|
|
507
|
+
ids.push(String(args.body.id));
|
|
508
|
+
}
|
|
509
|
+
if (args.body?.ids) {
|
|
510
|
+
ids.push(...ensureStringArray(args.body.ids, "body.ids"));
|
|
511
|
+
}
|
|
512
|
+
if (output.result?.id) {
|
|
513
|
+
ids.push(String(output.result.id));
|
|
514
|
+
}
|
|
515
|
+
if (output.result?.documentId) {
|
|
516
|
+
ids.push(String(output.result.documentId));
|
|
517
|
+
}
|
|
518
|
+
return [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function markDeletedEntries(bucket, ids, meta) {
|
|
522
|
+
const now = meta.observedAt;
|
|
523
|
+
let count = 0;
|
|
524
|
+
for (const id of ids) {
|
|
525
|
+
const key = `${meta.kind}:${id}`;
|
|
526
|
+
const existing = bucket.entries[key] || {
|
|
527
|
+
type: meta.kind,
|
|
528
|
+
id,
|
|
529
|
+
aliases: [id],
|
|
530
|
+
firstObservedAt: now,
|
|
531
|
+
observedCount: 0,
|
|
532
|
+
};
|
|
533
|
+
bucket.entries[key] = compactValue({
|
|
534
|
+
...existing,
|
|
535
|
+
type: meta.kind,
|
|
536
|
+
id,
|
|
537
|
+
aliases: existing.aliases || [id],
|
|
538
|
+
deletedAt: now,
|
|
539
|
+
deletedBy: meta.tool,
|
|
540
|
+
lastObservedAt: now,
|
|
541
|
+
observedCount: Number(existing.observedCount || 0) + 1,
|
|
542
|
+
sourceTools: [
|
|
543
|
+
{
|
|
544
|
+
tool: meta.tool,
|
|
545
|
+
observedAt: now,
|
|
546
|
+
...(meta.method ? { method: meta.method } : {}),
|
|
547
|
+
},
|
|
548
|
+
...(existing.sourceTools || []),
|
|
549
|
+
].slice(0, MAX_SOURCE_TOOLS),
|
|
550
|
+
}) || {};
|
|
551
|
+
count += 1;
|
|
552
|
+
}
|
|
553
|
+
return count;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function isStaleHydrationStatus(status) {
|
|
557
|
+
return [403, 404, 410].includes(Number(status));
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async function tombstoneHydrationMiss(ctx, candidate, endpoint, status) {
|
|
561
|
+
if (!ctx?.profile?.id || !candidate?.id || !isStaleHydrationStatus(status)) {
|
|
562
|
+
return { tombstoned: false };
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const file = ctx.memory?.file || defaultMemoryFile();
|
|
566
|
+
const store = await loadStore(file);
|
|
567
|
+
const bucket = profileBucket(store, ctx.profile.id);
|
|
568
|
+
const meta = {
|
|
569
|
+
kind: ["collection", "user", "group", "template"].includes(candidate.type) ? candidate.type : "document",
|
|
570
|
+
tool: "memory.resolve",
|
|
571
|
+
method: endpoint,
|
|
572
|
+
observedAt: new Date().toISOString(),
|
|
573
|
+
};
|
|
574
|
+
const count = markDeletedEntries(bucket, [candidate.id], meta);
|
|
575
|
+
if (count > 0) {
|
|
576
|
+
bucket.updatedAt = meta.observedAt;
|
|
577
|
+
await saveStore(store, file);
|
|
578
|
+
}
|
|
579
|
+
return { tombstoned: count > 0, file, updatedAt: bucket.updatedAt };
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
export async function recordToolObservation(ctx, toolName, args = {}, output = {}) {
|
|
583
|
+
if (!shouldObserve(ctx, toolName)) {
|
|
584
|
+
return { observed: false, count: 0 };
|
|
585
|
+
}
|
|
586
|
+
const kind = observationKind(toolName, output);
|
|
587
|
+
if (!kind) {
|
|
588
|
+
return { observed: false, count: 0 };
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const meta = {
|
|
592
|
+
kind,
|
|
593
|
+
tool: toolName,
|
|
594
|
+
method: output?.method,
|
|
595
|
+
queries: normalizeQueryArgs(args, output),
|
|
596
|
+
observedAt: new Date().toISOString(),
|
|
597
|
+
authoritative: isAuthoritativeObservation(toolName, output),
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
const file = ctx.memory?.file || defaultMemoryFile();
|
|
601
|
+
const store = await loadStore(file);
|
|
602
|
+
const bucket = profileBucket(store, ctx.profile.id);
|
|
603
|
+
|
|
604
|
+
if (isDeleteObservation(toolName, output) && operationSucceeded(output)) {
|
|
605
|
+
const deletedIds = deletedObservationIds(args, output);
|
|
606
|
+
const count = markDeletedEntries(bucket, deletedIds, meta);
|
|
607
|
+
if (count > 0) {
|
|
608
|
+
bucket.updatedAt = meta.observedAt;
|
|
609
|
+
await saveStore(store, file);
|
|
610
|
+
return { observed: true, count, tombstoned: true };
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
const entities = collectEntities(output, meta);
|
|
615
|
+
if (entities.length === 0) {
|
|
616
|
+
return { observed: false, count: 0 };
|
|
617
|
+
}
|
|
618
|
+
const seenKeys = new Set();
|
|
619
|
+
|
|
620
|
+
for (const entity of entities) {
|
|
621
|
+
const key = `${entity.type}:${entity.id}`;
|
|
622
|
+
if (seenKeys.has(key)) {
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
seenKeys.add(key);
|
|
626
|
+
bucket.entries[key] = mergeEntry(bucket.entries[key], entity, meta);
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
bucket.updatedAt = meta.observedAt;
|
|
630
|
+
pruneProfile(bucket, toInteger(ctx.memory?.maxEntriesPerProfile, DEFAULT_MAX_ENTRIES_PER_PROFILE));
|
|
631
|
+
await saveStore(store, file);
|
|
632
|
+
return { observed: true, count: seenKeys.size };
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function scoreEntry(entry, query) {
|
|
636
|
+
const rawQuery = String(query || "").trim();
|
|
637
|
+
const queryAliases = aliasesForQuery(rawQuery);
|
|
638
|
+
const queryNorms = queryAliases.map((item) => normalizeText(item)).filter(Boolean);
|
|
639
|
+
const primaryQueryNorm = queryNorms[0] || normalizeText(rawQuery);
|
|
640
|
+
const aliases = [entry.id, entry.urlId, entry.url, entry.title, entry.name, entry.email, ...(entry.aliases || [])]
|
|
641
|
+
.map((item) => String(item || "").trim())
|
|
642
|
+
.filter(Boolean);
|
|
643
|
+
const normalizedAliases = aliases.map((item) => normalizeText(item)).filter(Boolean);
|
|
644
|
+
|
|
645
|
+
if (queryAliases.some((queryAlias) => aliases.includes(queryAlias))) {
|
|
646
|
+
return 100;
|
|
647
|
+
}
|
|
648
|
+
if (queryNorms.some((queryNorm) => normalizedAliases.includes(queryNorm))) {
|
|
649
|
+
return 100;
|
|
650
|
+
}
|
|
651
|
+
if (queryAliases.some((queryAlias) => entry.id === queryAlias || entry.urlId === queryAlias || entry.url === queryAlias)) {
|
|
652
|
+
return 100;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
let best = 0;
|
|
656
|
+
for (const alias of normalizedAliases) {
|
|
657
|
+
for (const queryNorm of queryNorms) {
|
|
658
|
+
if (!alias || !queryNorm) {
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
if (alias.includes(queryNorm) || queryNorm.includes(alias)) {
|
|
662
|
+
best = Math.max(best, 82);
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
const queryTokens = tokenize(queryNorm);
|
|
666
|
+
if (queryTokens.length > 0) {
|
|
667
|
+
const aliasTokens = new Set(tokenize(alias));
|
|
668
|
+
const matched = queryTokens.filter((token) => aliasTokens.has(token)).length;
|
|
669
|
+
if (matched > 0) {
|
|
670
|
+
best = Math.max(best, 45 + Math.round((matched / queryTokens.length) * 35));
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const queryHits = (entry.queries || []).map((item) => normalizeText(item));
|
|
677
|
+
if (queryHits.some((item) => item.includes(primaryQueryNorm) || primaryQueryNorm.includes(item))) {
|
|
678
|
+
best = Math.max(best, 70);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
return best;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function shapeEntry(entry, score) {
|
|
685
|
+
return compactValue({
|
|
686
|
+
type: entry.type,
|
|
687
|
+
id: entry.id,
|
|
688
|
+
title: entry.title,
|
|
689
|
+
name: entry.name,
|
|
690
|
+
email: entry.email,
|
|
691
|
+
avatarUrl: entry.avatarUrl,
|
|
692
|
+
role: entry.role,
|
|
693
|
+
isAdmin: entry.isAdmin,
|
|
694
|
+
isSuspended: entry.isSuspended,
|
|
695
|
+
memberCount: entry.memberCount,
|
|
696
|
+
createdAt: entry.createdAt,
|
|
697
|
+
urlId: entry.urlId,
|
|
698
|
+
collectionId: entry.collectionId,
|
|
699
|
+
parentDocumentId: entry.parentDocumentId,
|
|
700
|
+
revision: entry.revision,
|
|
701
|
+
updatedAt: entry.updatedAt,
|
|
702
|
+
publishedAt: entry.publishedAt,
|
|
703
|
+
url: entry.url,
|
|
704
|
+
lastObservedAt: entry.lastObservedAt,
|
|
705
|
+
observedCount: entry.observedCount,
|
|
706
|
+
score,
|
|
707
|
+
sourceTools: entry.sourceTools,
|
|
708
|
+
queries: entry.queries,
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
async function findMemoryMatches(ctx, args) {
|
|
713
|
+
const query = args.query || args.id || args.urlId || args.url;
|
|
714
|
+
if (!query) {
|
|
715
|
+
throw new CliError("memory.lookup requires args.query, args.id, args.urlId, or args.url");
|
|
716
|
+
}
|
|
717
|
+
const file = ctx.memory?.file || defaultMemoryFile();
|
|
718
|
+
const store = await loadStore(file);
|
|
719
|
+
const profileId = args.profile || ctx.profile?.id;
|
|
720
|
+
const bucket = profileId ? store.profiles?.[profileId] : null;
|
|
721
|
+
const limit = Math.max(1, toInteger(args.limit, 10));
|
|
722
|
+
const minScore = Math.max(0, toInteger(args.minScore, 1));
|
|
723
|
+
const maxAgeHours = args.maxAgeHours === undefined ? null : Math.max(0, Number(args.maxAgeHours));
|
|
724
|
+
const cutoff = maxAgeHours === null ? null : Date.now() - maxAgeHours * 3600 * 1000;
|
|
725
|
+
|
|
726
|
+
const rows = [];
|
|
727
|
+
for (const entry of Object.values(bucket?.entries || {})) {
|
|
728
|
+
if (!entry || entry.deletedAt) {
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
if (args.type && entry.type !== args.type) {
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
if (cutoff !== null) {
|
|
735
|
+
const observedAt = Date.parse(entry.lastObservedAt || "");
|
|
736
|
+
if (!Number.isFinite(observedAt) || observedAt < cutoff) {
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
const score = scoreEntry(entry, query);
|
|
741
|
+
if (score >= minScore) {
|
|
742
|
+
rows.push(shapeEntry(entry, score));
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
rows.sort((a, b) => {
|
|
747
|
+
if (b.score !== a.score) {
|
|
748
|
+
return b.score - a.score;
|
|
749
|
+
}
|
|
750
|
+
return String(b.lastObservedAt || "").localeCompare(String(a.lastObservedAt || ""));
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
return {
|
|
754
|
+
query,
|
|
755
|
+
file,
|
|
756
|
+
profileId,
|
|
757
|
+
bucket,
|
|
758
|
+
total: rows.length,
|
|
759
|
+
items: rows.slice(0, limit),
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
export async function memoryLookupTool(ctx, args) {
|
|
764
|
+
const matches = await findMemoryMatches(ctx, args);
|
|
765
|
+
|
|
766
|
+
return {
|
|
767
|
+
tool: "memory.lookup",
|
|
768
|
+
profile: matches.profileId,
|
|
769
|
+
result: {
|
|
770
|
+
query: matches.query,
|
|
771
|
+
total: matches.total,
|
|
772
|
+
items: matches.items,
|
|
773
|
+
memory: {
|
|
774
|
+
file: matches.file,
|
|
775
|
+
updatedAt: matches.bucket?.updatedAt || null,
|
|
776
|
+
liveUpdate: "updated opportunistically after successful CLI read/search/list/info calls",
|
|
777
|
+
},
|
|
778
|
+
},
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function baseUrlFromProfile(profile) {
|
|
783
|
+
const baseUrl = String(profile?.baseUrl || "").trim();
|
|
784
|
+
return baseUrl ? baseUrl.replace(/\/+$/, "") : "";
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function sourceUrlFromDocument(profile, row) {
|
|
788
|
+
if (!row || typeof row !== "object") {
|
|
789
|
+
return undefined;
|
|
790
|
+
}
|
|
791
|
+
const url = String(row.url || "").trim();
|
|
792
|
+
if (/^https?:\/\//i.test(url)) {
|
|
793
|
+
return url;
|
|
794
|
+
}
|
|
795
|
+
const baseUrl = baseUrlFromProfile(profile);
|
|
796
|
+
if (!baseUrl) {
|
|
797
|
+
return undefined;
|
|
798
|
+
}
|
|
799
|
+
if (url) {
|
|
800
|
+
return `${baseUrl}${url.startsWith("/") ? url : `/${url}`}`;
|
|
801
|
+
}
|
|
802
|
+
const urlId = String(row.urlId || "").trim();
|
|
803
|
+
if (urlId) {
|
|
804
|
+
return `${baseUrl}/doc/${urlId}`;
|
|
805
|
+
}
|
|
806
|
+
return undefined;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function normalizeLiveDocument(row, view = "summary", profile = null) {
|
|
810
|
+
if (!row || typeof row !== "object") {
|
|
811
|
+
return row;
|
|
812
|
+
}
|
|
813
|
+
const sourceUrl = sourceUrlFromDocument(profile, row);
|
|
814
|
+
if (view === "full") {
|
|
815
|
+
return compactValue({
|
|
816
|
+
...row,
|
|
817
|
+
sourceUrl,
|
|
818
|
+
}) || row;
|
|
819
|
+
}
|
|
820
|
+
const out = {
|
|
821
|
+
id: row.id,
|
|
822
|
+
title: row.title,
|
|
823
|
+
collectionId: row.collectionId,
|
|
824
|
+
parentDocumentId: row.parentDocumentId,
|
|
825
|
+
revision: row.revision,
|
|
826
|
+
updatedAt: row.updatedAt,
|
|
827
|
+
publishedAt: row.publishedAt,
|
|
828
|
+
urlId: row.urlId,
|
|
829
|
+
url: row.url,
|
|
830
|
+
sourceUrl,
|
|
831
|
+
emoji: row.emoji,
|
|
832
|
+
};
|
|
833
|
+
if (view === "ids") {
|
|
834
|
+
return compactValue({
|
|
835
|
+
id: out.id,
|
|
836
|
+
title: out.title,
|
|
837
|
+
sourceUrl,
|
|
838
|
+
}) || {};
|
|
839
|
+
}
|
|
840
|
+
return compactValue(out) || {};
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
function normalizeLiveCollection(row, view = "summary") {
|
|
844
|
+
if (!row || typeof row !== "object") {
|
|
845
|
+
return row;
|
|
846
|
+
}
|
|
847
|
+
if (view === "full") {
|
|
848
|
+
return row;
|
|
849
|
+
}
|
|
850
|
+
return compactValue({
|
|
851
|
+
id: row.id,
|
|
852
|
+
name: row.name,
|
|
853
|
+
description: view === "ids" ? undefined : row.description,
|
|
854
|
+
permission: view === "ids" ? undefined : row.permission,
|
|
855
|
+
sharing: view === "ids" ? undefined : row.sharing,
|
|
856
|
+
updatedAt: view === "ids" ? undefined : row.updatedAt,
|
|
857
|
+
color: view === "ids" ? undefined : row.color,
|
|
858
|
+
icon: view === "ids" ? undefined : row.icon,
|
|
859
|
+
urlId: row.urlId,
|
|
860
|
+
}) || {};
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
function normalizeLiveUser(row, view = "summary") {
|
|
864
|
+
if (!row || typeof row !== "object") {
|
|
865
|
+
return row;
|
|
866
|
+
}
|
|
867
|
+
if (view === "full") {
|
|
868
|
+
return row;
|
|
869
|
+
}
|
|
870
|
+
return compactValue({
|
|
871
|
+
id: row.id,
|
|
872
|
+
name: row.name,
|
|
873
|
+
email: row.email,
|
|
874
|
+
avatarUrl: view === "ids" ? undefined : row.avatarUrl,
|
|
875
|
+
role: view === "ids" ? undefined : row.role,
|
|
876
|
+
isAdmin: view === "ids" ? undefined : row.isAdmin,
|
|
877
|
+
isSuspended: view === "ids" ? undefined : row.isSuspended,
|
|
878
|
+
lastActiveAt: view === "ids" ? undefined : row.lastActiveAt,
|
|
879
|
+
}) || {};
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function normalizeLiveGroup(row, view = "summary") {
|
|
883
|
+
if (!row || typeof row !== "object") {
|
|
884
|
+
return row;
|
|
885
|
+
}
|
|
886
|
+
if (view === "full") {
|
|
887
|
+
return row;
|
|
888
|
+
}
|
|
889
|
+
return compactValue({
|
|
890
|
+
id: row.id,
|
|
891
|
+
name: row.name,
|
|
892
|
+
memberCount: view === "ids" ? undefined : row.memberCount,
|
|
893
|
+
createdAt: view === "ids" ? undefined : row.createdAt,
|
|
894
|
+
updatedAt: view === "ids" ? undefined : row.updatedAt,
|
|
895
|
+
}) || {};
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function normalizeLiveTemplate(row, view = "summary") {
|
|
899
|
+
if (!row || typeof row !== "object") {
|
|
900
|
+
return row;
|
|
901
|
+
}
|
|
902
|
+
if (view === "full") {
|
|
903
|
+
return row;
|
|
904
|
+
}
|
|
905
|
+
return compactValue({
|
|
906
|
+
id: row.id,
|
|
907
|
+
title: row.title,
|
|
908
|
+
name: row.name,
|
|
909
|
+
collectionId: row.collectionId,
|
|
910
|
+
createdAt: view === "ids" ? undefined : row.createdAt,
|
|
911
|
+
updatedAt: view === "ids" ? undefined : row.updatedAt,
|
|
912
|
+
}) || {};
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function maybeDropPolicies(payload, includePolicies) {
|
|
916
|
+
if (includePolicies) {
|
|
917
|
+
return payload;
|
|
918
|
+
}
|
|
919
|
+
if (!payload || typeof payload !== "object") {
|
|
920
|
+
return payload;
|
|
921
|
+
}
|
|
922
|
+
const next = { ...payload };
|
|
923
|
+
delete next.policies;
|
|
924
|
+
if (next.data && typeof next.data === "object" && !Array.isArray(next.data)) {
|
|
925
|
+
next.data = { ...next.data };
|
|
926
|
+
delete next.data.policies;
|
|
927
|
+
}
|
|
928
|
+
return next;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
async function hydrateMemoryCandidate(ctx, candidate, args) {
|
|
932
|
+
const maxAttempts = toInteger(args.maxAttempts, 2);
|
|
933
|
+
const view = args.view || "summary";
|
|
934
|
+
const endpoint = candidate.type === "collection"
|
|
935
|
+
? "collections.info"
|
|
936
|
+
: candidate.type === "user"
|
|
937
|
+
? "users.info"
|
|
938
|
+
: candidate.type === "group"
|
|
939
|
+
? "groups.info"
|
|
940
|
+
: candidate.type === "template"
|
|
941
|
+
? "templates.info"
|
|
942
|
+
: "documents.info";
|
|
943
|
+
try {
|
|
944
|
+
const res = await ctx.client.call(endpoint, { id: candidate.id }, { maxAttempts });
|
|
945
|
+
const raw = res.body?.data;
|
|
946
|
+
const data = candidate.type === "collection"
|
|
947
|
+
? normalizeLiveCollection(raw, view)
|
|
948
|
+
: candidate.type === "user"
|
|
949
|
+
? normalizeLiveUser(raw, view)
|
|
950
|
+
: candidate.type === "group"
|
|
951
|
+
? normalizeLiveGroup(raw, view)
|
|
952
|
+
: candidate.type === "template"
|
|
953
|
+
? normalizeLiveTemplate(raw, view)
|
|
954
|
+
: normalizeLiveDocument(raw, view, ctx.profile);
|
|
955
|
+
|
|
956
|
+
await recordToolObservation(ctx, endpoint, { id: candidate.id, view }, {
|
|
957
|
+
tool: endpoint,
|
|
958
|
+
profile: ctx.profile?.id,
|
|
959
|
+
result: res.body,
|
|
960
|
+
});
|
|
961
|
+
|
|
962
|
+
return {
|
|
963
|
+
candidate,
|
|
964
|
+
ok: true,
|
|
965
|
+
endpoint,
|
|
966
|
+
result: compactValue({
|
|
967
|
+
...res.body,
|
|
968
|
+
data,
|
|
969
|
+
}) || {},
|
|
970
|
+
};
|
|
971
|
+
} catch (err) {
|
|
972
|
+
if (err instanceof ApiError) {
|
|
973
|
+
const stale = await tombstoneHydrationMiss(ctx, candidate, endpoint, err.details?.status);
|
|
974
|
+
return {
|
|
975
|
+
candidate,
|
|
976
|
+
ok: false,
|
|
977
|
+
endpoint,
|
|
978
|
+
error: err.message,
|
|
979
|
+
status: err.details?.status,
|
|
980
|
+
memory: stale.tombstoned ? stale : undefined,
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
throw err;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
async function openDocumentByDirectInfo(ctx, args) {
|
|
988
|
+
const maxAttempts = toInteger(args.maxAttempts, 2);
|
|
989
|
+
const view = args.view || "summary";
|
|
990
|
+
const body = compactValue({
|
|
991
|
+
id: args.id,
|
|
992
|
+
shareId: args.shareId,
|
|
993
|
+
}) || {};
|
|
994
|
+
const res = await ctx.client.call("documents.info", body, { maxAttempts });
|
|
995
|
+
const payload = maybeDropPolicies(res.body, !!args.includePolicies);
|
|
996
|
+
const data = normalizeLiveDocument(payload?.data, view, ctx.profile);
|
|
997
|
+
const response = compactValue({
|
|
998
|
+
...payload,
|
|
999
|
+
data,
|
|
1000
|
+
}) || {};
|
|
1001
|
+
|
|
1002
|
+
await recordToolObservation(ctx, "documents.info", { ...body, view }, {
|
|
1003
|
+
tool: "documents.info",
|
|
1004
|
+
profile: ctx.profile?.id,
|
|
1005
|
+
result: res.body,
|
|
1006
|
+
});
|
|
1007
|
+
|
|
1008
|
+
return {
|
|
1009
|
+
tool: "documents.open",
|
|
1010
|
+
profile: ctx.profile?.id,
|
|
1011
|
+
result: {
|
|
1012
|
+
ok: true,
|
|
1013
|
+
mode: args.id ? "id" : "shareId",
|
|
1014
|
+
query: args.id || args.shareId,
|
|
1015
|
+
document: data,
|
|
1016
|
+
response,
|
|
1017
|
+
memory: {
|
|
1018
|
+
refreshed: true,
|
|
1019
|
+
strategy: "direct documents.info",
|
|
1020
|
+
},
|
|
1021
|
+
},
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
async function openCollectionByDirectInfo(ctx, args) {
|
|
1026
|
+
const maxAttempts = toInteger(args.maxAttempts, 2);
|
|
1027
|
+
const view = args.view || "summary";
|
|
1028
|
+
const res = await ctx.client.call("collections.info", { id: args.id }, { maxAttempts });
|
|
1029
|
+
const payload = maybeDropPolicies(res.body, !!args.includePolicies);
|
|
1030
|
+
const data = normalizeLiveCollection(payload?.data, view);
|
|
1031
|
+
const response = compactValue({
|
|
1032
|
+
...payload,
|
|
1033
|
+
data,
|
|
1034
|
+
}) || {};
|
|
1035
|
+
|
|
1036
|
+
await recordToolObservation(ctx, "collections.info", { id: args.id, view }, {
|
|
1037
|
+
tool: "collections.info",
|
|
1038
|
+
profile: ctx.profile?.id,
|
|
1039
|
+
result: res.body,
|
|
1040
|
+
});
|
|
1041
|
+
|
|
1042
|
+
return {
|
|
1043
|
+
tool: "collections.open",
|
|
1044
|
+
profile: ctx.profile?.id,
|
|
1045
|
+
result: {
|
|
1046
|
+
ok: true,
|
|
1047
|
+
mode: "id",
|
|
1048
|
+
query: args.id,
|
|
1049
|
+
collection: data,
|
|
1050
|
+
response,
|
|
1051
|
+
memory: {
|
|
1052
|
+
refreshed: true,
|
|
1053
|
+
strategy: "direct collections.info",
|
|
1054
|
+
},
|
|
1055
|
+
},
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
function assertHydrationProfileMatches(ctx, args) {
|
|
1060
|
+
if (args.refresh === false || !args.profile) {
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
if (args.profile === ctx.profile?.id) {
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
throw new CliError(
|
|
1067
|
+
"memory.resolve live refresh requires args.profile to match the selected CLI profile; set refresh=false for cross-profile local lookup"
|
|
1068
|
+
);
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
function shouldFallbackSearch(args, refresh) {
|
|
1072
|
+
return refresh && args.fallbackSearch !== false;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
function shouldFallbackForMatches(args, refresh, matches) {
|
|
1076
|
+
if (!shouldFallbackSearch(args, refresh)) {
|
|
1077
|
+
return false;
|
|
1078
|
+
}
|
|
1079
|
+
if (!matches?.items?.length) {
|
|
1080
|
+
return true;
|
|
1081
|
+
}
|
|
1082
|
+
if (args.fallbackMinScore === undefined) {
|
|
1083
|
+
return false;
|
|
1084
|
+
}
|
|
1085
|
+
const threshold = Math.max(0, toInteger(args.fallbackMinScore, 0));
|
|
1086
|
+
return Number(matches.items[0]?.score || 0) < threshold;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
function normalizeFallbackMode(args) {
|
|
1090
|
+
const mode = String(args.fallbackMode || "titles").trim().toLowerCase();
|
|
1091
|
+
if (["titles", "semantic", "both"].includes(mode)) {
|
|
1092
|
+
return mode;
|
|
1093
|
+
}
|
|
1094
|
+
return "titles";
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
async function runFallbackSearch(ctx, args, query) {
|
|
1098
|
+
if (!shouldFallbackSearch(args, args.refresh !== false)) {
|
|
1099
|
+
return null;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
const maxAttempts = toInteger(args.maxAttempts, 2);
|
|
1103
|
+
const limit = Math.max(1, toInteger(args.fallbackLimit, Math.min(toInteger(args.limit, 10), 10)));
|
|
1104
|
+
const searchQuery = fallbackQueryForReference(query);
|
|
1105
|
+
const common = compactValue({
|
|
1106
|
+
query: searchQuery,
|
|
1107
|
+
limit,
|
|
1108
|
+
offset: 0,
|
|
1109
|
+
collectionId: args.collectionId,
|
|
1110
|
+
}) || {};
|
|
1111
|
+
const calls = [];
|
|
1112
|
+
const errors = [];
|
|
1113
|
+
let observed = 0;
|
|
1114
|
+
|
|
1115
|
+
const callAndObserve = async (endpoint, body) => {
|
|
1116
|
+
try {
|
|
1117
|
+
const res = await ctx.client.call(endpoint, body, { maxAttempts });
|
|
1118
|
+
const count = Array.isArray(res.body?.data) ? res.body.data.length : 0;
|
|
1119
|
+
calls.push({ endpoint, count });
|
|
1120
|
+
await recordToolObservation(ctx, endpoint, body, {
|
|
1121
|
+
tool: endpoint,
|
|
1122
|
+
method: endpoint,
|
|
1123
|
+
profile: ctx.profile?.id,
|
|
1124
|
+
result: res.body,
|
|
1125
|
+
});
|
|
1126
|
+
observed += count;
|
|
1127
|
+
} catch (err) {
|
|
1128
|
+
if (err instanceof ApiError) {
|
|
1129
|
+
errors.push({
|
|
1130
|
+
endpoint,
|
|
1131
|
+
error: err.message,
|
|
1132
|
+
status: err.details?.status,
|
|
1133
|
+
});
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
throw err;
|
|
1137
|
+
}
|
|
1138
|
+
};
|
|
1139
|
+
|
|
1140
|
+
if (args.type === "collection") {
|
|
1141
|
+
await callAndObserve("collections.list", common);
|
|
1142
|
+
} else if (args.type === "user") {
|
|
1143
|
+
await callAndObserve("users.list", common);
|
|
1144
|
+
} else if (args.type === "group") {
|
|
1145
|
+
await callAndObserve("groups.list", common);
|
|
1146
|
+
} else if (args.type === "template") {
|
|
1147
|
+
await callAndObserve("templates.list", common);
|
|
1148
|
+
} else {
|
|
1149
|
+
const mode = normalizeFallbackMode(args);
|
|
1150
|
+
if (mode === "titles" || mode === "both") {
|
|
1151
|
+
await callAndObserve("documents.search_titles", common);
|
|
1152
|
+
}
|
|
1153
|
+
if (mode === "semantic" || mode === "both") {
|
|
1154
|
+
await callAndObserve("documents.search", compactValue({
|
|
1155
|
+
...common,
|
|
1156
|
+
snippetMinWords: toInteger(args.snippetMinWords, 16),
|
|
1157
|
+
snippetMaxWords: toInteger(args.snippetMaxWords, 24),
|
|
1158
|
+
}) || common);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
return compactValue({
|
|
1163
|
+
attempted: true,
|
|
1164
|
+
query,
|
|
1165
|
+
searchQuery,
|
|
1166
|
+
limit,
|
|
1167
|
+
mode: args.type === "collection"
|
|
1168
|
+
? "collections"
|
|
1169
|
+
: args.type === "user"
|
|
1170
|
+
? "users"
|
|
1171
|
+
: args.type === "group"
|
|
1172
|
+
? "groups"
|
|
1173
|
+
: args.type === "template"
|
|
1174
|
+
? "templates"
|
|
1175
|
+
: normalizeFallbackMode(args),
|
|
1176
|
+
calls,
|
|
1177
|
+
observed,
|
|
1178
|
+
errors,
|
|
1179
|
+
}) || { attempted: true, query, calls, observed };
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
export async function memoryResolveTool(ctx, args) {
|
|
1183
|
+
assertHydrationProfileMatches(ctx, args);
|
|
1184
|
+
let matches = await findMemoryMatches(ctx, args);
|
|
1185
|
+
const refresh = args.refresh !== false;
|
|
1186
|
+
let fallback = null;
|
|
1187
|
+
if (shouldFallbackForMatches(args, refresh, matches)) {
|
|
1188
|
+
fallback = await runFallbackSearch(ctx, args, matches.query);
|
|
1189
|
+
if (fallback?.observed > 0) {
|
|
1190
|
+
matches = await findMemoryMatches(ctx, args);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
const hydrateLimit = Math.max(1, toInteger(args.hydrateLimit, Math.min(matches.items.length || 1, 3)));
|
|
1194
|
+
const selected = refresh ? matches.items.slice(0, hydrateLimit) : [];
|
|
1195
|
+
const live = [];
|
|
1196
|
+
|
|
1197
|
+
for (const candidate of selected) {
|
|
1198
|
+
live.push(await hydrateMemoryCandidate(ctx, candidate, args));
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
return {
|
|
1202
|
+
tool: "memory.resolve",
|
|
1203
|
+
profile: matches.profileId,
|
|
1204
|
+
result: {
|
|
1205
|
+
query: matches.query,
|
|
1206
|
+
total: matches.total,
|
|
1207
|
+
candidates: matches.items,
|
|
1208
|
+
live,
|
|
1209
|
+
memory: {
|
|
1210
|
+
file: matches.file,
|
|
1211
|
+
updatedAt: matches.bucket?.updatedAt || null,
|
|
1212
|
+
refreshed: refresh,
|
|
1213
|
+
hydrateLimit: selected.length,
|
|
1214
|
+
fallback,
|
|
1215
|
+
},
|
|
1216
|
+
},
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
function normalizeBatchReferences(args) {
|
|
1221
|
+
const refs = [];
|
|
1222
|
+
if (args.queries) {
|
|
1223
|
+
refs.push(...ensureStringArray(args.queries, "queries"));
|
|
1224
|
+
}
|
|
1225
|
+
if (args.ids) {
|
|
1226
|
+
refs.push(...ensureStringArray(args.ids, "ids"));
|
|
1227
|
+
}
|
|
1228
|
+
if (args.urlIds) {
|
|
1229
|
+
refs.push(...ensureStringArray(args.urlIds, "urlIds"));
|
|
1230
|
+
}
|
|
1231
|
+
if (args.urls) {
|
|
1232
|
+
refs.push(...ensureStringArray(args.urls, "urls"));
|
|
1233
|
+
}
|
|
1234
|
+
return [...new Set(refs.map((item) => String(item || "").trim()).filter(Boolean))];
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
export async function memoryResolveBatchTool(ctx, args) {
|
|
1238
|
+
assertHydrationProfileMatches(ctx, args);
|
|
1239
|
+
const references = normalizeBatchReferences(args);
|
|
1240
|
+
if (references.length === 0) {
|
|
1241
|
+
throw new CliError("memory.resolve_batch requires args.queries[], args.ids[], args.urlIds[], or args.urls[]");
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
const concurrency = Math.max(1, toInteger(args.concurrency, 4));
|
|
1245
|
+
const hydrateConcurrency = Math.max(1, toInteger(args.hydrateConcurrency, 4));
|
|
1246
|
+
const hydrateLimit = Math.max(1, toInteger(args.hydrateLimit, 1));
|
|
1247
|
+
const refresh = args.refresh !== false;
|
|
1248
|
+
|
|
1249
|
+
let resolved = await mapLimit(references, concurrency, async (query, index) => {
|
|
1250
|
+
const matches = await findMemoryMatches(ctx, {
|
|
1251
|
+
...args,
|
|
1252
|
+
query,
|
|
1253
|
+
});
|
|
1254
|
+
const selected = refresh ? matches.items.slice(0, hydrateLimit) : [];
|
|
1255
|
+
return {
|
|
1256
|
+
index,
|
|
1257
|
+
query,
|
|
1258
|
+
profile: matches.profileId,
|
|
1259
|
+
total: matches.total,
|
|
1260
|
+
candidates: matches.items,
|
|
1261
|
+
selected,
|
|
1262
|
+
memory: {
|
|
1263
|
+
file: matches.file,
|
|
1264
|
+
updatedAt: matches.bucket?.updatedAt || null,
|
|
1265
|
+
},
|
|
1266
|
+
};
|
|
1267
|
+
});
|
|
1268
|
+
|
|
1269
|
+
if (shouldFallbackSearch(args, refresh)) {
|
|
1270
|
+
const fallbackByQuery = new Map();
|
|
1271
|
+
for (const item of resolved.filter((row) => shouldFallbackForMatches(args, refresh, { items: row.candidates }))) {
|
|
1272
|
+
const refreshedMatches = await findMemoryMatches(ctx, {
|
|
1273
|
+
...args,
|
|
1274
|
+
query: item.query,
|
|
1275
|
+
});
|
|
1276
|
+
if (!shouldFallbackForMatches(args, refresh, refreshedMatches)) {
|
|
1277
|
+
continue;
|
|
1278
|
+
}
|
|
1279
|
+
const fallback = await runFallbackSearch(ctx, args, item.query);
|
|
1280
|
+
if (fallback) {
|
|
1281
|
+
fallbackByQuery.set(item.query, fallback);
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
if (fallbackByQuery.size > 0) {
|
|
1286
|
+
resolved = await mapLimit(references, concurrency, async (query, index) => {
|
|
1287
|
+
const matches = await findMemoryMatches(ctx, {
|
|
1288
|
+
...args,
|
|
1289
|
+
query,
|
|
1290
|
+
});
|
|
1291
|
+
const selected = refresh ? matches.items.slice(0, hydrateLimit) : [];
|
|
1292
|
+
return {
|
|
1293
|
+
index,
|
|
1294
|
+
query,
|
|
1295
|
+
profile: matches.profileId,
|
|
1296
|
+
total: matches.total,
|
|
1297
|
+
candidates: matches.items,
|
|
1298
|
+
selected,
|
|
1299
|
+
memory: {
|
|
1300
|
+
file: matches.file,
|
|
1301
|
+
updatedAt: matches.bucket?.updatedAt || null,
|
|
1302
|
+
fallback: fallbackByQuery.get(query) || null,
|
|
1303
|
+
},
|
|
1304
|
+
};
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
const hydrationTargets = [];
|
|
1310
|
+
const targetKeys = new Set();
|
|
1311
|
+
for (const item of resolved) {
|
|
1312
|
+
for (const candidate of item.selected) {
|
|
1313
|
+
const key = `${candidate.type}:${candidate.id}`;
|
|
1314
|
+
if (targetKeys.has(key)) {
|
|
1315
|
+
continue;
|
|
1316
|
+
}
|
|
1317
|
+
targetKeys.add(key);
|
|
1318
|
+
hydrationTargets.push(candidate);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
const hydrated = new Map();
|
|
1323
|
+
if (refresh && hydrationTargets.length > 0) {
|
|
1324
|
+
const rows = await mapLimit(hydrationTargets, hydrateConcurrency, async (candidate) =>
|
|
1325
|
+
hydrateMemoryCandidate(ctx, candidate, args)
|
|
1326
|
+
);
|
|
1327
|
+
for (const row of rows) {
|
|
1328
|
+
hydrated.set(`${row.candidate.type}:${row.candidate.id}`, row);
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
const items = resolved.map((item) => ({
|
|
1333
|
+
index: item.index,
|
|
1334
|
+
query: item.query,
|
|
1335
|
+
total: item.total,
|
|
1336
|
+
candidates: item.candidates,
|
|
1337
|
+
live: item.selected
|
|
1338
|
+
.map((candidate) => hydrated.get(`${candidate.type}:${candidate.id}`))
|
|
1339
|
+
.filter(Boolean),
|
|
1340
|
+
memory: item.memory,
|
|
1341
|
+
}));
|
|
1342
|
+
const failedHydrations = [...hydrated.values()].filter((item) => !item.ok).length;
|
|
1343
|
+
|
|
1344
|
+
return {
|
|
1345
|
+
tool: "memory.resolve_batch",
|
|
1346
|
+
profile: args.profile || ctx.profile?.id,
|
|
1347
|
+
result: {
|
|
1348
|
+
queryCount: references.length,
|
|
1349
|
+
totalCandidates: items.reduce((sum, item) => sum + item.total, 0),
|
|
1350
|
+
hydrationRequested: hydrationTargets.length,
|
|
1351
|
+
hydrationFailed: failedHydrations,
|
|
1352
|
+
items,
|
|
1353
|
+
memory: {
|
|
1354
|
+
refreshed: refresh,
|
|
1355
|
+
hydrateLimit,
|
|
1356
|
+
concurrency,
|
|
1357
|
+
hydrateConcurrency,
|
|
1358
|
+
},
|
|
1359
|
+
},
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
export async function documentsOpenTool(ctx, args) {
|
|
1364
|
+
if (args.id || args.shareId) {
|
|
1365
|
+
if (args.profile && args.profile !== ctx.profile?.id) {
|
|
1366
|
+
throw new CliError(
|
|
1367
|
+
"documents.open live read requires args.profile to match the selected CLI profile"
|
|
1368
|
+
);
|
|
1369
|
+
}
|
|
1370
|
+
return openDocumentByDirectInfo(ctx, args);
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
assertHydrationProfileMatches(ctx, args);
|
|
1374
|
+
const strict = args.strict !== false;
|
|
1375
|
+
const strictThreshold = Math.max(0, toInteger(args.strictThreshold, 85));
|
|
1376
|
+
const resolveArgs = {
|
|
1377
|
+
...args,
|
|
1378
|
+
type: "document",
|
|
1379
|
+
minScore: args.minScore === undefined ? (strict ? strictThreshold : 1) : args.minScore,
|
|
1380
|
+
fallbackMinScore: args.fallbackMinScore === undefined && strict ? strictThreshold : args.fallbackMinScore,
|
|
1381
|
+
hydrateLimit: 1,
|
|
1382
|
+
limit: Math.max(1, toInteger(args.limit, 5)),
|
|
1383
|
+
refresh: args.refresh !== false,
|
|
1384
|
+
};
|
|
1385
|
+
const resolved = await memoryResolveTool(ctx, resolveArgs);
|
|
1386
|
+
const candidates = resolved.result?.candidates || [];
|
|
1387
|
+
const topCandidate = candidates[0] || null;
|
|
1388
|
+
const topScore = Number(topCandidate?.score || 0);
|
|
1389
|
+
|
|
1390
|
+
if (!topCandidate) {
|
|
1391
|
+
return {
|
|
1392
|
+
tool: "documents.open",
|
|
1393
|
+
profile: resolved.profile,
|
|
1394
|
+
result: {
|
|
1395
|
+
ok: false,
|
|
1396
|
+
status: "not_found",
|
|
1397
|
+
query: resolved.result?.query || args.query || args.urlId || args.url,
|
|
1398
|
+
document: null,
|
|
1399
|
+
candidates,
|
|
1400
|
+
memory: resolved.result?.memory,
|
|
1401
|
+
},
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
if (strict && topScore < strictThreshold) {
|
|
1406
|
+
return {
|
|
1407
|
+
tool: "documents.open",
|
|
1408
|
+
profile: resolved.profile,
|
|
1409
|
+
result: {
|
|
1410
|
+
ok: false,
|
|
1411
|
+
status: "low_confidence",
|
|
1412
|
+
query: resolved.result?.query,
|
|
1413
|
+
strictThreshold,
|
|
1414
|
+
document: null,
|
|
1415
|
+
candidate: topCandidate,
|
|
1416
|
+
candidates,
|
|
1417
|
+
memory: resolved.result?.memory,
|
|
1418
|
+
},
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
const live = (resolved.result?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
|
|
1423
|
+
|| (resolved.result?.live || [])[0]
|
|
1424
|
+
|| null;
|
|
1425
|
+
if (!live?.ok) {
|
|
1426
|
+
return {
|
|
1427
|
+
tool: "documents.open",
|
|
1428
|
+
profile: resolved.profile,
|
|
1429
|
+
result: {
|
|
1430
|
+
ok: false,
|
|
1431
|
+
status: live ? "hydrate_failed" : "not_hydrated",
|
|
1432
|
+
query: resolved.result?.query,
|
|
1433
|
+
document: null,
|
|
1434
|
+
candidate: topCandidate,
|
|
1435
|
+
candidates,
|
|
1436
|
+
live,
|
|
1437
|
+
memory: resolved.result?.memory,
|
|
1438
|
+
},
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
return {
|
|
1443
|
+
tool: "documents.open",
|
|
1444
|
+
profile: resolved.profile,
|
|
1445
|
+
result: {
|
|
1446
|
+
ok: true,
|
|
1447
|
+
mode: "memory",
|
|
1448
|
+
query: resolved.result?.query,
|
|
1449
|
+
document: live.result?.data || null,
|
|
1450
|
+
response: live.result,
|
|
1451
|
+
candidate: topCandidate,
|
|
1452
|
+
candidates,
|
|
1453
|
+
memory: resolved.result?.memory,
|
|
1454
|
+
},
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
export async function collectionsOpenTool(ctx, args) {
|
|
1459
|
+
if (args.id) {
|
|
1460
|
+
if (args.profile && args.profile !== ctx.profile?.id) {
|
|
1461
|
+
throw new CliError(
|
|
1462
|
+
"collections.open live read requires args.profile to match the selected CLI profile"
|
|
1463
|
+
);
|
|
1464
|
+
}
|
|
1465
|
+
return openCollectionByDirectInfo(ctx, args);
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
assertHydrationProfileMatches(ctx, args);
|
|
1469
|
+
const strict = args.strict !== false;
|
|
1470
|
+
const strictThreshold = Math.max(0, toInteger(args.strictThreshold, 85));
|
|
1471
|
+
const resolveArgs = {
|
|
1472
|
+
...args,
|
|
1473
|
+
type: "collection",
|
|
1474
|
+
minScore: args.minScore === undefined ? (strict ? strictThreshold : 1) : args.minScore,
|
|
1475
|
+
fallbackMinScore: args.fallbackMinScore === undefined && strict ? strictThreshold : args.fallbackMinScore,
|
|
1476
|
+
hydrateLimit: 1,
|
|
1477
|
+
limit: Math.max(1, toInteger(args.limit, 5)),
|
|
1478
|
+
refresh: args.refresh !== false,
|
|
1479
|
+
};
|
|
1480
|
+
const resolved = await memoryResolveTool(ctx, resolveArgs);
|
|
1481
|
+
const candidates = resolved.result?.candidates || [];
|
|
1482
|
+
const topCandidate = candidates[0] || null;
|
|
1483
|
+
const topScore = Number(topCandidate?.score || 0);
|
|
1484
|
+
|
|
1485
|
+
if (!topCandidate) {
|
|
1486
|
+
return {
|
|
1487
|
+
tool: "collections.open",
|
|
1488
|
+
profile: resolved.profile,
|
|
1489
|
+
result: {
|
|
1490
|
+
ok: false,
|
|
1491
|
+
status: "not_found",
|
|
1492
|
+
query: resolved.result?.query || args.query || args.urlId || args.url,
|
|
1493
|
+
collection: null,
|
|
1494
|
+
candidates,
|
|
1495
|
+
memory: resolved.result?.memory,
|
|
1496
|
+
},
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
if (strict && topScore < strictThreshold) {
|
|
1501
|
+
return {
|
|
1502
|
+
tool: "collections.open",
|
|
1503
|
+
profile: resolved.profile,
|
|
1504
|
+
result: {
|
|
1505
|
+
ok: false,
|
|
1506
|
+
status: "low_confidence",
|
|
1507
|
+
query: resolved.result?.query,
|
|
1508
|
+
strictThreshold,
|
|
1509
|
+
collection: null,
|
|
1510
|
+
candidate: topCandidate,
|
|
1511
|
+
candidates,
|
|
1512
|
+
memory: resolved.result?.memory,
|
|
1513
|
+
},
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
const live = (resolved.result?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
|
|
1518
|
+
|| (resolved.result?.live || [])[0]
|
|
1519
|
+
|| null;
|
|
1520
|
+
if (!live?.ok) {
|
|
1521
|
+
return {
|
|
1522
|
+
tool: "collections.open",
|
|
1523
|
+
profile: resolved.profile,
|
|
1524
|
+
result: {
|
|
1525
|
+
ok: false,
|
|
1526
|
+
status: live ? "hydrate_failed" : "not_hydrated",
|
|
1527
|
+
query: resolved.result?.query,
|
|
1528
|
+
collection: null,
|
|
1529
|
+
candidate: topCandidate,
|
|
1530
|
+
candidates,
|
|
1531
|
+
live,
|
|
1532
|
+
memory: resolved.result?.memory,
|
|
1533
|
+
},
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
return {
|
|
1538
|
+
tool: "collections.open",
|
|
1539
|
+
profile: resolved.profile,
|
|
1540
|
+
result: {
|
|
1541
|
+
ok: true,
|
|
1542
|
+
mode: "memory",
|
|
1543
|
+
query: resolved.result?.query,
|
|
1544
|
+
collection: live.result?.data || null,
|
|
1545
|
+
response: live.result,
|
|
1546
|
+
candidate: topCandidate,
|
|
1547
|
+
candidates,
|
|
1548
|
+
memory: resolved.result?.memory,
|
|
1549
|
+
},
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
function normalizeOpenBatchReferences(args) {
|
|
1554
|
+
const refs = [];
|
|
1555
|
+
const pushMany = (kind, values) => {
|
|
1556
|
+
for (const value of ensureStringArray(values, kind === "query" ? "queries" : `${kind}s`) || []) {
|
|
1557
|
+
const text = String(value || "").trim();
|
|
1558
|
+
if (text) {
|
|
1559
|
+
refs.push({ index: refs.length, kind, value: text });
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
};
|
|
1563
|
+
|
|
1564
|
+
if (args.refs) {
|
|
1565
|
+
for (const value of ensureStringArray(args.refs, "refs") || []) {
|
|
1566
|
+
const text = String(value || "").trim();
|
|
1567
|
+
if (!text) {
|
|
1568
|
+
continue;
|
|
1569
|
+
}
|
|
1570
|
+
refs.push({
|
|
1571
|
+
index: refs.length,
|
|
1572
|
+
kind: /^https?:\/\//i.test(text) ? "url" : "query",
|
|
1573
|
+
value: text,
|
|
1574
|
+
});
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
pushMany("query", args.queries);
|
|
1578
|
+
pushMany("id", args.ids);
|
|
1579
|
+
pushMany("shareId", args.shareIds);
|
|
1580
|
+
pushMany("urlId", args.urlIds);
|
|
1581
|
+
pushMany("url", args.urls);
|
|
1582
|
+
|
|
1583
|
+
return refs.map((ref, index) => ({ ...ref, index }));
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
function openBatchItemFromResolved(row, ref, args) {
|
|
1587
|
+
const strict = args.strict !== false;
|
|
1588
|
+
const strictThreshold = Math.max(0, toInteger(args.strictThreshold, 85));
|
|
1589
|
+
const candidates = row?.candidates || [];
|
|
1590
|
+
const topCandidate = candidates[0] || null;
|
|
1591
|
+
const topScore = Number(topCandidate?.score || 0);
|
|
1592
|
+
|
|
1593
|
+
if (!topCandidate) {
|
|
1594
|
+
return {
|
|
1595
|
+
index: ref.index,
|
|
1596
|
+
kind: ref.kind,
|
|
1597
|
+
value: ref.value,
|
|
1598
|
+
ok: false,
|
|
1599
|
+
status: "not_found",
|
|
1600
|
+
document: null,
|
|
1601
|
+
candidates,
|
|
1602
|
+
memory: row?.memory,
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
if (strict && topScore < strictThreshold) {
|
|
1607
|
+
return {
|
|
1608
|
+
index: ref.index,
|
|
1609
|
+
kind: ref.kind,
|
|
1610
|
+
value: ref.value,
|
|
1611
|
+
ok: false,
|
|
1612
|
+
status: "low_confidence",
|
|
1613
|
+
strictThreshold,
|
|
1614
|
+
document: null,
|
|
1615
|
+
candidate: topCandidate,
|
|
1616
|
+
candidates,
|
|
1617
|
+
memory: row?.memory,
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
const live = (row?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
|
|
1622
|
+
|| (row?.live || [])[0]
|
|
1623
|
+
|| null;
|
|
1624
|
+
if (!live?.ok) {
|
|
1625
|
+
return {
|
|
1626
|
+
index: ref.index,
|
|
1627
|
+
kind: ref.kind,
|
|
1628
|
+
value: ref.value,
|
|
1629
|
+
ok: false,
|
|
1630
|
+
status: live ? "hydrate_failed" : "not_hydrated",
|
|
1631
|
+
document: null,
|
|
1632
|
+
candidate: topCandidate,
|
|
1633
|
+
candidates,
|
|
1634
|
+
live,
|
|
1635
|
+
memory: row?.memory,
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
return {
|
|
1640
|
+
index: ref.index,
|
|
1641
|
+
kind: ref.kind,
|
|
1642
|
+
value: ref.value,
|
|
1643
|
+
ok: true,
|
|
1644
|
+
mode: "memory",
|
|
1645
|
+
document: live.result?.data || null,
|
|
1646
|
+
response: live.result,
|
|
1647
|
+
candidate: topCandidate,
|
|
1648
|
+
candidates,
|
|
1649
|
+
memory: row?.memory,
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
function openCollectionBatchItemFromResolved(row, ref, args) {
|
|
1654
|
+
const strict = args.strict !== false;
|
|
1655
|
+
const strictThreshold = Math.max(0, toInteger(args.strictThreshold, 85));
|
|
1656
|
+
const candidates = row?.candidates || [];
|
|
1657
|
+
const topCandidate = candidates[0] || null;
|
|
1658
|
+
const topScore = Number(topCandidate?.score || 0);
|
|
1659
|
+
|
|
1660
|
+
if (!topCandidate) {
|
|
1661
|
+
return {
|
|
1662
|
+
index: ref.index,
|
|
1663
|
+
kind: ref.kind,
|
|
1664
|
+
value: ref.value,
|
|
1665
|
+
ok: false,
|
|
1666
|
+
status: "not_found",
|
|
1667
|
+
collection: null,
|
|
1668
|
+
candidates,
|
|
1669
|
+
memory: row?.memory,
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
if (strict && topScore < strictThreshold) {
|
|
1674
|
+
return {
|
|
1675
|
+
index: ref.index,
|
|
1676
|
+
kind: ref.kind,
|
|
1677
|
+
value: ref.value,
|
|
1678
|
+
ok: false,
|
|
1679
|
+
status: "low_confidence",
|
|
1680
|
+
strictThreshold,
|
|
1681
|
+
collection: null,
|
|
1682
|
+
candidate: topCandidate,
|
|
1683
|
+
candidates,
|
|
1684
|
+
memory: row?.memory,
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
const live = (row?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
|
|
1689
|
+
|| (row?.live || [])[0]
|
|
1690
|
+
|| null;
|
|
1691
|
+
if (!live?.ok) {
|
|
1692
|
+
return {
|
|
1693
|
+
index: ref.index,
|
|
1694
|
+
kind: ref.kind,
|
|
1695
|
+
value: ref.value,
|
|
1696
|
+
ok: false,
|
|
1697
|
+
status: live ? "hydrate_failed" : "not_hydrated",
|
|
1698
|
+
collection: null,
|
|
1699
|
+
candidate: topCandidate,
|
|
1700
|
+
candidates,
|
|
1701
|
+
live,
|
|
1702
|
+
memory: row?.memory,
|
|
1703
|
+
};
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
return {
|
|
1707
|
+
index: ref.index,
|
|
1708
|
+
kind: ref.kind,
|
|
1709
|
+
value: ref.value,
|
|
1710
|
+
ok: true,
|
|
1711
|
+
mode: "memory",
|
|
1712
|
+
collection: live.result?.data || null,
|
|
1713
|
+
response: live.result,
|
|
1714
|
+
candidate: topCandidate,
|
|
1715
|
+
candidates,
|
|
1716
|
+
memory: row?.memory,
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
export async function documentsOpenBatchTool(ctx, args) {
|
|
1721
|
+
const references = normalizeOpenBatchReferences(args);
|
|
1722
|
+
if (references.length === 0) {
|
|
1723
|
+
throw new CliError("documents.open_batch requires args.refs[], args.queries[], args.ids[], args.shareIds[], args.urlIds[], or args.urls[]");
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
const directRefs = references.filter((ref) => ref.kind === "id" || ref.kind === "shareId");
|
|
1727
|
+
const fuzzyRefs = references.filter((ref) => ref.kind !== "id" && ref.kind !== "shareId");
|
|
1728
|
+
|
|
1729
|
+
if (directRefs.length > 0 && args.profile && args.profile !== ctx.profile?.id) {
|
|
1730
|
+
throw new CliError(
|
|
1731
|
+
"documents.open_batch live reads require args.profile to match the selected CLI profile"
|
|
1732
|
+
);
|
|
1733
|
+
}
|
|
1734
|
+
if (fuzzyRefs.length > 0) {
|
|
1735
|
+
assertHydrationProfileMatches(ctx, args);
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
const concurrency = Math.max(1, toInteger(args.concurrency, 4));
|
|
1739
|
+
const itemsByIndex = new Map();
|
|
1740
|
+
|
|
1741
|
+
if (directRefs.length > 0) {
|
|
1742
|
+
const uniqueDirectRefs = [];
|
|
1743
|
+
const seen = new Set();
|
|
1744
|
+
for (const ref of directRefs) {
|
|
1745
|
+
const key = `${ref.kind}:${ref.value}`;
|
|
1746
|
+
if (!seen.has(key)) {
|
|
1747
|
+
seen.add(key);
|
|
1748
|
+
uniqueDirectRefs.push(ref);
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
const opened = await mapLimit(uniqueDirectRefs, concurrency, async (ref) => {
|
|
1752
|
+
try {
|
|
1753
|
+
const result = await openDocumentByDirectInfo(ctx, {
|
|
1754
|
+
...args,
|
|
1755
|
+
id: ref.kind === "id" ? ref.value : undefined,
|
|
1756
|
+
shareId: ref.kind === "shareId" ? ref.value : undefined,
|
|
1757
|
+
});
|
|
1758
|
+
return {
|
|
1759
|
+
key: `${ref.kind}:${ref.value}`,
|
|
1760
|
+
item: {
|
|
1761
|
+
kind: ref.kind,
|
|
1762
|
+
value: ref.value,
|
|
1763
|
+
ok: true,
|
|
1764
|
+
mode: result.result.mode,
|
|
1765
|
+
document: result.result.document,
|
|
1766
|
+
response: result.result.response,
|
|
1767
|
+
memory: result.result.memory,
|
|
1768
|
+
},
|
|
1769
|
+
};
|
|
1770
|
+
} catch (err) {
|
|
1771
|
+
if (err instanceof ApiError) {
|
|
1772
|
+
return {
|
|
1773
|
+
key: `${ref.kind}:${ref.value}`,
|
|
1774
|
+
item: {
|
|
1775
|
+
kind: ref.kind,
|
|
1776
|
+
value: ref.value,
|
|
1777
|
+
ok: false,
|
|
1778
|
+
status: "hydrate_failed",
|
|
1779
|
+
document: null,
|
|
1780
|
+
error: err.message,
|
|
1781
|
+
statusCode: err.details?.status,
|
|
1782
|
+
},
|
|
1783
|
+
};
|
|
1784
|
+
}
|
|
1785
|
+
throw err;
|
|
1786
|
+
}
|
|
1787
|
+
});
|
|
1788
|
+
const directByKey = new Map(opened.map((row) => [row.key, row.item]));
|
|
1789
|
+
for (const ref of directRefs) {
|
|
1790
|
+
itemsByIndex.set(ref.index, {
|
|
1791
|
+
index: ref.index,
|
|
1792
|
+
...directByKey.get(`${ref.kind}:${ref.value}`),
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
let fuzzyMemory = null;
|
|
1798
|
+
if (fuzzyRefs.length > 0) {
|
|
1799
|
+
const resolved = await memoryResolveBatchTool(ctx, {
|
|
1800
|
+
...args,
|
|
1801
|
+
queries: fuzzyRefs.filter((ref) => ref.kind === "query").map((ref) => ref.value),
|
|
1802
|
+
urlIds: fuzzyRefs.filter((ref) => ref.kind === "urlId").map((ref) => ref.value),
|
|
1803
|
+
urls: fuzzyRefs.filter((ref) => ref.kind === "url").map((ref) => ref.value),
|
|
1804
|
+
ids: undefined,
|
|
1805
|
+
type: "document",
|
|
1806
|
+
hydrateLimit: 1,
|
|
1807
|
+
minScore: args.minScore === undefined && args.strict !== false
|
|
1808
|
+
? Math.max(0, toInteger(args.strictThreshold, 85))
|
|
1809
|
+
: args.minScore,
|
|
1810
|
+
fallbackMinScore: args.fallbackMinScore === undefined && args.strict !== false
|
|
1811
|
+
? Math.max(0, toInteger(args.strictThreshold, 85))
|
|
1812
|
+
: args.fallbackMinScore,
|
|
1813
|
+
refresh: args.refresh !== false,
|
|
1814
|
+
});
|
|
1815
|
+
fuzzyMemory = resolved.result?.memory || null;
|
|
1816
|
+
const rowsByValue = new Map((resolved.result?.items || []).map((row) => [row.query, row]));
|
|
1817
|
+
for (const ref of fuzzyRefs) {
|
|
1818
|
+
itemsByIndex.set(ref.index, openBatchItemFromResolved(rowsByValue.get(ref.value), ref, args));
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
const items = references.map((ref) => itemsByIndex.get(ref.index)).filter(Boolean);
|
|
1823
|
+
const ok = items.filter((item) => item.ok).length;
|
|
1824
|
+
|
|
1825
|
+
return {
|
|
1826
|
+
tool: "documents.open_batch",
|
|
1827
|
+
profile: args.profile || ctx.profile?.id,
|
|
1828
|
+
result: {
|
|
1829
|
+
referenceCount: references.length,
|
|
1830
|
+
ok,
|
|
1831
|
+
failed: items.length - ok,
|
|
1832
|
+
items,
|
|
1833
|
+
memory: {
|
|
1834
|
+
refreshed: args.refresh !== false,
|
|
1835
|
+
directCount: directRefs.length,
|
|
1836
|
+
fuzzyCount: fuzzyRefs.length,
|
|
1837
|
+
concurrency,
|
|
1838
|
+
fuzzy: fuzzyMemory,
|
|
1839
|
+
},
|
|
1840
|
+
},
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
export async function collectionsOpenBatchTool(ctx, args) {
|
|
1845
|
+
const references = normalizeOpenBatchReferences(args);
|
|
1846
|
+
if (references.length === 0) {
|
|
1847
|
+
throw new CliError("collections.open_batch requires args.refs[], args.queries[], args.ids[], args.urlIds[], or args.urls[]");
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
const directRefs = references.filter((ref) => ref.kind === "id");
|
|
1851
|
+
const fuzzyRefs = references.filter((ref) => ref.kind !== "id" && ref.kind !== "shareId");
|
|
1852
|
+
if (references.some((ref) => ref.kind === "shareId")) {
|
|
1853
|
+
throw new CliError("collections.open_batch does not support shareIds[]");
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
if (directRefs.length > 0 && args.profile && args.profile !== ctx.profile?.id) {
|
|
1857
|
+
throw new CliError(
|
|
1858
|
+
"collections.open_batch live reads require args.profile to match the selected CLI profile"
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
if (fuzzyRefs.length > 0) {
|
|
1862
|
+
assertHydrationProfileMatches(ctx, args);
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
const concurrency = Math.max(1, toInteger(args.concurrency, 4));
|
|
1866
|
+
const itemsByIndex = new Map();
|
|
1867
|
+
|
|
1868
|
+
if (directRefs.length > 0) {
|
|
1869
|
+
const uniqueDirectRefs = [];
|
|
1870
|
+
const seen = new Set();
|
|
1871
|
+
for (const ref of directRefs) {
|
|
1872
|
+
const key = `${ref.kind}:${ref.value}`;
|
|
1873
|
+
if (!seen.has(key)) {
|
|
1874
|
+
seen.add(key);
|
|
1875
|
+
uniqueDirectRefs.push(ref);
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
const opened = await mapLimit(uniqueDirectRefs, concurrency, async (ref) => {
|
|
1879
|
+
try {
|
|
1880
|
+
const result = await openCollectionByDirectInfo(ctx, {
|
|
1881
|
+
...args,
|
|
1882
|
+
id: ref.value,
|
|
1883
|
+
});
|
|
1884
|
+
return {
|
|
1885
|
+
key: `${ref.kind}:${ref.value}`,
|
|
1886
|
+
item: {
|
|
1887
|
+
kind: ref.kind,
|
|
1888
|
+
value: ref.value,
|
|
1889
|
+
ok: true,
|
|
1890
|
+
mode: result.result.mode,
|
|
1891
|
+
collection: result.result.collection,
|
|
1892
|
+
response: result.result.response,
|
|
1893
|
+
memory: result.result.memory,
|
|
1894
|
+
},
|
|
1895
|
+
};
|
|
1896
|
+
} catch (err) {
|
|
1897
|
+
if (err instanceof ApiError) {
|
|
1898
|
+
return {
|
|
1899
|
+
key: `${ref.kind}:${ref.value}`,
|
|
1900
|
+
item: {
|
|
1901
|
+
kind: ref.kind,
|
|
1902
|
+
value: ref.value,
|
|
1903
|
+
ok: false,
|
|
1904
|
+
status: "hydrate_failed",
|
|
1905
|
+
collection: null,
|
|
1906
|
+
error: err.message,
|
|
1907
|
+
statusCode: err.details?.status,
|
|
1908
|
+
},
|
|
1909
|
+
};
|
|
1910
|
+
}
|
|
1911
|
+
throw err;
|
|
1912
|
+
}
|
|
1913
|
+
});
|
|
1914
|
+
const directByKey = new Map(opened.map((row) => [row.key, row.item]));
|
|
1915
|
+
for (const ref of directRefs) {
|
|
1916
|
+
itemsByIndex.set(ref.index, {
|
|
1917
|
+
index: ref.index,
|
|
1918
|
+
...directByKey.get(`${ref.kind}:${ref.value}`),
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
let fuzzyMemory = null;
|
|
1924
|
+
if (fuzzyRefs.length > 0) {
|
|
1925
|
+
const resolved = await memoryResolveBatchTool(ctx, {
|
|
1926
|
+
...args,
|
|
1927
|
+
queries: fuzzyRefs.filter((ref) => ref.kind === "query").map((ref) => ref.value),
|
|
1928
|
+
urlIds: fuzzyRefs.filter((ref) => ref.kind === "urlId").map((ref) => ref.value),
|
|
1929
|
+
urls: fuzzyRefs.filter((ref) => ref.kind === "url").map((ref) => ref.value),
|
|
1930
|
+
ids: undefined,
|
|
1931
|
+
type: "collection",
|
|
1932
|
+
hydrateLimit: 1,
|
|
1933
|
+
minScore: args.minScore === undefined && args.strict !== false
|
|
1934
|
+
? Math.max(0, toInteger(args.strictThreshold, 85))
|
|
1935
|
+
: args.minScore,
|
|
1936
|
+
fallbackMinScore: args.fallbackMinScore === undefined && args.strict !== false
|
|
1937
|
+
? Math.max(0, toInteger(args.strictThreshold, 85))
|
|
1938
|
+
: args.fallbackMinScore,
|
|
1939
|
+
refresh: args.refresh !== false,
|
|
1940
|
+
});
|
|
1941
|
+
fuzzyMemory = resolved.result?.memory || null;
|
|
1942
|
+
const rowsByValue = new Map((resolved.result?.items || []).map((row) => [row.query, row]));
|
|
1943
|
+
for (const ref of fuzzyRefs) {
|
|
1944
|
+
itemsByIndex.set(ref.index, openCollectionBatchItemFromResolved(rowsByValue.get(ref.value), ref, args));
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
const items = references.map((ref) => itemsByIndex.get(ref.index)).filter(Boolean);
|
|
1949
|
+
const ok = items.filter((item) => item.ok).length;
|
|
1950
|
+
|
|
1951
|
+
return {
|
|
1952
|
+
tool: "collections.open_batch",
|
|
1953
|
+
profile: args.profile || ctx.profile?.id,
|
|
1954
|
+
result: {
|
|
1955
|
+
referenceCount: references.length,
|
|
1956
|
+
ok,
|
|
1957
|
+
failed: items.length - ok,
|
|
1958
|
+
items,
|
|
1959
|
+
memory: {
|
|
1960
|
+
refreshed: args.refresh !== false,
|
|
1961
|
+
directCount: directRefs.length,
|
|
1962
|
+
fuzzyCount: fuzzyRefs.length,
|
|
1963
|
+
concurrency,
|
|
1964
|
+
fuzzy: fuzzyMemory,
|
|
1965
|
+
},
|
|
1966
|
+
},
|
|
1967
|
+
};
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
export async function memoryRecentTool(ctx, args = {}) {
|
|
1971
|
+
const file = ctx.memory?.file || defaultMemoryFile();
|
|
1972
|
+
const store = await loadStore(file);
|
|
1973
|
+
const profileId = args.profile || ctx.profile?.id;
|
|
1974
|
+
const bucket = profileId ? store.profiles?.[profileId] : null;
|
|
1975
|
+
const limit = Math.max(1, toInteger(args.limit, 20));
|
|
1976
|
+
const maxAgeHours = args.maxAgeHours === undefined ? null : Math.max(0, Number(args.maxAgeHours));
|
|
1977
|
+
const cutoff = maxAgeHours === null ? null : Date.now() - maxAgeHours * 3600 * 1000;
|
|
1978
|
+
|
|
1979
|
+
const rows = [];
|
|
1980
|
+
for (const entry of Object.values(bucket?.entries || {})) {
|
|
1981
|
+
if (!entry || (!args.includeDeleted && entry.deletedAt)) {
|
|
1982
|
+
continue;
|
|
1983
|
+
}
|
|
1984
|
+
if (args.type && entry.type !== args.type) {
|
|
1985
|
+
continue;
|
|
1986
|
+
}
|
|
1987
|
+
if (cutoff !== null) {
|
|
1988
|
+
const observedAt = Date.parse(entry.lastObservedAt || "");
|
|
1989
|
+
if (!Number.isFinite(observedAt) || observedAt < cutoff) {
|
|
1990
|
+
continue;
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
rows.push(shapeEntry(entry));
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
rows.sort((a, b) => String(b.lastObservedAt || "").localeCompare(String(a.lastObservedAt || "")));
|
|
1997
|
+
|
|
1998
|
+
return {
|
|
1999
|
+
tool: "memory.recent",
|
|
2000
|
+
profile: profileId,
|
|
2001
|
+
result: {
|
|
2002
|
+
total: rows.length,
|
|
2003
|
+
items: rows.slice(0, limit),
|
|
2004
|
+
memory: {
|
|
2005
|
+
file,
|
|
2006
|
+
updatedAt: bucket?.updatedAt || null,
|
|
2007
|
+
},
|
|
2008
|
+
},
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
export async function memoryRememberTool(ctx, args) {
|
|
2013
|
+
assertPerformAction(args, {
|
|
2014
|
+
tool: "memory.remember",
|
|
2015
|
+
action: "write a local Outline CLI memory mapping",
|
|
2016
|
+
});
|
|
2017
|
+
|
|
2018
|
+
const type = args.type;
|
|
2019
|
+
if (!["document", "collection", "user", "group", "template"].includes(type)) {
|
|
2020
|
+
throw new CliError("memory.remember requires args.type to be 'document', 'collection', 'user', 'group', or 'template'");
|
|
2021
|
+
}
|
|
2022
|
+
if (!args.id) {
|
|
2023
|
+
throw new CliError("memory.remember requires args.id");
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
const file = ctx.memory?.file || defaultMemoryFile();
|
|
2027
|
+
const store = await loadStore(file);
|
|
2028
|
+
const profileId = args.profile || ctx.profile?.id;
|
|
2029
|
+
if (!profileId) {
|
|
2030
|
+
throw new CliError("memory.remember requires a selected profile or args.profile");
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
const now = new Date().toISOString();
|
|
2034
|
+
const aliases = new Set();
|
|
2035
|
+
addAlias(aliases, args.id);
|
|
2036
|
+
addAlias(aliases, args.title);
|
|
2037
|
+
addAlias(aliases, args.name);
|
|
2038
|
+
addAlias(aliases, args.email);
|
|
2039
|
+
addAlias(aliases, args.urlId);
|
|
2040
|
+
addAlias(aliases, args.url);
|
|
2041
|
+
for (const alias of ensureStringArray(args.aliases || [], "aliases")) {
|
|
2042
|
+
addAlias(aliases, alias);
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
const queries = [
|
|
2046
|
+
...ensureStringArray(args.queries || [], "queries"),
|
|
2047
|
+
...(args.query ? [String(args.query)] : []),
|
|
2048
|
+
].map((item) => item.trim()).filter(Boolean);
|
|
2049
|
+
|
|
2050
|
+
const bucket = profileBucket(store, profileId);
|
|
2051
|
+
const key = `${type}:${args.id}`;
|
|
2052
|
+
bucket.entries[key] = mergeEntry(bucket.entries[key], compactValue({
|
|
2053
|
+
type,
|
|
2054
|
+
id: String(args.id),
|
|
2055
|
+
title: ["document", "template"].includes(type) ? args.title : undefined,
|
|
2056
|
+
name: ["collection", "user", "group", "template"].includes(type) ? (args.name || args.title) : undefined,
|
|
2057
|
+
email: type === "user" ? args.email : undefined,
|
|
2058
|
+
urlId: args.urlId,
|
|
2059
|
+
url: args.url,
|
|
2060
|
+
aliases: [...aliases],
|
|
2061
|
+
queries,
|
|
2062
|
+
}) || { type, id: String(args.id), aliases: [...aliases], queries }, {
|
|
2063
|
+
kind: type,
|
|
2064
|
+
tool: "memory.remember",
|
|
2065
|
+
method: "memory.remember",
|
|
2066
|
+
queries,
|
|
2067
|
+
observedAt: now,
|
|
2068
|
+
authoritative: true,
|
|
2069
|
+
});
|
|
2070
|
+
bucket.updatedAt = now;
|
|
2071
|
+
pruneProfile(bucket, toInteger(ctx.memory?.maxEntriesPerProfile, DEFAULT_MAX_ENTRIES_PER_PROFILE));
|
|
2072
|
+
await saveStore(store, file);
|
|
2073
|
+
|
|
2074
|
+
return {
|
|
2075
|
+
tool: "memory.remember",
|
|
2076
|
+
profile: profileId,
|
|
2077
|
+
result: {
|
|
2078
|
+
item: shapeEntry(bucket.entries[key], 100),
|
|
2079
|
+
memory: {
|
|
2080
|
+
file,
|
|
2081
|
+
updatedAt: bucket.updatedAt,
|
|
2082
|
+
},
|
|
2083
|
+
},
|
|
2084
|
+
};
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2087
|
+
export async function memoryStatsTool(ctx) {
|
|
2088
|
+
const file = ctx.memory?.file || defaultMemoryFile();
|
|
2089
|
+
const store = await loadStore(file);
|
|
2090
|
+
const profiles = Object.entries(store.profiles || {}).map(([profileId, bucket]) => {
|
|
2091
|
+
const entries = Object.values(bucket.entries || {});
|
|
2092
|
+
const byType = {};
|
|
2093
|
+
const tombstonedByType = {};
|
|
2094
|
+
for (const entry of entries) {
|
|
2095
|
+
byType[entry.type] = (byType[entry.type] || 0) + 1;
|
|
2096
|
+
if (entry.deletedAt) {
|
|
2097
|
+
tombstonedByType[entry.type] = (tombstonedByType[entry.type] || 0) + 1;
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
return {
|
|
2101
|
+
profile: profileId,
|
|
2102
|
+
total: entries.length,
|
|
2103
|
+
active: entries.filter((entry) => !entry.deletedAt).length,
|
|
2104
|
+
tombstoned: entries.filter((entry) => entry.deletedAt).length,
|
|
2105
|
+
byType,
|
|
2106
|
+
tombstonedByType,
|
|
2107
|
+
updatedAt: bucket.updatedAt || null,
|
|
2108
|
+
};
|
|
2109
|
+
});
|
|
2110
|
+
|
|
2111
|
+
return {
|
|
2112
|
+
tool: "memory.stats",
|
|
2113
|
+
profile: ctx.profile?.id,
|
|
2114
|
+
result: {
|
|
2115
|
+
file,
|
|
2116
|
+
profiles,
|
|
2117
|
+
},
|
|
2118
|
+
};
|
|
2119
|
+
}
|
|
2120
|
+
|
|
2121
|
+
export async function memoryClearTool(ctx, args) {
|
|
2122
|
+
assertPerformAction(args, {
|
|
2123
|
+
tool: "memory.clear",
|
|
2124
|
+
action: "clear local Outline CLI memory",
|
|
2125
|
+
});
|
|
2126
|
+
|
|
2127
|
+
const file = ctx.memory?.file || defaultMemoryFile();
|
|
2128
|
+
const store = await loadStore(file);
|
|
2129
|
+
const profileId = args.profile || ctx.profile?.id;
|
|
2130
|
+
const beforeProfiles = Object.keys(store.profiles || {}).length;
|
|
2131
|
+
let clearedProfiles = [];
|
|
2132
|
+
|
|
2133
|
+
if (args.allProfiles === true) {
|
|
2134
|
+
clearedProfiles = Object.keys(store.profiles || {});
|
|
2135
|
+
store.profiles = {};
|
|
2136
|
+
} else if (profileId && store.profiles?.[profileId]) {
|
|
2137
|
+
clearedProfiles = [profileId];
|
|
2138
|
+
delete store.profiles[profileId];
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
await saveStore(store, file);
|
|
2142
|
+
|
|
2143
|
+
return {
|
|
2144
|
+
tool: "memory.clear",
|
|
2145
|
+
profile: profileId,
|
|
2146
|
+
result: {
|
|
2147
|
+
file,
|
|
2148
|
+
clearedProfiles,
|
|
2149
|
+
beforeProfiles,
|
|
2150
|
+
afterProfiles: Object.keys(store.profiles || {}).length,
|
|
2151
|
+
},
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
export const MEMORY_TOOLS = {
|
|
2156
|
+
"collections.open": {
|
|
2157
|
+
signature:
|
|
2158
|
+
"collections.open(args: { query?: string; id?: string; urlId?: string; url?: string; profile?: string; limit?: number; minScore?: number; maxAgeHours?: number; refresh?: boolean; strict?: boolean; strictThreshold?: number; fallbackSearch?: boolean; fallbackMinScore?: number; fallbackLimit?: number; view?: 'summary'|'full'; includePolicies?: boolean; maxAttempts?: number })",
|
|
2159
|
+
description: "Open one collection by ID or resolve a remembered collection name, URL id, or URL through local memory plus bounded live fallback.",
|
|
2160
|
+
usageExample: {
|
|
2161
|
+
tool: "collections.open",
|
|
2162
|
+
args: {
|
|
2163
|
+
query: "engineering",
|
|
2164
|
+
view: "summary",
|
|
2165
|
+
},
|
|
2166
|
+
},
|
|
2167
|
+
bestPractices: [
|
|
2168
|
+
"Use this for direct one-call collection reads when the user gives a collection name, alias, URL id, URL, or known collection id.",
|
|
2169
|
+
"Keep strict=true for automation so weak fuzzy matches return candidates instead of a guessed collection.",
|
|
2170
|
+
"Use collections.info ids[] when you already have several exact collection IDs.",
|
|
2171
|
+
],
|
|
2172
|
+
handler: collectionsOpenTool,
|
|
2173
|
+
},
|
|
2174
|
+
"collections.open_batch": {
|
|
2175
|
+
signature:
|
|
2176
|
+
"collections.open_batch(args: { refs?: string[]; queries?: string[]; ids?: string[]; urlIds?: string[]; urls?: string[]; profile?: string; limit?: number; minScore?: number; maxAgeHours?: number; refresh?: boolean; strict?: boolean; strictThreshold?: number; fallbackSearch?: boolean; fallbackMinScore?: number; fallbackLimit?: number; view?: 'summary'|'full'; includePolicies?: boolean; concurrency?: number; hydrateConcurrency?: number; maxAttempts?: number })",
|
|
2177
|
+
description: "Open several collections by mixed IDs, remembered names, URL ids, or full URLs while deduplicating live hydration inside one CLI call.",
|
|
2178
|
+
usageExample: {
|
|
2179
|
+
tool: "collections.open_batch",
|
|
2180
|
+
args: {
|
|
2181
|
+
refs: ["engineering", "product"],
|
|
2182
|
+
ids: ["collection-id"],
|
|
2183
|
+
view: "summary",
|
|
2184
|
+
},
|
|
2185
|
+
},
|
|
2186
|
+
bestPractices: [
|
|
2187
|
+
"Use this when a task names multiple collections and you need ordered hydrated rows in one CLI invocation.",
|
|
2188
|
+
"Use refs[] for mixed names and URLs; use ids[] for exact server identifiers.",
|
|
2189
|
+
"Keep strict=true so low-confidence fuzzy references return candidates instead of guessed collections.",
|
|
2190
|
+
],
|
|
2191
|
+
handler: collectionsOpenBatchTool,
|
|
2192
|
+
},
|
|
2193
|
+
"documents.open": {
|
|
2194
|
+
signature:
|
|
2195
|
+
"documents.open(args: { query?: string; id?: string; shareId?: string; urlId?: string; url?: string; profile?: string; limit?: number; minScore?: number; maxAgeHours?: number; refresh?: boolean; strict?: boolean; strictThreshold?: number; fallbackSearch?: boolean; fallbackMinScore?: number; fallbackLimit?: number; fallbackMode?: 'titles'|'semantic'|'both'; collectionId?: string; view?: 'summary'|'full'; includePolicies?: boolean; maxAttempts?: number })",
|
|
2196
|
+
description: "Open one document by ID/share ID or resolve a remembered title, URL, or URL id through local memory plus bounded live fallback.",
|
|
2197
|
+
usageExample: {
|
|
2198
|
+
tool: "documents.open",
|
|
2199
|
+
args: {
|
|
2200
|
+
query: "incident runbook",
|
|
2201
|
+
view: "summary",
|
|
2202
|
+
},
|
|
2203
|
+
},
|
|
2204
|
+
bestPractices: [
|
|
2205
|
+
"Use this for direct one-call reads when the user gives a title, alias, URL, URL id, share id, or known document id.",
|
|
2206
|
+
"Keep strict=true for automation so weak fuzzy matches return candidates instead of a guessed document.",
|
|
2207
|
+
"Set view=full only for the final document body you actually need.",
|
|
2208
|
+
"Use documents.info ids[] when you already have several exact document IDs.",
|
|
2209
|
+
],
|
|
2210
|
+
handler: documentsOpenTool,
|
|
2211
|
+
},
|
|
2212
|
+
"documents.open_batch": {
|
|
2213
|
+
signature:
|
|
2214
|
+
"documents.open_batch(args: { refs?: string[]; queries?: string[]; ids?: string[]; shareIds?: string[]; urlIds?: string[]; urls?: string[]; profile?: string; limit?: number; minScore?: number; maxAgeHours?: number; refresh?: boolean; strict?: boolean; strictThreshold?: number; fallbackSearch?: boolean; fallbackMinScore?: number; fallbackLimit?: number; fallbackMode?: 'titles'|'semantic'|'both'; collectionId?: string; view?: 'summary'|'full'; includePolicies?: boolean; concurrency?: number; hydrateConcurrency?: number; maxAttempts?: number })",
|
|
2215
|
+
description: "Open several documents by mixed IDs, share IDs, remembered titles, URL ids, or full URLs while deduplicating live hydration inside one CLI call.",
|
|
2216
|
+
usageExample: {
|
|
2217
|
+
tool: "documents.open_batch",
|
|
2218
|
+
args: {
|
|
2219
|
+
refs: ["incident runbook", "https://handbook.example.com/doc/oncall-AbCdEf12"],
|
|
2220
|
+
ids: ["doc-id"],
|
|
2221
|
+
view: "summary",
|
|
2222
|
+
},
|
|
2223
|
+
},
|
|
2224
|
+
bestPractices: [
|
|
2225
|
+
"Use this when a task names multiple documents and you need direct hydrated results in one CLI invocation.",
|
|
2226
|
+
"Use refs[] for mixed titles and URLs; use ids[] or shareIds[] for exact server identifiers.",
|
|
2227
|
+
"Keep strict=true so low-confidence fuzzy references return candidates instead of guessed documents.",
|
|
2228
|
+
"Set view=full only when the final answer needs full document bodies.",
|
|
2229
|
+
],
|
|
2230
|
+
handler: documentsOpenBatchTool,
|
|
2231
|
+
},
|
|
2232
|
+
"memory.lookup": {
|
|
2233
|
+
signature:
|
|
2234
|
+
"memory.lookup(args: { query?: string; id?: string; urlId?: string; url?: string; type?: 'document'|'collection'|'user'|'group'|'template'; profile?: string; limit?: number; minScore?: number; maxAgeHours?: number })",
|
|
2235
|
+
description: "Resolve recently observed documents, collections, users, groups, or templates from local profile-scoped memory without a network call, including remembered URL references.",
|
|
2236
|
+
usageExample: {
|
|
2237
|
+
tool: "memory.lookup",
|
|
2238
|
+
args: {
|
|
2239
|
+
query: "incident runbook",
|
|
2240
|
+
type: "document",
|
|
2241
|
+
limit: 5,
|
|
2242
|
+
},
|
|
2243
|
+
},
|
|
2244
|
+
bestPractices: [
|
|
2245
|
+
"Use this as a zero-network first pass for IDs, titles, names, emails, template names, and recently observed results.",
|
|
2246
|
+
"Treat results as hints; re-read with the matching info tool before decisions that require freshness.",
|
|
2247
|
+
"Use maxAgeHours when stale local matches would be worse than another live lookup.",
|
|
2248
|
+
],
|
|
2249
|
+
handler: memoryLookupTool,
|
|
2250
|
+
},
|
|
2251
|
+
"memory.resolve": {
|
|
2252
|
+
signature:
|
|
2253
|
+
"memory.resolve(args: { query?: string; id?: string; urlId?: string; url?: string; type?: 'document'|'collection'|'user'|'group'|'template'; profile?: string; limit?: number; minScore?: number; maxAgeHours?: number; refresh?: boolean; hydrateLimit?: number; fallbackSearch?: boolean; fallbackMinScore?: number; fallbackLimit?: number; fallbackMode?: 'titles'|'semantic'|'both'; collectionId?: string; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
|
|
2254
|
+
description: "Resolve from local memory, fall back to a bounded live search on misses, and optionally live-hydrate top matches in one call.",
|
|
2255
|
+
usageExample: {
|
|
2256
|
+
tool: "memory.resolve",
|
|
2257
|
+
args: {
|
|
2258
|
+
query: "incident runbook",
|
|
2259
|
+
type: "document",
|
|
2260
|
+
refresh: true,
|
|
2261
|
+
hydrateLimit: 1,
|
|
2262
|
+
view: "summary",
|
|
2263
|
+
},
|
|
2264
|
+
},
|
|
2265
|
+
bestPractices: [
|
|
2266
|
+
"Use this when you likely saw a title, name, email, or ID before but need fresh metadata in the same turn.",
|
|
2267
|
+
"Keep hydrateLimit small to avoid turning a memory lookup into broad live hydration.",
|
|
2268
|
+
"Leave fallbackSearch enabled for cold-start direct results; set fallbackSearch=false for memory-only behavior.",
|
|
2269
|
+
"Set fallbackMinScore when weak fuzzy memory matches should still trigger one bounded live search.",
|
|
2270
|
+
"When using args.profile to inspect another profile's local memory, set refresh=false unless that profile is selected.",
|
|
2271
|
+
"Use memory.lookup instead when zero-network behavior is more important than freshness.",
|
|
2272
|
+
],
|
|
2273
|
+
handler: memoryResolveTool,
|
|
2274
|
+
},
|
|
2275
|
+
"memory.resolve_batch": {
|
|
2276
|
+
signature:
|
|
2277
|
+
"memory.resolve_batch(args: { queries?: string[]; ids?: string[]; urlIds?: string[]; urls?: string[]; type?: 'document'|'collection'|'user'|'group'|'template'; profile?: string; limit?: number; minScore?: number; maxAgeHours?: number; refresh?: boolean; hydrateLimit?: number; fallbackSearch?: boolean; fallbackMinScore?: number; fallbackLimit?: number; fallbackMode?: 'titles'|'semantic'|'both'; collectionId?: string; view?: 'ids'|'summary'|'full'; concurrency?: number; hydrateConcurrency?: number; maxAttempts?: number })",
|
|
2278
|
+
description: "Resolve multiple references from local memory, fall back to bounded live search for misses, and deduplicate optional live hydration in one call.",
|
|
2279
|
+
usageExample: {
|
|
2280
|
+
tool: "memory.resolve_batch",
|
|
2281
|
+
args: {
|
|
2282
|
+
queries: ["incident runbook", "oncall escalation"],
|
|
2283
|
+
type: "document",
|
|
2284
|
+
refresh: true,
|
|
2285
|
+
hydrateLimit: 1,
|
|
2286
|
+
view: "summary",
|
|
2287
|
+
},
|
|
2288
|
+
},
|
|
2289
|
+
bestPractices: [
|
|
2290
|
+
"Use this when a task mentions several documents, collections, users, groups, or templates from prior sessions.",
|
|
2291
|
+
"Keep hydrateLimit=1 for low-call workflows; duplicate live targets are hydrated once per batch.",
|
|
2292
|
+
"Leave fallbackSearch enabled to resolve cold misses without a separate search tool call.",
|
|
2293
|
+
"Set fallbackMinScore when low-score remembered candidates should not suppress live search.",
|
|
2294
|
+
"When using args.profile to inspect another profile's local memory, set refresh=false unless that profile is selected.",
|
|
2295
|
+
"Set refresh=false when the caller only needs remembered IDs and titles.",
|
|
2296
|
+
],
|
|
2297
|
+
handler: memoryResolveBatchTool,
|
|
2298
|
+
},
|
|
2299
|
+
"memory.recent": {
|
|
2300
|
+
signature:
|
|
2301
|
+
"memory.recent(args?: { type?: 'document'|'collection'|'user'|'group'|'template'; profile?: string; limit?: number; maxAgeHours?: number; includeDeleted?: boolean })",
|
|
2302
|
+
description: "List recently observed local memory entries for the selected profile without a network call.",
|
|
2303
|
+
usageExample: {
|
|
2304
|
+
tool: "memory.recent",
|
|
2305
|
+
args: {
|
|
2306
|
+
type: "document",
|
|
2307
|
+
limit: 10,
|
|
2308
|
+
},
|
|
2309
|
+
},
|
|
2310
|
+
bestPractices: [
|
|
2311
|
+
"Use this as a zero-network history view before searching again.",
|
|
2312
|
+
"Keep includeDeleted=false unless auditing local tombstones.",
|
|
2313
|
+
"Hydrate selected IDs with memory.resolve or documents.info when freshness matters.",
|
|
2314
|
+
],
|
|
2315
|
+
handler: memoryRecentTool,
|
|
2316
|
+
},
|
|
2317
|
+
"memory.remember": {
|
|
2318
|
+
signature:
|
|
2319
|
+
"memory.remember(args: { type: 'document'|'collection'|'user'|'group'|'template'; id: string; title?: string; name?: string; email?: string; urlId?: string; url?: string; aliases?: string[]; query?: string; queries?: string[]; profile?: string; performAction?: boolean })",
|
|
2320
|
+
description: "Manually store a local profile-scoped memory alias for a known document, collection, user, group, or template.",
|
|
2321
|
+
usageExample: {
|
|
2322
|
+
tool: "memory.remember",
|
|
2323
|
+
args: {
|
|
2324
|
+
type: "document",
|
|
2325
|
+
id: "doc-id",
|
|
2326
|
+
title: "Incident Runbook",
|
|
2327
|
+
aliases: ["runbook"],
|
|
2328
|
+
performAction: true,
|
|
2329
|
+
},
|
|
2330
|
+
},
|
|
2331
|
+
bestPractices: [
|
|
2332
|
+
"Use this for stable human aliases that agents should resolve in later sessions.",
|
|
2333
|
+
"Prefer real document or collection IDs from Outline reads before remembering a mapping.",
|
|
2334
|
+
"This only changes the local memory file and is action-gated with performAction=true.",
|
|
2335
|
+
],
|
|
2336
|
+
handler: memoryRememberTool,
|
|
2337
|
+
},
|
|
2338
|
+
"memory.stats": {
|
|
2339
|
+
signature: "memory.stats(args?: {})",
|
|
2340
|
+
description: "Summarize the local profile-scoped observation index.",
|
|
2341
|
+
usageExample: {
|
|
2342
|
+
tool: "memory.stats",
|
|
2343
|
+
args: {},
|
|
2344
|
+
},
|
|
2345
|
+
bestPractices: [
|
|
2346
|
+
"Use this to verify whether previous calls populated local memory.",
|
|
2347
|
+
"Inspect per-profile counts before relying on memory.lookup across multiple workspaces.",
|
|
2348
|
+
],
|
|
2349
|
+
handler: memoryStatsTool,
|
|
2350
|
+
},
|
|
2351
|
+
"memory.clear": {
|
|
2352
|
+
signature:
|
|
2353
|
+
"memory.clear(args?: { profile?: string; allProfiles?: boolean; performAction?: boolean })",
|
|
2354
|
+
description: "Clear local Outline CLI memory for the selected profile or all profiles.",
|
|
2355
|
+
usageExample: {
|
|
2356
|
+
tool: "memory.clear",
|
|
2357
|
+
args: {
|
|
2358
|
+
performAction: true,
|
|
2359
|
+
},
|
|
2360
|
+
},
|
|
2361
|
+
bestPractices: [
|
|
2362
|
+
"Clear the current profile when local lookup results are stale or from a retired workspace.",
|
|
2363
|
+
"Use allProfiles=true only when intentionally resetting the whole local observation index.",
|
|
2364
|
+
"This tool is action-gated; set performAction=true only after confirming local cache deletion.",
|
|
2365
|
+
],
|
|
2366
|
+
handler: memoryClearTool,
|
|
2367
|
+
},
|
|
2368
|
+
};
|