@khanglvm/outline-cli 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,11 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { createHash } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { ApiError, CliError } from "./errors.js";
5
5
  import { assertPerformAction } from "./action-gate.js";
6
6
  import { defaultTmpDir } from "./config-store.js";
7
7
  import { compactValue, ensureStringArray, mapLimit, sanitizeFileToken, toInteger } from "./utils.js";
8
+ import { collectionsOpenBatchTool, collectionsOpenTool, documentsOpenBatchTool, memoryResolveTool } from "./memory-store.js";
8
9
 
9
10
  const CONTROL_ARG_KEYS = new Set([
10
11
  "performAction",
@@ -16,6 +17,116 @@ const CONTROL_ARG_KEYS = new Set([
16
17
  "compact",
17
18
  ]);
18
19
 
20
+ const ACCESS_RESOLVE_ARG_KEYS = [
21
+ "documentId",
22
+ "collectionId",
23
+ "documentRef",
24
+ "documentRefs",
25
+ "documentQuery",
26
+ "documentQueries",
27
+ "refs",
28
+ "query",
29
+ "queries",
30
+ "shareId",
31
+ "shareIds",
32
+ "urlId",
33
+ "urlIds",
34
+ "url",
35
+ "urls",
36
+ "profile",
37
+ "resolveLimit",
38
+ "minScore",
39
+ "maxAgeHours",
40
+ "refresh",
41
+ "strict",
42
+ "strictThreshold",
43
+ "fallbackSearch",
44
+ "fallbackMinScore",
45
+ "fallbackLimit",
46
+ "fallbackMode",
47
+ "resolveCollectionId",
48
+ "resolveConcurrency",
49
+ "resolveHydrateConcurrency",
50
+ "hydrateConcurrency",
51
+ "snippetMinWords",
52
+ "snippetMaxWords",
53
+ ];
54
+
55
+ const ENTITY_RESOLVE_ARG_KEYS = [
56
+ "ref",
57
+ "refs",
58
+ "query",
59
+ "queries",
60
+ "userRef",
61
+ "userRefs",
62
+ "userQuery",
63
+ "userQueries",
64
+ "groupRef",
65
+ "groupRefs",
66
+ "groupQuery",
67
+ "groupQueries",
68
+ "templateRef",
69
+ "templateRefs",
70
+ "templateQuery",
71
+ "templateQueries",
72
+ "profile",
73
+ "resolveLimit",
74
+ "minScore",
75
+ "maxAgeHours",
76
+ "refresh",
77
+ "strict",
78
+ "strictThreshold",
79
+ "fallbackSearch",
80
+ "fallbackMinScore",
81
+ "fallbackLimit",
82
+ "fallbackMode",
83
+ "resolveConcurrency",
84
+ "resolveHydrateConcurrency",
85
+ "hydrateConcurrency",
86
+ ];
87
+
88
+ const ANSWER_RESOLVE_ARG_KEYS = [
89
+ "id",
90
+ "documentQuery",
91
+ "documentQueries",
92
+ "documentRef",
93
+ "documentRefs",
94
+ "refs",
95
+ "shareId",
96
+ "shareIds",
97
+ "urlId",
98
+ "urlIds",
99
+ "url",
100
+ "urls",
101
+ "collectionQuery",
102
+ "collectionRef",
103
+ "collectionQueries",
104
+ "collectionRefs",
105
+ "userQuery",
106
+ "userRef",
107
+ "userQueries",
108
+ "userRefs",
109
+ "profile",
110
+ "resolveLimit",
111
+ "minScore",
112
+ "maxAgeHours",
113
+ "refresh",
114
+ "strict",
115
+ "strictThreshold",
116
+ "fallbackSearch",
117
+ "fallbackMinScore",
118
+ "fallbackLimit",
119
+ "fallbackMode",
120
+ "resolveCollectionId",
121
+ "resolveConcurrency",
122
+ "resolveHydrateConcurrency",
123
+ "hydrateConcurrency",
124
+ "contextChars",
125
+ "excerptChars",
126
+ "snippetMinWords",
127
+ "snippetMaxWords",
128
+ ];
129
+
19
130
  function maybeDropPolicies(payload, includePolicies) {
20
131
  if (includePolicies) {
21
132
  return payload;
@@ -162,10 +273,74 @@ function extractAttachmentRefsFromText(text, baseUrl = "") {
162
273
  }
163
274
 
164
275
  async function readDocumentForAttachments(ctx, args = {}) {
165
- const id = args.id || args.documentId || extractDocumentUrlId(args.url);
276
+ const urlId = args.urlId || extractDocumentUrlId(args.url);
277
+ const id = args.id || args.documentId || urlId;
166
278
  const shareId = args.shareId;
279
+ const refArgs = compactValue({
280
+ refs: args.refs,
281
+ queries: args.queries || (args.query ? [args.query] : undefined),
282
+ shareIds: shareId ? [shareId] : undefined,
283
+ urlIds: args.urlId ? [args.urlId] : undefined,
284
+ urls: args.url && !urlId ? [args.url] : undefined,
285
+ profile: args.profile,
286
+ limit: args.resolveLimit,
287
+ minScore: args.minScore,
288
+ maxAgeHours: args.maxAgeHours,
289
+ refresh: args.refresh,
290
+ strict: args.strict,
291
+ strictThreshold: args.strictThreshold,
292
+ fallbackSearch: args.fallbackSearch,
293
+ fallbackMinScore: args.fallbackMinScore,
294
+ fallbackLimit: args.fallbackLimit,
295
+ fallbackMode: args.fallbackMode,
296
+ collectionId: args.resolveCollectionId,
297
+ view: "full",
298
+ concurrency: args.resolveConcurrency,
299
+ hydrateConcurrency: args.resolveHydrateConcurrency,
300
+ maxAttempts: args.maxAttempts,
301
+ }) || {};
302
+
303
+ if (!id && !shareId && (refArgs.refs || refArgs.queries || refArgs.urlIds || refArgs.urls)) {
304
+ const opened = await documentsOpenBatchTool(ctx, refArgs);
305
+ const item = (opened.result?.items || []).find((row) => row?.ok && row.document?.id)
306
+ || (opened.result?.items || [])[0]
307
+ || null;
308
+ if (item?.ok && item.document) {
309
+ return {
310
+ document: item.document,
311
+ resolution: {
312
+ mode: item.mode,
313
+ index: item.index,
314
+ kind: item.kind,
315
+ value: item.value,
316
+ id: item.document.id,
317
+ title: item.document.title,
318
+ candidate: item.candidate,
319
+ memory: item.memory || opened.result?.memory || null,
320
+ },
321
+ };
322
+ }
323
+ return {
324
+ document: null,
325
+ resolution: {
326
+ failed: item
327
+ ? {
328
+ index: item.index,
329
+ kind: item.kind,
330
+ value: item.value,
331
+ status: item.status || "not_found",
332
+ candidate: item.candidate,
333
+ candidates: item.candidates,
334
+ error: item.error,
335
+ }
336
+ : { status: "not_found" },
337
+ memory: item?.memory || opened.result?.memory || null,
338
+ },
339
+ };
340
+ }
341
+
167
342
  if (!id && !shareId) {
168
- throw new CliError("document attachment tools require args.id, args.documentId, args.url, or args.shareId");
343
+ throw new CliError("document attachment tools require args.id, args.documentId, args.url, args.shareId, or document refs");
169
344
  }
170
345
 
171
346
  const body = compactValue({ id, shareId }) || {};
@@ -176,7 +351,16 @@ async function readDocumentForAttachments(ctx, args = {}) {
176
351
  if (!doc) {
177
352
  throw new CliError("documents.info response did not include document data");
178
353
  }
179
- return doc;
354
+ return {
355
+ document: doc,
356
+ resolution: {
357
+ mode: "direct",
358
+ id: doc?.id || id || "",
359
+ shareId: shareId || "",
360
+ urlId: urlId || "",
361
+ memory: null,
362
+ },
363
+ };
180
364
  }
181
365
 
182
366
  function summarizeAttachmentDocument(doc) {
@@ -251,6 +435,65 @@ async function downloadAttachmentToFile(ctx, args = {}, id, index = null) {
251
435
  }
252
436
 
253
437
  function defaultUsageArgs(def) {
438
+ const resolveConfig = normalizeResolveAccessConfig(def.resolveAccess);
439
+ const entityConfig = normalizeResolveEntityConfig(def.resolveEntity);
440
+ const principalConfig = normalizeResolveEntityConfig(def.resolvePrincipal);
441
+ if (principalConfig) {
442
+ const principalKey = principalConfig.queryKeys?.[0] || `${principalConfig.type}Query`;
443
+ const principalValue = principalConfig.type === "group" ? "Engineering" : "Alice Example";
444
+ if (resolveConfig?.kind === "document") {
445
+ return {
446
+ [resolveConfig.queryKeys?.includes("query") ? "query" : "documentQuery"]: "incident runbook",
447
+ [principalKey]: principalValue,
448
+ ...(def.mutating ? { performAction: true } : {}),
449
+ };
450
+ }
451
+ if (resolveConfig?.kind === "collection") {
452
+ const collectionQueryKey = resolveConfig.queryKeys?.includes("query") ? "query" : "collectionQuery";
453
+ return {
454
+ [collectionQueryKey]: "engineering",
455
+ [principalKey]: principalValue,
456
+ ...(def.mutating ? { performAction: true } : {}),
457
+ };
458
+ }
459
+ if (entityConfig?.type === "group") {
460
+ return {
461
+ [entityConfig.queryKeys?.[0] || "groupQuery"]: "Engineering",
462
+ [principalKey]: principalValue,
463
+ ...(def.mutating ? { performAction: true } : {}),
464
+ };
465
+ }
466
+ }
467
+ if (entityConfig?.type === "user") {
468
+ return {
469
+ query: "Alice Example",
470
+ };
471
+ }
472
+ if (entityConfig?.type === "group") {
473
+ return {
474
+ query: "Engineering",
475
+ limit: 20,
476
+ };
477
+ }
478
+ if (entityConfig?.type === "template") {
479
+ return {
480
+ [entityConfig.queryKeys?.[0] || "templateQuery"]: "incident postmortem",
481
+ limit: 20,
482
+ };
483
+ }
484
+ if (resolveConfig?.kind === "document") {
485
+ return {
486
+ [resolveConfig.queryKeys?.includes("query") ? "query" : "documentQuery"]: "incident runbook",
487
+ limit: 20,
488
+ };
489
+ }
490
+ if (resolveConfig?.kind === "collection") {
491
+ const collectionQueryKey = resolveConfig.queryKeys?.includes("query") ? "query" : "collectionQuery";
492
+ return {
493
+ [collectionQueryKey]: "engineering",
494
+ limit: 20,
495
+ };
496
+ }
254
497
  if (def.tool === "documents.empty_trash") {
255
498
  return def.mutating ? { performAction: true } : {};
256
499
  }
@@ -270,7 +513,7 @@ function defaultUsageArgs(def) {
270
513
  }
271
514
  if (def.tool === "shares.create") {
272
515
  return {
273
- documentId: "document-id",
516
+ documentQuery: "incident runbook",
274
517
  performAction: true,
275
518
  };
276
519
  }
@@ -356,197 +599,1530 @@ function defaultUsageArgs(def) {
356
599
  };
357
600
  }
358
601
 
359
- function makeRpcHandler(def) {
360
- return async function rpcHandler(ctx, args = {}) {
361
- if (def.mutating) {
362
- assertPerformAction(args, {
363
- tool: def.tool,
364
- action: `invoke mutating method '${def.method}'`,
365
- });
602
+ function nonEmptyString(value) {
603
+ const text = String(value || "").trim();
604
+ return text || "";
605
+ }
606
+
607
+ function hasAccessRefInput(args = {}, kind) {
608
+ if (nonEmptyString(args.query) || nonEmptyString(args.documentQuery) || nonEmptyString(args.urlId) || nonEmptyString(args.url)) {
609
+ return true;
610
+ }
611
+ if (kind === "document" && nonEmptyString(args.shareId)) {
612
+ return true;
613
+ }
614
+ return ["refs", "queries", "documentQueries", "urlIds", "urls", ...(kind === "document" ? ["shareIds"] : [])]
615
+ .some((key) => Array.isArray(args[key]) && args[key].some((item) => nonEmptyString(item)));
616
+ }
617
+
618
+ function normalizeResolveAccessConfig(input) {
619
+ if (!input) {
620
+ return null;
621
+ }
622
+ if (typeof input === "string") {
623
+ const aliasKey = input === "collection" ? "collectionId" : "documentId";
624
+ const queryKeys = input === "document" ? ["query", "documentQuery"] : ["query"];
625
+ const arrayQueryKeys = input === "document" ? ["queries", "documentQueries"] : ["queries"];
626
+ return {
627
+ kind: input,
628
+ outputField: "id",
629
+ resultField: aliasKey,
630
+ exactKeys: ["id", aliasKey],
631
+ required: true,
632
+ queryKeys,
633
+ arrayQueryKeys,
634
+ omitKeys: ACCESS_RESOLVE_ARG_KEYS,
635
+ };
636
+ }
637
+ const kind = input.kind || "document";
638
+ const aliasKey = kind === "collection" ? "collectionId" : "documentId";
639
+ const queryKeys = input.queryKeys || ["query"];
640
+ const arrayQueryKeys = input.arrayQueryKeys || ["queries"];
641
+ const outputField = input.outputField || "id";
642
+ const resultField = input.resultField || aliasKey;
643
+ const omitKeys = new Set([
644
+ ...ACCESS_RESOLVE_ARG_KEYS,
645
+ ...queryKeys,
646
+ ...arrayQueryKeys,
647
+ ...(input.omitKeys || []),
648
+ ]);
649
+ if (input.preserveQuery === true) {
650
+ omitKeys.delete("query");
651
+ omitKeys.delete("queries");
652
+ }
653
+ omitKeys.delete(outputField);
654
+ return {
655
+ kind,
656
+ outputField,
657
+ resultField,
658
+ exactKeys: input.exactKeys || ["id", aliasKey],
659
+ required: input.required !== false,
660
+ queryKeys,
661
+ arrayQueryKeys,
662
+ omitKeys: [...omitKeys],
663
+ };
664
+ }
665
+
666
+ function collectResolveQueries(args, config) {
667
+ const queries = [];
668
+ for (const key of config.queryKeys || []) {
669
+ const value = nonEmptyString(args[key]);
670
+ if (value) {
671
+ queries.push(value);
672
+ }
673
+ }
674
+ for (const key of config.arrayQueryKeys || []) {
675
+ if (!Array.isArray(args[key])) {
676
+ continue;
677
+ }
678
+ for (const value of args[key]) {
679
+ const text = nonEmptyString(value);
680
+ if (text) {
681
+ queries.push(text);
682
+ }
366
683
  }
684
+ }
685
+ return queries;
686
+ }
367
687
 
368
- const maxAttempts = toInteger(args.maxAttempts, def.mutating ? 1 : 2);
369
- const body = buildBody(args);
370
- let res;
371
- try {
372
- res = await ctx.client.call(def.method, body, { maxAttempts });
373
- } catch (err) {
374
- // Some Outline deployments require comments.update payload in data.text form.
375
- if (
376
- def.tool === "comments.update"
377
- && err instanceof ApiError
378
- && err.details?.status === 400
379
- && /data/i.test(String(err.message || ""))
380
- && typeof args?.text === "string"
381
- && args?.text.length > 0
382
- && (args?.data === undefined || args?.data === null)
383
- ) {
384
- const fallbackBody = buildBody({
385
- ...args,
386
- text: undefined,
387
- data: { text: args.text },
388
- });
389
- res = await ctx.client.call(def.method, fallbackBody, { maxAttempts });
390
- } else {
391
- throw err;
688
+ function firstEntityReference(args = {}, config = {}) {
689
+ for (const key of config.queryKeys || ["query", "ref"]) {
690
+ const value = nonEmptyString(args[key]);
691
+ if (value) {
692
+ return {
693
+ key,
694
+ value,
695
+ };
696
+ }
697
+ }
698
+ for (const key of config.arrayQueryKeys || ["refs", "queries"]) {
699
+ if (!Array.isArray(args[key])) {
700
+ continue;
701
+ }
702
+ for (const item of args[key]) {
703
+ const value = nonEmptyString(item);
704
+ if (value) {
705
+ return {
706
+ key,
707
+ value,
708
+ };
392
709
  }
393
710
  }
711
+ }
712
+ return null;
713
+ }
714
+
715
+ function normalizeResolveEntityConfig(input) {
716
+ if (!input) {
717
+ return null;
718
+ }
719
+ const type = typeof input === "string" ? input : input.type;
720
+ if (!type) {
721
+ return null;
722
+ }
723
+ const queryKeys = input.queryKeys || ["query", "ref"];
724
+ const arrayQueryKeys = input.arrayQueryKeys || ["refs", "queries"];
725
+ const outputField = input.outputField || "id";
726
+ const resultField = input.resultField || `${type}Id`;
727
+ return {
728
+ type,
729
+ outputField,
730
+ resultField,
731
+ exactKeys: input.exactKeys || ["id"],
732
+ passthroughKeys: input.passthroughKeys || [],
733
+ queryKeys,
734
+ arrayQueryKeys,
735
+ omitKeys: [...new Set([...ENTITY_RESOLVE_ARG_KEYS, ...queryKeys, ...arrayQueryKeys, ...(input.omitKeys || [])])],
736
+ strictThreshold: input.strictThreshold,
737
+ };
738
+ }
739
+
740
+ function resolutionFromEntityCandidate(resolved, ref, config) {
741
+ const candidates = resolved.result?.candidates || [];
742
+ const topCandidate = candidates[0] || null;
743
+ const strict = ref.strict !== false;
744
+ const strictThreshold = Math.max(0, toInteger(ref.strictThreshold ?? config.strictThreshold, 85));
745
+ const topScore = Number(topCandidate?.score || 0);
394
746
 
747
+ if (!topCandidate) {
395
748
  return {
396
- tool: def.tool,
397
- profile: ctx.profile.id,
398
- result: maybeDropPolicies(res.body, !!args.includePolicies),
749
+ error: {
750
+ failed: {
751
+ kind: ref.key,
752
+ value: ref.value,
753
+ status: "not_found",
754
+ },
755
+ memory: resolved.result?.memory || null,
756
+ },
757
+ };
758
+ }
759
+ if (strict && topScore < strictThreshold) {
760
+ return {
761
+ error: {
762
+ failed: {
763
+ kind: ref.key,
764
+ value: ref.value,
765
+ status: "low_confidence",
766
+ strictThreshold,
767
+ },
768
+ candidate: topCandidate,
769
+ candidates,
770
+ memory: resolved.result?.memory || null,
771
+ },
772
+ };
773
+ }
774
+
775
+ const live = (resolved.result?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
776
+ || (resolved.result?.live || [])[0]
777
+ || null;
778
+ if (live && !live.ok) {
779
+ return {
780
+ error: {
781
+ failed: {
782
+ kind: ref.key,
783
+ value: ref.value,
784
+ status: "hydrate_failed",
785
+ error: live.error,
786
+ statusCode: live.status,
787
+ },
788
+ candidate: topCandidate,
789
+ memory: resolved.result?.memory || live.memory || null,
790
+ },
399
791
  };
792
+ }
793
+
794
+ return {
795
+ id: topCandidate.id,
796
+ resolution: compactValue({
797
+ mode: "memory",
798
+ kind: ref.key,
799
+ value: ref.value,
800
+ id: topCandidate.id,
801
+ name: topCandidate.name,
802
+ email: topCandidate.email,
803
+ candidate: topCandidate,
804
+ live,
805
+ memory: resolved.result?.memory || null,
806
+ }) || { id: topCandidate.id },
400
807
  };
401
808
  }
402
809
 
403
- function makeRpcContract(def) {
810
+ async function resolveEntityId(ctx, args = {}, input) {
811
+ const config = normalizeResolveEntityConfig(input);
812
+ if (!config) {
813
+ return null;
814
+ }
815
+ const exact = (config.exactKeys || [])
816
+ .map((key) => ({ key, value: nonEmptyString(args[key]) }))
817
+ .find((item) => item.value);
818
+ if (exact?.value) {
819
+ if (exact.key !== config.outputField) {
820
+ return {
821
+ id: exact.value,
822
+ resolution: null,
823
+ outputField: config.outputField,
824
+ resultField: config.resultField,
825
+ omitKeys: config.omitKeys,
826
+ };
827
+ }
828
+ return null;
829
+ }
830
+ if ((config.passthroughKeys || []).some((key) => nonEmptyString(args[key]) || (Array.isArray(args[key]) && args[key].length > 0))) {
831
+ return null;
832
+ }
833
+
834
+ const ref = firstEntityReference(args, config);
835
+ if (!ref) {
836
+ return null;
837
+ }
838
+
839
+ const resolved = await memoryResolveTool(ctx, {
840
+ query: ref.value,
841
+ type: config.type,
842
+ profile: args.profile,
843
+ limit: Math.max(1, toInteger(args.resolveLimit, 5)),
844
+ hydrateLimit: 1,
845
+ maxAgeHours: args.maxAgeHours,
846
+ minScore: args.minScore === undefined && args.strict !== false
847
+ ? Math.max(0, toInteger(args.strictThreshold ?? config.strictThreshold, 85))
848
+ : args.minScore,
849
+ strict: args.strict,
850
+ strictThreshold: args.strictThreshold,
851
+ fallbackSearch: args.fallbackSearch,
852
+ fallbackMinScore: args.fallbackMinScore === undefined && args.strict !== false
853
+ ? Math.max(0, toInteger(args.strictThreshold ?? config.strictThreshold, 85))
854
+ : args.fallbackMinScore,
855
+ fallbackLimit: args.fallbackLimit,
856
+ refresh: args.refresh !== false,
857
+ });
404
858
  return {
405
- signature: `${def.tool}(args?: { ...endpointArgs; includePolicies?: boolean; maxAttempts?: number${
406
- def.mutating ? "; performAction?: boolean" : ""
407
- } })`,
408
- description: def.description,
409
- usageExample: {
410
- tool: def.tool,
411
- args: defaultUsageArgs(def),
412
- },
413
- bestPractices: [
414
- "Prefer minimal payloads to keep responses deterministic and token-efficient.",
415
- ...(def.mutating
416
- ? ["This tool is action-gated; set performAction=true only for explicitly confirmed mutations."]
417
- : ["Use includePolicies=true only when policy details are required."]),
418
- ],
419
- handler: makeRpcHandler(def),
859
+ ...resolutionFromEntityCandidate(resolved, { ...ref, strict: args.strict, strictThreshold: args.strictThreshold }, config),
860
+ outputField: config.outputField,
861
+ resultField: config.resultField,
862
+ omitKeys: config.omitKeys,
420
863
  };
421
864
  }
422
865
 
423
- const RPC_WRAPPER_DEFS = [
424
- { tool: "shares.list", method: "shares.list", description: "List shares." },
425
- { tool: "shares.info", method: "shares.info", description: "Get share details." },
426
- { tool: "shares.create", method: "shares.create", description: "Create a share.", mutating: true },
427
- { tool: "shares.update", method: "shares.update", description: "Update a share.", mutating: true },
428
- { tool: "shares.revoke", method: "shares.revoke", description: "Revoke a share.", mutating: true },
429
- { tool: "templates.list", method: "templates.list", description: "List templates." },
430
- { tool: "templates.info", method: "templates.info", description: "Get template details." },
431
- { tool: "templates.create", method: "templates.create", description: "Create a template.", mutating: true },
432
- { tool: "templates.update", method: "templates.update", description: "Update a template.", mutating: true },
433
- { tool: "templates.delete", method: "templates.delete", description: "Delete a template.", mutating: true },
434
- { tool: "templates.restore", method: "templates.restore", description: "Restore a template.", mutating: true },
435
- { tool: "templates.duplicate", method: "templates.duplicate", description: "Duplicate a template.", mutating: true },
436
- { tool: "documents.templatize", method: "documents.templatize", description: "Convert a document into a template.", mutating: true },
437
- { tool: "documents.import", method: "documents.import", description: "Import a document from JSON payload.", mutating: true },
438
- { tool: "comments.list", method: "comments.list", description: "List comments." },
439
- { tool: "comments.info", method: "comments.info", description: "Get comment details." },
440
- { tool: "comments.create", method: "comments.create", description: "Create a comment.", mutating: true },
441
- { tool: "comments.update", method: "comments.update", description: "Update a comment.", mutating: true },
442
- { tool: "comments.delete", method: "comments.delete", description: "Delete a comment.", mutating: true },
443
- { tool: "events.list", method: "events.list", description: "List workspace events." },
444
- { tool: "oauth_clients.list", method: "oauthClients.list", description: "List OAuth clients." },
445
- { tool: "oauth_clients.info", method: "oauthClients.info", description: "Get OAuth client details." },
446
- { tool: "oauth_clients.create", method: "oauthClients.create", description: "Create an OAuth client.", mutating: true },
447
- { tool: "oauth_clients.update", method: "oauthClients.update", description: "Update an OAuth client.", mutating: true },
448
- {
449
- tool: "oauth_clients.rotate_secret",
450
- method: "oauthClients.rotate_secret",
451
- description: "Rotate an OAuth client secret.",
452
- mutating: true,
453
- },
454
- { tool: "oauth_clients.delete", method: "oauthClients.delete", description: "Delete an OAuth client.", mutating: true },
455
- {
456
- tool: "oauth_authentications.list",
457
- method: "oauthAuthentications.list",
458
- description: "List OAuth authentications.",
459
- },
460
- {
461
- tool: "oauth_authentications.delete",
462
- method: "oauthAuthentications.delete",
463
- description: "Delete an OAuth authentication.",
464
- mutating: true,
465
- },
466
- {
467
- tool: "oauthClients.delete",
468
- method: "oauthClients.delete",
469
- description: "Compatibility alias for oauth_clients.delete.",
470
- mutating: true,
471
- },
472
- {
473
- tool: "oauthAuthentications.delete",
474
- method: "oauthAuthentications.delete",
475
- description: "Compatibility alias for oauth_authentications.delete.",
476
- mutating: true,
477
- },
478
- { tool: "data_attributes.list", method: "dataAttributes.list", description: "List data attributes." },
479
- { tool: "data_attributes.info", method: "dataAttributes.info", description: "Get data attribute details." },
480
- { tool: "data_attributes.create", method: "dataAttributes.create", description: "Create a data attribute.", mutating: true },
481
- { tool: "data_attributes.update", method: "dataAttributes.update", description: "Update a data attribute.", mutating: true },
482
- { tool: "data_attributes.delete", method: "dataAttributes.delete", description: "Delete a data attribute.", mutating: true },
483
- { tool: "revisions.info", method: "revisions.info", description: "Get revision details." },
484
- { tool: "documents.archived", method: "documents.archived", description: "List archived documents." },
485
- { tool: "documents.deleted", method: "documents.deleted", description: "List deleted documents." },
486
- { tool: "documents.archive", method: "documents.archive", description: "Archive a document.", mutating: true },
487
- { tool: "documents.restore", method: "documents.restore", description: "Restore a document.", mutating: true },
488
- {
489
- tool: "documents.permanent_delete",
490
- method: "documents.permanent_delete",
491
- description: "Permanently delete a document.",
492
- mutating: true,
493
- },
494
- { tool: "documents.empty_trash", method: "documents.empty_trash", description: "Empty document trash.", mutating: true },
495
- { tool: "webhooks.list", method: "webhooks.list", description: "List webhooks." },
496
- { tool: "webhooks.info", method: "webhooks.info", description: "Get webhook details." },
497
- { tool: "webhooks.create", method: "webhooks.create", description: "Create a webhook.", mutating: true },
498
- { tool: "webhooks.update", method: "webhooks.update", description: "Update a webhook.", mutating: true },
499
- { tool: "webhooks.delete", method: "webhooks.delete", description: "Delete a webhook.", mutating: true },
500
- { tool: "users.list", method: "users.list", description: "List users." },
501
- { tool: "users.info", method: "users.info", description: "Get user details." },
502
- { tool: "users.invite", method: "users.invite", description: "Invite a user.", mutating: true },
503
- {
504
- tool: "users.update_role",
505
- method: "users.update_role",
506
- description: "Update a user's workspace role.",
507
- mutating: true,
508
- },
509
- { tool: "users.activate", method: "users.activate", description: "Activate a user.", mutating: true },
510
- { tool: "users.suspend", method: "users.suspend", description: "Suspend a user.", mutating: true },
511
- { tool: "groups.list", method: "groups.list", description: "List groups." },
512
- { tool: "groups.info", method: "groups.info", description: "Get group details." },
513
- { tool: "groups.memberships", method: "groups.memberships", description: "List group user memberships." },
514
- { tool: "groups.create", method: "groups.create", description: "Create a group.", mutating: true },
515
- { tool: "groups.update", method: "groups.update", description: "Update a group.", mutating: true },
516
- { tool: "groups.delete", method: "groups.delete", description: "Delete a group.", mutating: true },
517
- { tool: "groups.add_user", method: "groups.add_user", description: "Add a user to a group.", mutating: true },
518
- { tool: "groups.remove_user", method: "groups.remove_user", description: "Remove a user from a group.", mutating: true },
519
- { tool: "collections.memberships", method: "collections.memberships", description: "List collection user memberships." },
520
- { tool: "collections.group_memberships", method: "collections.group_memberships", description: "List collection group memberships." },
521
- { tool: "collections.add_user", method: "collections.add_user", description: "Add a user to a collection.", mutating: true },
522
- { tool: "collections.remove_user", method: "collections.remove_user", description: "Remove a user from a collection.", mutating: true },
523
- { tool: "collections.add_group", method: "collections.add_group", description: "Add a group to a collection.", mutating: true },
524
- { tool: "collections.remove_group", method: "collections.remove_group", description: "Remove a group from a collection.", mutating: true },
525
- { tool: "documents.users", method: "documents.users", description: "List users with access to a document." },
526
- { tool: "documents.memberships", method: "documents.memberships", description: "List document user memberships." },
527
- { tool: "documents.group_memberships", method: "documents.group_memberships", description: "List document group memberships." },
528
- { tool: "documents.add_user", method: "documents.add_user", description: "Add a user to a document.", mutating: true },
529
- { tool: "documents.remove_user", method: "documents.remove_user", description: "Remove a user from a document.", mutating: true },
530
- { tool: "documents.add_group", method: "documents.add_group", description: "Add a group to a document.", mutating: true },
531
- { tool: "documents.remove_group", method: "documents.remove_group", description: "Remove a group from a document.", mutating: true },
532
- { tool: "file_operations.list", method: "fileOperations.list", description: "List file operations." },
533
- { tool: "file_operations.info", method: "fileOperations.info", description: "Get file operation details." },
534
- { tool: "file_operations.delete", method: "fileOperations.delete", description: "Delete a file operation.", mutating: true },
535
- ];
536
-
537
- const RPC_TOOLS = Object.fromEntries(
538
- RPC_WRAPPER_DEFS.map((def) => [
539
- def.tool,
540
- makeRpcContract({
541
- ...def,
542
- mutating: !!def.mutating,
543
- }),
544
- ])
545
- );
866
+ function successfulResolutions(resolutions) {
867
+ return resolutions.filter((item) => item?.id);
868
+ }
546
869
 
547
- function parseQuestionItem(raw, index) {
548
- if (typeof raw === "string") {
549
- const question = raw.trim();
870
+ function combinedResolutionPayload(resolutions) {
871
+ const resolved = successfulResolutions(resolutions).filter((item) => item.resolution);
872
+ if (resolved.length === 0) {
873
+ return null;
874
+ }
875
+ if (resolved.length === 1) {
876
+ return resolved[0].resolution;
877
+ }
878
+ const byField = {};
879
+ for (const item of resolved) {
880
+ byField[item.resultField || item.outputField || "id"] = item.resolution;
881
+ }
882
+ return compactValue(byField);
883
+ }
884
+
885
+ function hasConfiguredAccessRefInput(args = {}, config) {
886
+ if (collectResolveQueries(args, config).length > 0) {
887
+ return true;
888
+ }
889
+ if (nonEmptyString(args.urlId) || nonEmptyString(args.url)) {
890
+ return true;
891
+ }
892
+ if (config.kind === "document" && nonEmptyString(args.shareId)) {
893
+ return true;
894
+ }
895
+ return ["refs", "urlIds", "urls", ...(config.kind === "document" ? ["shareIds"] : [])]
896
+ .some((key) => Array.isArray(args[key]) && args[key].some((item) => nonEmptyString(item)));
897
+ }
898
+
899
+ function resolutionFromAccessOpenItem(item, opened, kind) {
900
+ const entity = kind === "collection" ? item?.collection : item?.document;
901
+ if (!item?.ok || !entity?.id) {
902
+ return {
903
+ error: {
904
+ failed: item
905
+ ? {
906
+ index: item.index,
907
+ kind: item.kind,
908
+ value: item.value,
909
+ status: item.status || "not_found",
910
+ error: item.error,
911
+ }
912
+ : {
913
+ status: "not_found",
914
+ },
915
+ memory: opened.result?.memory || item?.memory || null,
916
+ },
917
+ };
918
+ }
919
+
920
+ return {
921
+ id: entity.id,
922
+ resolution: compactValue({
923
+ mode: item.mode,
924
+ index: item.index,
925
+ kind: item.kind,
926
+ value: item.value,
927
+ id: entity.id,
928
+ title: entity.title,
929
+ name: entity.name,
930
+ candidate: item.candidate,
931
+ memory: item.memory || opened.result?.memory || null,
932
+ }) || { id: entity.id },
933
+ };
934
+ }
935
+
936
+ async function resolveAccessId(ctx, args = {}, input) {
937
+ const config = normalizeResolveAccessConfig(input);
938
+ const aliasKey = config.kind === "collection" ? "collectionId" : "documentId";
939
+ const exactId = (config.exactKeys || []).map((key) => nonEmptyString(args[key])).find(Boolean) || "";
940
+ if (exactId) {
941
+ return {
942
+ id: exactId,
943
+ resolution: null,
944
+ outputField: config.outputField,
945
+ resultField: config.resultField,
946
+ omitKeys: config.omitKeys,
947
+ };
948
+ }
949
+ if (!hasConfiguredAccessRefInput(args, config)) {
950
+ return config.required ? {
951
+ error: {
952
+ failed: {
953
+ status: "missing_selector",
954
+ message: `requires ${config.exactKeys.map((key) => `args.${key}`).join(", ")} or a resolvable reference`,
955
+ },
956
+ },
957
+ outputField: config.outputField,
958
+ resultField: config.resultField,
959
+ omitKeys: config.omitKeys,
960
+ } : null;
961
+ }
962
+
963
+ const queries = collectResolveQueries(args, config);
964
+ const openArgs = compactValue({
965
+ refs: args.refs,
966
+ queries: queries.length > 0 ? queries : undefined,
967
+ shareIds: config.kind === "document"
968
+ ? (args.shareIds || (args.shareId ? [args.shareId] : undefined))
969
+ : undefined,
970
+ urlIds: args.urlIds || (args.urlId ? [args.urlId] : undefined),
971
+ urls: args.urls || (args.url ? [args.url] : undefined),
972
+ profile: args.profile,
973
+ limit: args.resolveLimit,
974
+ minScore: args.minScore,
975
+ maxAgeHours: args.maxAgeHours,
976
+ refresh: args.refresh,
977
+ strict: args.strict,
978
+ strictThreshold: args.strictThreshold,
979
+ fallbackSearch: args.fallbackSearch,
980
+ fallbackMinScore: args.fallbackMinScore,
981
+ fallbackLimit: args.fallbackLimit,
982
+ fallbackMode: args.fallbackMode,
983
+ collectionId: config.kind === "document" ? args.resolveCollectionId : undefined,
984
+ snippetMinWords: args.snippetMinWords,
985
+ snippetMaxWords: args.snippetMaxWords,
986
+ view: "summary",
987
+ concurrency: args.resolveConcurrency,
988
+ hydrateConcurrency: args.resolveHydrateConcurrency,
989
+ maxAttempts: args.maxAttempts,
990
+ }) || {};
991
+
992
+ const opened = config.kind === "collection"
993
+ ? await collectionsOpenBatchTool(ctx, openArgs)
994
+ : await documentsOpenBatchTool(ctx, openArgs);
995
+ const item = (opened.result?.items || []).find((row) => row?.ok)
996
+ || (opened.result?.items || [])[0]
997
+ || null;
998
+ return {
999
+ ...resolutionFromAccessOpenItem(item, opened, config.kind),
1000
+ outputField: config.outputField,
1001
+ resultField: config.resultField,
1002
+ omitKeys: config.omitKeys,
1003
+ };
1004
+ }
1005
+
1006
+ // ---------------------------------------------------------------------------
1007
+ // Comment ergonomics: plain/markdown text -> Outline ProseMirror `data` doc,
1008
+ // with first-class @-mention resolution.
1009
+ //
1010
+ // Outline stores comment bodies as a ProseMirror document under `data`, NOT a
1011
+ // plain `text` field (the API returns validation_error if only text is sent on
1012
+ // some deployments, and mentions are impossible without the doc form). Each
1013
+ // mention is a node: { type: "mention", attrs: { type: "user", modelId, label,
1014
+ // id, actorId } } where `id` is a fresh UUID per mention. Outline enforces a
1015
+ // 1000-character limit measured on the comment TEXT (not the JSON), returning
1016
+ // validation_error "Comment must be less than 1000 characters (data)".
1017
+ //
1018
+ // We accept a simple `text` body plus a `mentions` list (names / emails /
1019
+ // userIds) and build the doc ourselves. Mentions are resolved against the
1020
+ // users API by FIRST-NAME token + email (display-name order varies across
1021
+ // systems, e.g. Outline shows "Quan, Tran Le" while Jira shows "Tran Le Quan").
1022
+ // ---------------------------------------------------------------------------
1023
+
1024
+ const COMMENT_TEXT_LIMIT = 1000;
1025
+
1026
+ function commentTextNode(text) {
1027
+ return { type: "text", text };
1028
+ }
1029
+
1030
+ function commentMentionNode({ userId, label }) {
1031
+ return {
1032
+ type: "mention",
1033
+ attrs: {
1034
+ type: "user",
1035
+ modelId: userId,
1036
+ label: label || "user",
1037
+ id: randomUUID(),
1038
+ actorId: null,
1039
+ },
1040
+ };
1041
+ }
1042
+
1043
+ // Split plain/markdown text into paragraphs on blank lines, and keep single
1044
+ // newlines as hard breaks inside a paragraph (mirrors how a human pastes text).
1045
+ function splitCommentParagraphs(text) {
1046
+ const normalized = String(text == null ? "" : text).replace(/\r\n?/g, "\n");
1047
+ const blocks = normalized.split(/\n{2,}/);
1048
+ const paragraphs = [];
1049
+ for (const block of blocks) {
1050
+ if (block.trim().length === 0) {
1051
+ continue;
1052
+ }
1053
+ paragraphs.push(block.split("\n"));
1054
+ }
1055
+ return paragraphs;
1056
+ }
1057
+
1058
+ // Build the ProseMirror `data` doc for a comment from text + resolved mentions.
1059
+ // Resolved mentions (each { userId, label }) are inserted at the very start of
1060
+ // the first paragraph, followed by a space, then the text.
1061
+ function buildCommentData(text, resolvedMentions = []) {
1062
+ const paragraphs = splitCommentParagraphs(text);
1063
+ const mentionNodes = resolvedMentions.map((mention) => commentMentionNode(mention));
1064
+
1065
+ const content = [];
1066
+ if (paragraphs.length === 0 && mentionNodes.length === 0) {
1067
+ content.push({ type: "paragraph" });
1068
+ }
1069
+
1070
+ paragraphs.forEach((lines, paragraphIndex) => {
1071
+ const inline = [];
1072
+ if (paragraphIndex === 0 && mentionNodes.length > 0) {
1073
+ mentionNodes.forEach((node) => {
1074
+ inline.push(node);
1075
+ inline.push(commentTextNode(" "));
1076
+ });
1077
+ }
1078
+ lines.forEach((line, lineIndex) => {
1079
+ if (lineIndex > 0) {
1080
+ inline.push({ type: "br" });
1081
+ }
1082
+ if (line.length > 0) {
1083
+ inline.push(commentTextNode(line));
1084
+ }
1085
+ });
1086
+ content.push(inline.length > 0 ? { type: "paragraph", content: inline } : { type: "paragraph" });
1087
+ });
1088
+
1089
+ // Mentions with no text body at all: emit a single paragraph holding them.
1090
+ if (paragraphs.length === 0 && mentionNodes.length > 0) {
1091
+ const inline = [];
1092
+ mentionNodes.forEach((node, index) => {
1093
+ inline.push(node);
1094
+ if (index < mentionNodes.length - 1) {
1095
+ inline.push(commentTextNode(" "));
1096
+ }
1097
+ });
1098
+ content.push({ type: "paragraph", content: inline });
1099
+ }
1100
+
1101
+ return { type: "doc", content };
1102
+ }
1103
+
1104
+ // Character count of the human-readable comment text (mention labels count as
1105
+ // "@label", matching how Outline measures the 1000-char limit on the data doc).
1106
+ function commentTextLength(text, resolvedMentions = []) {
1107
+ const textLen = String(text == null ? "" : text).length;
1108
+ const mentionLen = resolvedMentions.reduce(
1109
+ (sum, mention) => sum + 1 + String(mention.label || "user").length + 1,
1110
+ 0
1111
+ );
1112
+ return textLen + mentionLen;
1113
+ }
1114
+
1115
+ function firstNameToken(name) {
1116
+ return String(name || "")
1117
+ // "Last, First Middle" -> take the part after the comma first
1118
+ .split(",")
1119
+ .map((part) => part.trim())
1120
+ .filter(Boolean)
1121
+ .reverse()[0]
1122
+ ?.split(/\s+/)
1123
+ .filter(Boolean)[0]
1124
+ ?.toLowerCase() || "";
1125
+ }
1126
+
1127
+ function normalizeMentionToken(value) {
1128
+ return String(value || "").trim().toLowerCase();
1129
+ }
1130
+
1131
+ function looksLikeUuid(value) {
1132
+ return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(
1133
+ String(value || "").trim()
1134
+ );
1135
+ }
1136
+
1137
+ function looksLikeEmail(value) {
1138
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || "").trim());
1139
+ }
1140
+
1141
+ // Pull the user rows out of a users.list response body (shape: { data: [...] }).
1142
+ function usersFromListBody(body) {
1143
+ if (Array.isArray(body)) {
1144
+ return body;
1145
+ }
1146
+ if (Array.isArray(body?.data)) {
1147
+ return body.data;
1148
+ }
1149
+ if (Array.isArray(body?.data?.users)) {
1150
+ return body.data.users;
1151
+ }
1152
+ return [];
1153
+ }
1154
+
1155
+ async function fetchWorkspaceUsers(ctx, { maxAttempts } = {}) {
1156
+ const collected = [];
1157
+ const limit = 100;
1158
+ let offset = 0;
1159
+ // Outline paginates users.list; pull a few pages to cover typical workspaces.
1160
+ for (let page = 0; page < 25; page += 1) {
1161
+ let res;
1162
+ try {
1163
+ res = await ctx.client.call("users.list", { limit, offset }, { maxAttempts: maxAttempts || 2 });
1164
+ } catch (err) {
1165
+ if (collected.length > 0) {
1166
+ break;
1167
+ }
1168
+ throw err;
1169
+ }
1170
+ const rows = usersFromListBody(res.body);
1171
+ collected.push(...rows);
1172
+ const pagination = res.body?.pagination;
1173
+ const total = Number(pagination?.total);
1174
+ if (rows.length < limit) {
1175
+ break;
1176
+ }
1177
+ offset += limit;
1178
+ if (Number.isFinite(total) && offset >= total) {
1179
+ break;
1180
+ }
1181
+ }
1182
+ return collected;
1183
+ }
1184
+
1185
+ // Resolve one mention token (name / email / userId) to { userId, label }.
1186
+ // Matching strategy:
1187
+ // - userId (uuid) -> exact id match
1188
+ // - email -> exact email match
1189
+ // - name -> FIRST-NAME token match (+ optional email disambiguation)
1190
+ // Returns { resolved } on success, or { error, candidates } on failure.
1191
+ function resolveMentionToken(token, users) {
1192
+ const raw = String(token || "").trim();
1193
+ if (!raw) {
1194
+ return { error: { value: token, status: "empty" } };
1195
+ }
1196
+
1197
+ if (looksLikeUuid(raw)) {
1198
+ const match = users.find((user) => normalizeMentionToken(user?.id) === normalizeMentionToken(raw));
1199
+ if (match) {
1200
+ return { resolved: { userId: match.id, label: match.name || match.email || "user" } };
1201
+ }
1202
+ return { error: { value: raw, status: "not_found", reason: "no user with that id" } };
1203
+ }
1204
+
1205
+ if (looksLikeEmail(raw)) {
1206
+ const match = users.find((user) => normalizeMentionToken(user?.email) === normalizeMentionToken(raw));
1207
+ if (match) {
1208
+ return { resolved: { userId: match.id, label: match.name || match.email || "user" } };
1209
+ }
1210
+ return { error: { value: raw, status: "not_found", reason: "no user with that email" } };
1211
+ }
1212
+
1213
+ // Name token: match on first-name token. Support "name <email>" / "name|email".
1214
+ const emailHint = raw.match(/[<|]\s*([^\s@<>|]+@[^\s@<>|]+)\s*>?/)?.[1];
1215
+ const namePart = emailHint ? raw.replace(/[<|]\s*[^\s@<>|]+@[^\s@<>|]+\s*>?/, "").trim() : raw;
1216
+ const wantFirst = firstNameToken(namePart);
1217
+
1218
+ let candidates = users.filter((user) => {
1219
+ const userFirst = firstNameToken(user?.name) || firstNameToken(user?.email);
1220
+ return userFirst && wantFirst && userFirst === wantFirst;
1221
+ });
1222
+
1223
+ if (emailHint) {
1224
+ const byEmail = candidates.filter(
1225
+ (user) => normalizeMentionToken(user?.email) === normalizeMentionToken(emailHint)
1226
+ );
1227
+ if (byEmail.length > 0) {
1228
+ candidates = byEmail;
1229
+ }
1230
+ }
1231
+
1232
+ if (candidates.length === 1) {
1233
+ const match = candidates[0];
1234
+ return { resolved: { userId: match.id, label: match.name || match.email || "user" } };
1235
+ }
1236
+
1237
+ if (candidates.length === 0) {
1238
+ return { error: { value: raw, status: "not_found", reason: "no user matched first name" } };
1239
+ }
1240
+
1241
+ return {
1242
+ error: {
1243
+ value: raw,
1244
+ status: "ambiguous",
1245
+ reason: "multiple users share that first name; pass an email or userId",
1246
+ candidates: candidates.map((user) => ({ id: user.id, name: user.name, email: user.email })),
1247
+ },
1248
+ };
1249
+ }
1250
+
1251
+ async function resolveMentions(ctx, mentions, { maxAttempts } = {}) {
1252
+ const tokens = ensureStringArray(mentions).map((item) => String(item).trim()).filter(Boolean);
1253
+ if (tokens.length === 0) {
1254
+ return { resolved: [], failures: [] };
1255
+ }
1256
+ const users = await fetchWorkspaceUsers(ctx, { maxAttempts });
1257
+ const resolved = [];
1258
+ const failures = [];
1259
+ for (const token of tokens) {
1260
+ const outcome = resolveMentionToken(token, users);
1261
+ if (outcome.resolved) {
1262
+ resolved.push(outcome.resolved);
1263
+ } else {
1264
+ failures.push(outcome.error);
1265
+ }
1266
+ }
1267
+ return { resolved, failures };
1268
+ }
1269
+
1270
+ // prepareBody hook for comments.create / comments.post. Runs AFTER document
1271
+ // resolution (so bodyArgs.documentId is set) and BEFORE the API call. Builds
1272
+ // the ProseMirror `data` doc from `text` + `mentions`, enforces the 1000-char
1273
+ // limit, and strips the convenience-only keys from the outgoing body.
1274
+ async function prepareCommentBody(ctx, def, args, bodyArgs) {
1275
+ const text = typeof bodyArgs.text === "string" ? bodyArgs.text : "";
1276
+ const hasMentions = Array.isArray(args.mentions) && args.mentions.length > 0;
1277
+ const hasExplicitData = bodyArgs.data !== undefined && bodyArgs.data !== null;
1278
+
1279
+ // Caller passed a pre-built ProseMirror doc and no mentions: passthrough,
1280
+ // just drop the convenience-only `mentions` key if present.
1281
+ if (hasExplicitData && !hasMentions && !text) {
1282
+ delete bodyArgs.mentions;
1283
+ return bodyArgs;
1284
+ }
1285
+
1286
+ let resolvedMentions = [];
1287
+ if (hasMentions) {
1288
+ const maxAttempts = toInteger(args.maxAttempts, 2);
1289
+ const { resolved, failures } = await resolveMentions(ctx, args.mentions, { maxAttempts });
1290
+ if (failures.length > 0) {
1291
+ throw new CliError(
1292
+ `comments.${def.tool.endsWith(".post") ? "post" : "create"}: could not resolve ${failures.length} mention(s): ` +
1293
+ failures.map((f) => `"${f.value}" (${f.status})`).join(", "),
1294
+ {
1295
+ code: "MENTION_UNRESOLVED",
1296
+ tool: def.tool,
1297
+ failures,
1298
+ }
1299
+ );
1300
+ }
1301
+ resolvedMentions = resolved;
1302
+ }
1303
+
1304
+ // Enforce the 1000-char limit on the human text (not the JSON), pre-flight.
1305
+ const length = commentTextLength(text, resolvedMentions);
1306
+ if (length > COMMENT_TEXT_LIMIT) {
1307
+ throw new CliError(
1308
+ `comments.${def.tool.endsWith(".post") ? "post" : "create"}: comment text is ${length} characters; Outline allows at most ${COMMENT_TEXT_LIMIT}.`,
1309
+ {
1310
+ code: "COMMENT_TOO_LONG",
1311
+ tool: def.tool,
1312
+ length,
1313
+ limit: COMMENT_TEXT_LIMIT,
1314
+ }
1315
+ );
1316
+ }
1317
+
1318
+ // If the caller gave an explicit data doc AND mentions, prepend mention nodes
1319
+ // to its first paragraph; otherwise build from text.
1320
+ if (hasExplicitData && resolvedMentions.length > 0) {
1321
+ const doc = bodyArgs.data;
1322
+ const mentionNodes = resolvedMentions.flatMap((mention) => [
1323
+ commentMentionNode(mention),
1324
+ commentTextNode(" "),
1325
+ ]);
1326
+ const firstParagraph = Array.isArray(doc?.content)
1327
+ ? doc.content.find((node) => node?.type === "paragraph")
1328
+ : null;
1329
+ if (firstParagraph) {
1330
+ firstParagraph.content = [...mentionNodes, ...(firstParagraph.content || [])];
1331
+ } else if (doc && Array.isArray(doc.content)) {
1332
+ doc.content.unshift({ type: "paragraph", content: mentionNodes });
1333
+ }
1334
+ bodyArgs.data = doc;
1335
+ } else if (!hasExplicitData) {
1336
+ bodyArgs.data = buildCommentData(text, resolvedMentions);
1337
+ }
1338
+
1339
+ // Outline wants `data`, not `text` — drop the convenience keys.
1340
+ delete bodyArgs.text;
1341
+ delete bodyArgs.mentions;
1342
+ return bodyArgs;
1343
+ }
1344
+
1345
+ function makeRpcHandler(def) {
1346
+ return async function rpcHandler(ctx, args = {}) {
1347
+ if (def.mutating) {
1348
+ assertPerformAction(args, {
1349
+ tool: def.tool,
1350
+ action: `invoke mutating method '${def.method}'`,
1351
+ });
1352
+ }
1353
+
1354
+ const maxAttempts = toInteger(args.maxAttempts, def.mutating ? 1 : 2);
1355
+ const resolutions = [];
1356
+ if (def.resolveAccess) {
1357
+ resolutions.push(await resolveAccessId(ctx, args, def.resolveAccess));
1358
+ }
1359
+ if (def.resolveEntity) {
1360
+ resolutions.push(await resolveEntityId(ctx, args, def.resolveEntity));
1361
+ }
1362
+ if (def.resolvePrincipal) {
1363
+ resolutions.push(await resolveEntityId(ctx, args, def.resolvePrincipal));
1364
+ }
1365
+ const failedResolution = resolutions.find((item) => item?.error);
1366
+ if (failedResolution?.error) {
1367
+ const resultField = failedResolution.resultField || failedResolution.outputField || (def.resolveAccess === "collection" ? "collectionId" : "documentId");
1368
+ return {
1369
+ tool: def.tool,
1370
+ profile: ctx.profile.id,
1371
+ result: compactValue({
1372
+ ok: false,
1373
+ status: failedResolution.error.status || "not_found",
1374
+ [resultField]: "",
1375
+ resolution: failedResolution.error,
1376
+ data: [],
1377
+ }) || {},
1378
+ };
1379
+ }
1380
+
1381
+ const bodyArgs = { ...args };
1382
+ const omitKeys = [];
1383
+ const resolvedOutputFields = new Set();
1384
+ for (const item of successfulResolutions(resolutions)) {
1385
+ const outputField = item.outputField || "id";
1386
+ bodyArgs[outputField] = item.id;
1387
+ resolvedOutputFields.add(outputField);
1388
+ omitKeys.push(...(item.omitKeys || []));
1389
+ }
1390
+ const effectiveOmitKeys = omitKeys.filter((key) => !resolvedOutputFields.has(key));
1391
+ if (typeof def.prepareBody === "function") {
1392
+ // Hook runs after target resolution (documentId is set) and before the
1393
+ // API call, letting a def transform the outgoing body (e.g. comments
1394
+ // build a ProseMirror data doc + resolve @-mentions).
1395
+ await def.prepareBody(ctx, def, args, bodyArgs);
1396
+ }
1397
+ const body = buildBody(
1398
+ bodyArgs,
1399
+ effectiveOmitKeys.length > 0
1400
+ ? effectiveOmitKeys
1401
+ : def.resolveAccess
1402
+ ? normalizeResolveAccessConfig(def.resolveAccess).omitKeys
1403
+ : []
1404
+ );
1405
+ let res;
1406
+ try {
1407
+ res = await ctx.client.call(def.method, body, { maxAttempts });
1408
+ } catch (err) {
1409
+ // Some Outline deployments require comments.update payload in data.text form.
1410
+ if (
1411
+ def.tool === "comments.update"
1412
+ && err instanceof ApiError
1413
+ && err.details?.status === 400
1414
+ && /data/i.test(String(err.message || ""))
1415
+ && typeof args?.text === "string"
1416
+ && args?.text.length > 0
1417
+ && (args?.data === undefined || args?.data === null)
1418
+ ) {
1419
+ const fallbackBody = buildBody({
1420
+ ...args,
1421
+ text: undefined,
1422
+ data: { text: args.text },
1423
+ });
1424
+ res = await ctx.client.call(def.method, fallbackBody, { maxAttempts });
1425
+ } else {
1426
+ throw err;
1427
+ }
1428
+ }
1429
+
1430
+ const resolutionPayload = combinedResolutionPayload(resolutions);
1431
+ const resolvedIds = {};
1432
+ for (const item of successfulResolutions(resolutions)) {
1433
+ resolvedIds[item.resultField || item.outputField || "id"] = item.id;
1434
+ }
1435
+
1436
+ return {
1437
+ tool: def.tool,
1438
+ profile: ctx.profile.id,
1439
+ result: resolutionPayload
1440
+ ? compactValue({
1441
+ ...maybeDropPolicies(res.body, !!args.includePolicies),
1442
+ ...resolvedIds,
1443
+ resolution: resolutionPayload,
1444
+ }) || {}
1445
+ : maybeDropPolicies(res.body, !!args.includePolicies),
1446
+ };
1447
+ };
1448
+ }
1449
+
1450
+ function makeRpcContract(def) {
1451
+ const resolveConfig = normalizeResolveAccessConfig(def.resolveAccess);
1452
+ const entityConfig = normalizeResolveEntityConfig(def.resolveEntity);
1453
+ const principalConfig = normalizeResolveEntityConfig(def.resolvePrincipal);
1454
+ const isAccessResolver = !!resolveConfig;
1455
+ const isEntityResolver = !!entityConfig;
1456
+ const hasPrincipalResolver = !!principalConfig;
1457
+ const targetIdArg = resolveConfig?.kind === "collection" ? "collectionId" : "documentId";
1458
+ const exactIdArg = resolveConfig?.exactKeys?.includes("id") ? "id?: string; " : "";
1459
+ const exactTargetText = resolveConfig?.exactKeys?.includes("id") ? `${targetIdArg}/id` : targetIdArg;
1460
+ const resolverQueryArg = resolveConfig?.queryKeys?.includes("query")
1461
+ ? "query"
1462
+ : resolveConfig?.kind === "collection"
1463
+ ? "collectionQuery"
1464
+ : "documentQuery";
1465
+ const entityQueryArg = entityConfig?.queryKeys?.[0] || "query";
1466
+ const entityExactArg = entityConfig?.exactKeys?.includes("id") ? "id?: string; " : "";
1467
+ const signature = def.signature || (hasPrincipalResolver
1468
+ ? `${def.tool}(args: { ${exactIdArg}${targetIdArg}?: string; ${resolverQueryArg}?: string; userId?: string; groupId?: string; userQuery?: string; groupQuery?: string; userRefs?: string[]; groupRefs?: string[]; includePolicies?: boolean; maxAttempts?: number${def.mutating ? "; performAction?: boolean" : ""} })`
1469
+ : isAccessResolver
1470
+ ? `${def.tool}(args: { ${exactIdArg}${targetIdArg}?: string; ${resolverQueryArg}?: string; refs?: string[]; urlId?: string; url?: string; limit?: number; offset?: number; includePolicies?: boolean; maxAttempts?: number })`
1471
+ : isEntityResolver
1472
+ ? `${def.tool}(args: { ${entityExactArg}${entityQueryArg}?: string; refs?: string[]; limit?: number; offset?: number; includePolicies?: boolean; maxAttempts?: number${def.mutating ? "; performAction?: boolean" : ""} })`
1473
+ : `${def.tool}(args?: { ...endpointArgs; includePolicies?: boolean; maxAttempts?: number${
1474
+ def.mutating ? "; performAction?: boolean" : ""
1475
+ } })`);
1476
+ const bestPractices = def.bestPractices || [
1477
+ hasPrincipalResolver
1478
+ ? `Pass exact IDs when known, or combine target refs with ${principalConfig.type}Query/${principalConfig.type}Refs to resolve remembered ${principalConfig.type}s first.`
1479
+ : isAccessResolver
1480
+ ? `Pass ${exactTargetText} for exact calls, or ${resolverQueryArg}/refs/url/urlId to resolve remembered targets first.`
1481
+ : isEntityResolver
1482
+ ? `Pass ${entityConfig.exactKeys?.includes("id") ? "id" : "exact IDs"} for exact calls, or ${entityQueryArg}/refs to resolve remembered ${entityConfig.type}s first.`
1483
+ : "Prefer minimal payloads to keep responses deterministic and token-efficient.",
1484
+ ...(def.mutating
1485
+ ? ["This tool is action-gated; set performAction=true only for explicitly confirmed mutations."]
1486
+ : ["Use includePolicies=true only when policy details are required."]),
1487
+ ];
1488
+ return {
1489
+ signature,
1490
+ description: def.description,
1491
+ usageExample: def.usageExample || {
1492
+ tool: def.tool,
1493
+ args: defaultUsageArgs(def),
1494
+ },
1495
+ bestPractices,
1496
+ handler: makeRpcHandler(def),
1497
+ };
1498
+ }
1499
+
1500
+ const RPC_WRAPPER_DEFS = [
1501
+ {
1502
+ tool: "shares.list",
1503
+ method: "shares.list",
1504
+ description: "List shares, optionally resolving a remembered document first.",
1505
+ resolveAccess: {
1506
+ kind: "document",
1507
+ outputField: "documentId",
1508
+ exactKeys: ["documentId"],
1509
+ required: false,
1510
+ queryKeys: ["documentQuery"],
1511
+ arrayQueryKeys: ["documentQueries"],
1512
+ preserveQuery: true,
1513
+ },
1514
+ },
1515
+ {
1516
+ tool: "shares.info",
1517
+ method: "shares.info",
1518
+ description: "Get share details by share ID, document ID, or remembered document reference.",
1519
+ resolveAccess: {
1520
+ kind: "document",
1521
+ outputField: "documentId",
1522
+ exactKeys: ["documentId"],
1523
+ required: false,
1524
+ queryKeys: ["query", "documentQuery"],
1525
+ arrayQueryKeys: ["queries", "documentQueries"],
1526
+ },
1527
+ },
1528
+ {
1529
+ tool: "shares.create",
1530
+ method: "shares.create",
1531
+ description: "Create a share for a document ID or remembered document reference.",
1532
+ signature:
1533
+ "shares.create(args: { documentId?: string; query?: string; documentQuery?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; includeChildDocuments?: boolean; published?: boolean; includePolicies?: boolean; view?: 'summary'|'full'; maxAttempts?: number; performAction?: boolean })",
1534
+ usageExample: {
1535
+ tool: "shares.create",
1536
+ args: {
1537
+ documentQuery: "public handbook",
1538
+ published: true,
1539
+ performAction: true,
1540
+ },
1541
+ },
1542
+ bestPractices: [
1543
+ "Pass documentQuery/refs/url/urlId when the user names a document but the exact ID is unknown.",
1544
+ "Use documentId for deterministic automation when already known.",
1545
+ "Confirm the target document before creating public share links in high-risk workspaces.",
1546
+ "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
1547
+ ],
1548
+ mutating: true,
1549
+ resolveAccess: {
1550
+ kind: "document",
1551
+ outputField: "documentId",
1552
+ exactKeys: ["documentId"],
1553
+ required: true,
1554
+ queryKeys: ["query", "documentQuery", "documentRef", "shareId", "urlId", "url"],
1555
+ arrayQueryKeys: ["queries", "documentQueries", "documentRefs", "refs", "shareIds", "urlIds", "urls"],
1556
+ },
1557
+ },
1558
+ { tool: "shares.update", method: "shares.update", description: "Update a share.", mutating: true },
1559
+ { tool: "shares.revoke", method: "shares.revoke", description: "Revoke a share.", mutating: true },
1560
+ {
1561
+ tool: "templates.list",
1562
+ method: "templates.list",
1563
+ description: "List templates, optionally resolving a remembered collection filter first.",
1564
+ resolveAccess: {
1565
+ kind: "collection",
1566
+ outputField: "collectionId",
1567
+ exactKeys: ["collectionId"],
1568
+ required: false,
1569
+ queryKeys: ["collectionQuery", "collectionRef"],
1570
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1571
+ },
1572
+ },
1573
+ {
1574
+ tool: "templates.info",
1575
+ method: "templates.info",
1576
+ description: "Get template details by ID or remembered template name.",
1577
+ resolveEntity: {
1578
+ type: "template",
1579
+ outputField: "id",
1580
+ resultField: "templateId",
1581
+ exactKeys: ["id"],
1582
+ queryKeys: ["templateQuery", "templateRef", "query"],
1583
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs", "queries"],
1584
+ },
1585
+ },
1586
+ { tool: "templates.create", method: "templates.create", description: "Create a template.", mutating: true },
1587
+ {
1588
+ tool: "templates.update",
1589
+ method: "templates.update",
1590
+ description: "Update a template by ID or remembered template name.",
1591
+ mutating: true,
1592
+ resolveEntity: {
1593
+ type: "template",
1594
+ outputField: "id",
1595
+ resultField: "templateId",
1596
+ exactKeys: ["id"],
1597
+ queryKeys: ["templateQuery", "templateRef"],
1598
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1599
+ },
1600
+ },
1601
+ {
1602
+ tool: "templates.delete",
1603
+ method: "templates.delete",
1604
+ description: "Delete a template by ID or remembered template name.",
1605
+ mutating: true,
1606
+ resolveEntity: {
1607
+ type: "template",
1608
+ outputField: "id",
1609
+ resultField: "templateId",
1610
+ exactKeys: ["id"],
1611
+ queryKeys: ["templateQuery", "templateRef"],
1612
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1613
+ },
1614
+ },
1615
+ {
1616
+ tool: "templates.restore",
1617
+ method: "templates.restore",
1618
+ description: "Restore a template by ID or remembered template name.",
1619
+ mutating: true,
1620
+ resolveEntity: {
1621
+ type: "template",
1622
+ outputField: "id",
1623
+ resultField: "templateId",
1624
+ exactKeys: ["id"],
1625
+ queryKeys: ["templateQuery", "templateRef"],
1626
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1627
+ },
1628
+ },
1629
+ {
1630
+ tool: "templates.duplicate",
1631
+ method: "templates.duplicate",
1632
+ description: "Duplicate a template by ID or remembered template name.",
1633
+ mutating: true,
1634
+ resolveEntity: {
1635
+ type: "template",
1636
+ outputField: "id",
1637
+ resultField: "templateId",
1638
+ exactKeys: ["id"],
1639
+ queryKeys: ["templateQuery", "templateRef"],
1640
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1641
+ },
1642
+ },
1643
+ { tool: "documents.templatize", method: "documents.templatize", description: "Convert a document into a template.", mutating: true },
1644
+ { tool: "documents.import", method: "documents.import", description: "Import a document from JSON payload.", mutating: true },
1645
+ {
1646
+ tool: "comments.list",
1647
+ method: "comments.list",
1648
+ description:
1649
+ "List comments on a document (and their replies). Resolve the target with documentId/query/refs/url/urlId. Use includeReplies=true to nest replies, or parentCommentId to fetch the replies of one thread.",
1650
+ signature:
1651
+ "comments.list(args?: { documentId?: string; query?: string; documentQuery?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; parentCommentId?: string; includeReplies?: boolean; includeAnchorText?: boolean; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; includePolicies?: boolean; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
1652
+ usageExample: {
1653
+ tool: "comments.list",
1654
+ args: {
1655
+ query: "incident runbook",
1656
+ includeReplies: true,
1657
+ limit: 50,
1658
+ },
1659
+ },
1660
+ bestPractices: [
1661
+ "Pass documentId for exact calls, or query/refs/url/urlId to resolve a remembered document first.",
1662
+ "Set includeReplies=true to fetch replies nested under each top-level comment.",
1663
+ "Pass parentCommentId to read the replies of a specific comment (e.g. after posting one).",
1664
+ "Use view='ids' or 'summary' to keep responses token-efficient.",
1665
+ ],
1666
+ resolveAccess: {
1667
+ kind: "document",
1668
+ outputField: "documentId",
1669
+ exactKeys: ["documentId"],
1670
+ required: false,
1671
+ queryKeys: ["query", "documentQuery"],
1672
+ arrayQueryKeys: ["queries", "documentQueries"],
1673
+ },
1674
+ },
1675
+ { tool: "comments.info", method: "comments.info", description: "Get comment details." },
1676
+ {
1677
+ tool: "comments.create",
1678
+ method: "comments.create",
1679
+ description:
1680
+ "Post a comment on a document. Pass plain/markdown `text` and the ProseMirror `data` doc is built for you; pass `mentions` (names/emails/userIds) to auto-insert @-mentions. Use `parentCommentId` to reply.",
1681
+ signature:
1682
+ "comments.create(args: { documentId?: string; query?: string; documentQuery?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; text?: string; mentions?: string[]; data?: object; parentCommentId?: string; includePolicies?: boolean; view?: 'summary'|'full'; maxAttempts?: number; performAction?: boolean })",
1683
+ usageExample: {
1684
+ tool: "comments.create",
1685
+ args: {
1686
+ query: "incident runbook",
1687
+ text: "Please review the rollback steps.",
1688
+ mentions: ["Tran Le Quan", "alice@example.com"],
1689
+ performAction: true,
1690
+ },
1691
+ },
1692
+ bestPractices: [
1693
+ "Pass plain/markdown `text`; the ProseMirror `data` doc is built for you (blank lines split paragraphs, single newlines become line breaks).",
1694
+ "Pass `mentions` as a list of names, emails, or userIds; names match on FIRST NAME (e.g. \"Tran Le Quan\" matches Outline's \"Quan, Tran Le\"). Ambiguous names are rejected with candidates — disambiguate with an email or userId.",
1695
+ "Comment text is capped at 1000 characters (pre-flight check on text, not JSON).",
1696
+ "Pass query/refs/url/urlId to comment on a remembered document without a separate lookup.",
1697
+ "Use parentCommentId to reply to an existing comment.",
1698
+ "Advanced: pass a raw ProseMirror `data` doc to bypass text building (mentions are still prepended if provided).",
1699
+ "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
1700
+ ],
1701
+ mutating: true,
1702
+ prepareBody: prepareCommentBody,
1703
+ resolveAccess: {
1704
+ kind: "document",
1705
+ outputField: "documentId",
1706
+ exactKeys: ["documentId"],
1707
+ required: true,
1708
+ queryKeys: ["query", "documentQuery", "documentRef", "shareId", "urlId", "url"],
1709
+ arrayQueryKeys: ["queries", "documentQueries", "documentRefs", "refs", "shareIds", "urlIds", "urls"],
1710
+ },
1711
+ },
1712
+ {
1713
+ tool: "comments.post",
1714
+ method: "comments.create",
1715
+ description:
1716
+ "Convenience alias of comments.create: post a comment from plain `text` + ergonomic `mentions`. The ProseMirror data doc and @-mention nodes are built for you.",
1717
+ signature:
1718
+ "comments.post(args: { documentId?: string; query?: string; documentQuery?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; text?: string; mentions?: string[]; data?: object; parentCommentId?: string; includePolicies?: boolean; view?: 'summary'|'full'; maxAttempts?: number; performAction?: boolean })",
1719
+ usageExample: {
1720
+ tool: "comments.post",
1721
+ args: {
1722
+ query: "incident runbook",
1723
+ text: "Can you confirm the timeline?",
1724
+ mentions: ["Quan"],
1725
+ performAction: true,
1726
+ },
1727
+ },
1728
+ bestPractices: [
1729
+ "Same as comments.create: simple `text` + `mentions` (names/emails/userIds), 1000-char limit, parentCommentId for replies.",
1730
+ "Names resolve on FIRST NAME + email; ambiguous names error with candidates.",
1731
+ "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
1732
+ ],
1733
+ mutating: true,
1734
+ prepareBody: prepareCommentBody,
1735
+ resolveAccess: {
1736
+ kind: "document",
1737
+ outputField: "documentId",
1738
+ exactKeys: ["documentId"],
1739
+ required: true,
1740
+ queryKeys: ["query", "documentQuery", "documentRef", "shareId", "urlId", "url"],
1741
+ arrayQueryKeys: ["queries", "documentQueries", "documentRefs", "refs", "shareIds", "urlIds", "urls"],
1742
+ },
1743
+ },
1744
+ { tool: "comments.update", method: "comments.update", description: "Update a comment.", mutating: true },
1745
+ { tool: "comments.delete", method: "comments.delete", description: "Delete a comment.", mutating: true },
1746
+ {
1747
+ tool: "events.list",
1748
+ method: "events.list",
1749
+ description: "List workspace events, optionally resolving remembered document, collection, and actor filters first.",
1750
+ signature:
1751
+ "events.list(args?: { documentId?: string; documentQuery?: string; refs?: string[]; collectionId?: string; collectionQuery?: string; actorId?: string; userQuery?: string; name?: string; auditLog?: boolean; limit?: number; offset?: number; includePolicies?: boolean; maxAttempts?: number })",
1752
+ usageExample: {
1753
+ tool: "events.list",
1754
+ args: {
1755
+ documentQuery: "incident runbook",
1756
+ userQuery: "Alice Example",
1757
+ auditLog: true,
1758
+ limit: 20,
1759
+ },
1760
+ },
1761
+ bestPractices: [
1762
+ "Pass exact IDs when known, or use documentQuery/refs/url/urlId, collectionQuery/collectionRefs, and userQuery/userRefs to resolve remembered audit filters first.",
1763
+ "Use auditLog=true when you need audit-grade event context for a scoped document or actor.",
1764
+ "Keep limit small and paginate with offset for low-token history review.",
1765
+ ],
1766
+ resolveAccess: {
1767
+ kind: "document",
1768
+ outputField: "documentId",
1769
+ exactKeys: ["documentId"],
1770
+ required: false,
1771
+ queryKeys: ["documentQuery", "documentRef"],
1772
+ arrayQueryKeys: ["documentQueries", "documentRefs", "refs"],
1773
+ },
1774
+ resolveEntity: {
1775
+ type: "collection",
1776
+ outputField: "collectionId",
1777
+ resultField: "collectionId",
1778
+ exactKeys: ["collectionId"],
1779
+ queryKeys: ["collectionQuery", "collectionRef"],
1780
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1781
+ },
1782
+ resolvePrincipal: {
1783
+ type: "user",
1784
+ outputField: "actorId",
1785
+ resultField: "actorId",
1786
+ exactKeys: ["actorId"],
1787
+ queryKeys: ["userQuery", "userRef"],
1788
+ arrayQueryKeys: ["userQueries", "userRefs"],
1789
+ },
1790
+ },
1791
+ { tool: "oauth_clients.list", method: "oauthClients.list", description: "List OAuth clients." },
1792
+ { tool: "oauth_clients.info", method: "oauthClients.info", description: "Get OAuth client details." },
1793
+ { tool: "oauth_clients.create", method: "oauthClients.create", description: "Create an OAuth client.", mutating: true },
1794
+ { tool: "oauth_clients.update", method: "oauthClients.update", description: "Update an OAuth client.", mutating: true },
1795
+ {
1796
+ tool: "oauth_clients.rotate_secret",
1797
+ method: "oauthClients.rotate_secret",
1798
+ description: "Rotate an OAuth client secret.",
1799
+ mutating: true,
1800
+ },
1801
+ { tool: "oauth_clients.delete", method: "oauthClients.delete", description: "Delete an OAuth client.", mutating: true },
1802
+ {
1803
+ tool: "oauth_authentications.list",
1804
+ method: "oauthAuthentications.list",
1805
+ description: "List OAuth authentications.",
1806
+ },
1807
+ {
1808
+ tool: "oauth_authentications.delete",
1809
+ method: "oauthAuthentications.delete",
1810
+ description: "Delete an OAuth authentication.",
1811
+ mutating: true,
1812
+ },
1813
+ {
1814
+ tool: "oauthClients.delete",
1815
+ method: "oauthClients.delete",
1816
+ description: "Compatibility alias for oauth_clients.delete.",
1817
+ mutating: true,
1818
+ },
1819
+ {
1820
+ tool: "oauthAuthentications.delete",
1821
+ method: "oauthAuthentications.delete",
1822
+ description: "Compatibility alias for oauth_authentications.delete.",
1823
+ mutating: true,
1824
+ },
1825
+ { tool: "data_attributes.list", method: "dataAttributes.list", description: "List data attributes." },
1826
+ { tool: "data_attributes.info", method: "dataAttributes.info", description: "Get data attribute details." },
1827
+ { tool: "data_attributes.create", method: "dataAttributes.create", description: "Create a data attribute.", mutating: true },
1828
+ { tool: "data_attributes.update", method: "dataAttributes.update", description: "Update a data attribute.", mutating: true },
1829
+ { tool: "data_attributes.delete", method: "dataAttributes.delete", description: "Delete a data attribute.", mutating: true },
1830
+ { tool: "revisions.info", method: "revisions.info", description: "Get revision details." },
1831
+ {
1832
+ tool: "documents.archived",
1833
+ method: "documents.archived",
1834
+ description: "List archived documents, optionally resolving a remembered collection filter first.",
1835
+ resolveAccess: {
1836
+ kind: "collection",
1837
+ outputField: "collectionId",
1838
+ exactKeys: ["collectionId"],
1839
+ required: false,
1840
+ queryKeys: ["collectionQuery", "collectionRef"],
1841
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1842
+ },
1843
+ },
1844
+ {
1845
+ tool: "documents.deleted",
1846
+ method: "documents.deleted",
1847
+ description: "List deleted documents, optionally resolving a remembered collection filter first.",
1848
+ resolveAccess: {
1849
+ kind: "collection",
1850
+ outputField: "collectionId",
1851
+ exactKeys: ["collectionId"],
1852
+ required: false,
1853
+ queryKeys: ["collectionQuery", "collectionRef"],
1854
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1855
+ },
1856
+ },
1857
+ { tool: "documents.archive", method: "documents.archive", description: "Archive a document.", mutating: true },
1858
+ { tool: "documents.restore", method: "documents.restore", description: "Restore a document.", mutating: true },
1859
+ {
1860
+ tool: "documents.permanent_delete",
1861
+ method: "documents.permanent_delete",
1862
+ description: "Permanently delete a document.",
1863
+ mutating: true,
1864
+ },
1865
+ { tool: "documents.empty_trash", method: "documents.empty_trash", description: "Empty document trash.", mutating: true },
1866
+ { tool: "webhooks.list", method: "webhooks.list", description: "List webhooks." },
1867
+ { tool: "webhooks.info", method: "webhooks.info", description: "Get webhook details." },
1868
+ { tool: "webhooks.create", method: "webhooks.create", description: "Create a webhook.", mutating: true },
1869
+ { tool: "webhooks.update", method: "webhooks.update", description: "Update a webhook.", mutating: true },
1870
+ { tool: "webhooks.delete", method: "webhooks.delete", description: "Delete a webhook.", mutating: true },
1871
+ { tool: "users.list", method: "users.list", description: "List users." },
1872
+ {
1873
+ tool: "users.info",
1874
+ method: "users.info",
1875
+ description: "Get user details by ID/email or remembered user reference.",
1876
+ resolveEntity: {
1877
+ type: "user",
1878
+ resultField: "userId",
1879
+ passthroughKeys: ["ids", "email"],
1880
+ },
1881
+ },
1882
+ { tool: "users.invite", method: "users.invite", description: "Invite a user.", mutating: true },
1883
+ {
1884
+ tool: "users.update_role",
1885
+ method: "users.update_role",
1886
+ description: "Update a user's workspace role.",
1887
+ mutating: true,
1888
+ },
1889
+ { tool: "users.activate", method: "users.activate", description: "Activate a user.", mutating: true },
1890
+ { tool: "users.suspend", method: "users.suspend", description: "Suspend a user.", mutating: true },
1891
+ { tool: "groups.list", method: "groups.list", description: "List groups." },
1892
+ {
1893
+ tool: "groups.info",
1894
+ method: "groups.info",
1895
+ description: "Get group details by ID or remembered group reference.",
1896
+ resolveEntity: {
1897
+ type: "group",
1898
+ resultField: "groupId",
1899
+ passthroughKeys: ["ids"],
1900
+ },
1901
+ },
1902
+ {
1903
+ tool: "groups.memberships",
1904
+ method: "groups.memberships",
1905
+ description: "Resolve a group and list group user memberships.",
1906
+ resolveEntity: {
1907
+ type: "group",
1908
+ resultField: "groupId",
1909
+ },
1910
+ },
1911
+ { tool: "groups.create", method: "groups.create", description: "Create a group.", mutating: true },
1912
+ { tool: "groups.update", method: "groups.update", description: "Update a group.", mutating: true },
1913
+ { tool: "groups.delete", method: "groups.delete", description: "Delete a group.", mutating: true },
1914
+ {
1915
+ tool: "groups.add_user",
1916
+ method: "groups.add_user",
1917
+ description: "Resolve a group and user before adding the user to the group.",
1918
+ mutating: true,
1919
+ resolveEntity: {
1920
+ type: "group",
1921
+ outputField: "id",
1922
+ resultField: "groupId",
1923
+ exactKeys: ["id", "groupId"],
1924
+ queryKeys: ["groupQuery", "groupRef"],
1925
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1926
+ },
1927
+ resolvePrincipal: {
1928
+ type: "user",
1929
+ outputField: "userId",
1930
+ resultField: "userId",
1931
+ exactKeys: ["userId"],
1932
+ queryKeys: ["userQuery", "userRef"],
1933
+ arrayQueryKeys: ["userQueries", "userRefs"],
1934
+ },
1935
+ },
1936
+ {
1937
+ tool: "groups.remove_user",
1938
+ method: "groups.remove_user",
1939
+ description: "Resolve a group and user before removing the user from the group.",
1940
+ mutating: true,
1941
+ resolveEntity: {
1942
+ type: "group",
1943
+ outputField: "id",
1944
+ resultField: "groupId",
1945
+ exactKeys: ["id", "groupId"],
1946
+ queryKeys: ["groupQuery", "groupRef"],
1947
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1948
+ },
1949
+ resolvePrincipal: {
1950
+ type: "user",
1951
+ outputField: "userId",
1952
+ resultField: "userId",
1953
+ exactKeys: ["userId"],
1954
+ queryKeys: ["userQuery", "userRef"],
1955
+ arrayQueryKeys: ["userQueries", "userRefs"],
1956
+ },
1957
+ },
1958
+ {
1959
+ tool: "collections.memberships",
1960
+ method: "collections.memberships",
1961
+ description: "Resolve a collection and list collection user memberships.",
1962
+ resolveAccess: "collection",
1963
+ },
1964
+ {
1965
+ tool: "collections.group_memberships",
1966
+ method: "collections.group_memberships",
1967
+ description: "Resolve a collection and list collection group memberships.",
1968
+ resolveAccess: "collection",
1969
+ },
1970
+ {
1971
+ tool: "collections.add_user",
1972
+ method: "collections.add_user",
1973
+ description: "Resolve a collection and user before adding collection access.",
1974
+ mutating: true,
1975
+ resolveAccess: "collection",
1976
+ resolvePrincipal: {
1977
+ type: "user",
1978
+ outputField: "userId",
1979
+ resultField: "userId",
1980
+ exactKeys: ["userId"],
1981
+ queryKeys: ["userQuery", "userRef"],
1982
+ arrayQueryKeys: ["userQueries", "userRefs"],
1983
+ },
1984
+ },
1985
+ {
1986
+ tool: "collections.remove_user",
1987
+ method: "collections.remove_user",
1988
+ description: "Resolve a collection and user before removing collection access.",
1989
+ mutating: true,
1990
+ resolveAccess: "collection",
1991
+ resolvePrincipal: {
1992
+ type: "user",
1993
+ outputField: "userId",
1994
+ resultField: "userId",
1995
+ exactKeys: ["userId"],
1996
+ queryKeys: ["userQuery", "userRef"],
1997
+ arrayQueryKeys: ["userQueries", "userRefs"],
1998
+ },
1999
+ },
2000
+ {
2001
+ tool: "collections.add_group",
2002
+ method: "collections.add_group",
2003
+ description: "Resolve a collection and group before adding group collection access.",
2004
+ mutating: true,
2005
+ resolveAccess: "collection",
2006
+ resolvePrincipal: {
2007
+ type: "group",
2008
+ outputField: "groupId",
2009
+ resultField: "groupId",
2010
+ exactKeys: ["groupId"],
2011
+ queryKeys: ["groupQuery", "groupRef"],
2012
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
2013
+ },
2014
+ },
2015
+ {
2016
+ tool: "collections.remove_group",
2017
+ method: "collections.remove_group",
2018
+ description: "Resolve a collection and group before removing group collection access.",
2019
+ mutating: true,
2020
+ resolveAccess: "collection",
2021
+ resolvePrincipal: {
2022
+ type: "group",
2023
+ outputField: "groupId",
2024
+ resultField: "groupId",
2025
+ exactKeys: ["groupId"],
2026
+ queryKeys: ["groupQuery", "groupRef"],
2027
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
2028
+ },
2029
+ },
2030
+ {
2031
+ tool: "documents.users",
2032
+ method: "documents.users",
2033
+ description: "Resolve a document and list users with access to it.",
2034
+ resolveAccess: "document",
2035
+ },
2036
+ {
2037
+ tool: "documents.memberships",
2038
+ method: "documents.memberships",
2039
+ description: "Resolve a document and list document user memberships.",
2040
+ resolveAccess: "document",
2041
+ },
2042
+ {
2043
+ tool: "documents.group_memberships",
2044
+ method: "documents.group_memberships",
2045
+ description: "Resolve a document and list document group memberships.",
2046
+ resolveAccess: "document",
2047
+ },
2048
+ {
2049
+ tool: "documents.add_user",
2050
+ method: "documents.add_user",
2051
+ description: "Resolve a document and user before adding document access.",
2052
+ mutating: true,
2053
+ resolveAccess: "document",
2054
+ resolvePrincipal: {
2055
+ type: "user",
2056
+ outputField: "userId",
2057
+ resultField: "userId",
2058
+ exactKeys: ["userId"],
2059
+ queryKeys: ["userQuery", "userRef"],
2060
+ arrayQueryKeys: ["userQueries", "userRefs"],
2061
+ },
2062
+ },
2063
+ {
2064
+ tool: "documents.remove_user",
2065
+ method: "documents.remove_user",
2066
+ description: "Resolve a document and user before removing document access.",
2067
+ mutating: true,
2068
+ resolveAccess: "document",
2069
+ resolvePrincipal: {
2070
+ type: "user",
2071
+ outputField: "userId",
2072
+ resultField: "userId",
2073
+ exactKeys: ["userId"],
2074
+ queryKeys: ["userQuery", "userRef"],
2075
+ arrayQueryKeys: ["userQueries", "userRefs"],
2076
+ },
2077
+ },
2078
+ {
2079
+ tool: "documents.add_group",
2080
+ method: "documents.add_group",
2081
+ description: "Resolve a document and group before adding group document access.",
2082
+ mutating: true,
2083
+ resolveAccess: "document",
2084
+ resolvePrincipal: {
2085
+ type: "group",
2086
+ outputField: "groupId",
2087
+ resultField: "groupId",
2088
+ exactKeys: ["groupId"],
2089
+ queryKeys: ["groupQuery", "groupRef"],
2090
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
2091
+ },
2092
+ },
2093
+ {
2094
+ tool: "documents.remove_group",
2095
+ method: "documents.remove_group",
2096
+ description: "Resolve a document and group before removing group document access.",
2097
+ mutating: true,
2098
+ resolveAccess: "document",
2099
+ resolvePrincipal: {
2100
+ type: "group",
2101
+ outputField: "groupId",
2102
+ resultField: "groupId",
2103
+ exactKeys: ["groupId"],
2104
+ queryKeys: ["groupQuery", "groupRef"],
2105
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
2106
+ },
2107
+ },
2108
+ { tool: "file_operations.list", method: "fileOperations.list", description: "List file operations." },
2109
+ { tool: "file_operations.info", method: "fileOperations.info", description: "Get file operation details." },
2110
+ { tool: "file_operations.delete", method: "fileOperations.delete", description: "Delete a file operation.", mutating: true },
2111
+ ];
2112
+
2113
+ const RPC_TOOLS = Object.fromEntries(
2114
+ RPC_WRAPPER_DEFS.map((def) => [
2115
+ def.tool,
2116
+ makeRpcContract({
2117
+ ...def,
2118
+ mutating: !!def.mutating,
2119
+ }),
2120
+ ])
2121
+ );
2122
+
2123
+ function parseQuestionItem(raw, index) {
2124
+ if (typeof raw === "string") {
2125
+ const question = raw.trim();
550
2126
  if (!question) {
551
2127
  throw new CliError(`questions[${index}] must not be empty`);
552
2128
  }
@@ -557,57 +2133,396 @@ function parseQuestionItem(raw, index) {
557
2133
  };
558
2134
  }
559
2135
 
560
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
561
- const question = String(raw.question ?? raw.query ?? "").trim();
562
- if (!question) {
563
- throw new CliError(`questions[${index}].question is required`);
564
- }
565
- const body = buildBody(raw, ["question", "query"]);
2136
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
2137
+ const question = String(raw.question ?? raw.query ?? "").trim();
2138
+ if (!question) {
2139
+ throw new CliError(`questions[${index}].question is required`);
2140
+ }
2141
+ const body = buildBody(raw, ["question", "query"]);
2142
+ return {
2143
+ question,
2144
+ body,
2145
+ documentId: body.id || body.documentId || null,
2146
+ };
2147
+ }
2148
+
2149
+ throw new CliError(`questions[${index}] must be string or object`);
2150
+ }
2151
+
2152
+ function isAnswerEndpointUnsupported(err) {
2153
+ if (!(err instanceof ApiError)) {
2154
+ return false;
2155
+ }
2156
+ if (err.details?.status !== 404) {
2157
+ return false;
2158
+ }
2159
+ const url = String(err.details?.url || "").toLowerCase();
2160
+ const message = String(err.message || "").toLowerCase();
2161
+ return url.includes("documents.answerquestion") || message.includes("answerquestion");
2162
+ }
2163
+
2164
+ function normalizeFallbackAnswerHit(row, contextChars = 220) {
2165
+ const doc = row?.document || row || {};
2166
+ const context = typeof row?.context === "string" ? row.context : "";
2167
+ return compactValue({
2168
+ id: doc.id,
2169
+ title: doc.title,
2170
+ collectionId: doc.collectionId,
2171
+ parentDocumentId: doc.parentDocumentId,
2172
+ updatedAt: doc.updatedAt,
2173
+ publishedAt: doc.publishedAt,
2174
+ urlId: doc.urlId,
2175
+ ranking: row?.ranking,
2176
+ context: context.length > contextChars ? `${context.slice(0, contextChars)}...` : context,
2177
+ });
2178
+ }
2179
+
2180
+ function firstAnswerReference(args = {}, keys = [], arrayKeys = []) {
2181
+ for (const key of keys) {
2182
+ const value = String(args[key] || "").trim();
2183
+ if (value) {
2184
+ return { key, value };
2185
+ }
2186
+ }
2187
+ for (const key of arrayKeys) {
2188
+ if (!Array.isArray(args[key])) {
2189
+ continue;
2190
+ }
2191
+ for (const item of args[key]) {
2192
+ const value = String(item || "").trim();
2193
+ if (value) {
2194
+ return { key, value };
2195
+ }
2196
+ }
2197
+ }
2198
+ return null;
2199
+ }
2200
+
2201
+ function answerResolutionFromMemoryCandidate(resolved, ref, config, args = {}) {
2202
+ const candidates = resolved.result?.candidates || [];
2203
+ const topCandidate = candidates[0] || null;
2204
+ const strict = args.strict !== false;
2205
+ const strictThreshold = Math.max(0, toInteger(args.strictThreshold, 85));
2206
+ const topScore = Number(topCandidate?.score || 0);
2207
+
2208
+ if (!topCandidate) {
2209
+ return {
2210
+ error: {
2211
+ failed: {
2212
+ kind: ref.key,
2213
+ value: ref.value,
2214
+ status: "not_found",
2215
+ },
2216
+ memory: resolved.result?.memory || null,
2217
+ },
2218
+ };
2219
+ }
2220
+ if (strict && topScore < strictThreshold) {
2221
+ return {
2222
+ error: {
2223
+ failed: {
2224
+ kind: ref.key,
2225
+ value: ref.value,
2226
+ status: "low_confidence",
2227
+ strictThreshold,
2228
+ },
2229
+ candidate: topCandidate,
2230
+ candidates,
2231
+ memory: resolved.result?.memory || null,
2232
+ },
2233
+ };
2234
+ }
2235
+
2236
+ const live = (resolved.result?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
2237
+ || (resolved.result?.live || [])[0]
2238
+ || null;
2239
+ if (live && !live.ok) {
2240
+ return {
2241
+ error: {
2242
+ failed: {
2243
+ kind: ref.key,
2244
+ value: ref.value,
2245
+ status: "hydrate_failed",
2246
+ error: live.error,
2247
+ statusCode: live.status,
2248
+ },
2249
+ candidate: topCandidate,
2250
+ memory: resolved.result?.memory || live.memory || null,
2251
+ },
2252
+ };
2253
+ }
2254
+
2255
+ return {
2256
+ id: topCandidate.id,
2257
+ resultField: config.resultField,
2258
+ resolution: compactValue({
2259
+ mode: "memory",
2260
+ kind: ref.key,
2261
+ value: ref.value,
2262
+ id: topCandidate.id,
2263
+ name: topCandidate.name,
2264
+ email: topCandidate.email,
2265
+ candidate: topCandidate,
2266
+ live,
2267
+ memory: resolved.result?.memory || null,
2268
+ }) || { id: topCandidate.id },
2269
+ };
2270
+ }
2271
+
2272
+ async function resolveAnswerEntityFilter(ctx, args = {}, config) {
2273
+ const exact = String(args[config.idKey] || "").trim();
2274
+ if (exact) {
2275
+ return { id: exact, resultField: config.resultField };
2276
+ }
2277
+ const ref = firstAnswerReference(args, config.queryKeys, config.arrayQueryKeys);
2278
+ if (!ref) {
2279
+ return null;
2280
+ }
2281
+
2282
+ const threshold = Math.max(0, toInteger(args.strictThreshold, 85));
2283
+ const resolved = await memoryResolveTool(ctx, {
2284
+ query: ref.value,
2285
+ type: config.type,
2286
+ profile: args.profile,
2287
+ limit: Math.max(1, toInteger(args.resolveLimit, 5)),
2288
+ hydrateLimit: 1,
2289
+ maxAgeHours: args.maxAgeHours,
2290
+ minScore: args.minScore === undefined && args.strict !== false ? threshold : args.minScore,
2291
+ strict: args.strict,
2292
+ strictThreshold: args.strictThreshold,
2293
+ fallbackSearch: args.fallbackSearch,
2294
+ fallbackMinScore: args.fallbackMinScore === undefined && args.strict !== false ? threshold : args.fallbackMinScore,
2295
+ fallbackLimit: args.fallbackLimit,
2296
+ refresh: args.refresh !== false,
2297
+ maxAttempts: args.maxAttempts,
2298
+ });
2299
+
2300
+ return {
2301
+ ...answerResolutionFromMemoryCandidate(resolved, ref, config, args),
2302
+ resultField: config.resultField,
2303
+ };
2304
+ }
2305
+
2306
+ async function resolveAnswerDocumentTarget(ctx, args = {}) {
2307
+ const exact = String(args.documentId || args.id || "").trim();
2308
+ if (exact) {
2309
+ return { id: exact, resultField: "documentId" };
2310
+ }
2311
+
2312
+ const ref = firstAnswerReference(
2313
+ args,
2314
+ ["documentQuery", "documentRef", "shareId", "urlId", "url"],
2315
+ ["documentQueries", "documentRefs", "refs", "shareIds", "urlIds", "urls"]
2316
+ );
2317
+ if (!ref) {
2318
+ return null;
2319
+ }
2320
+
2321
+ const opened = await documentsOpenBatchTool(ctx, compactValue({
2322
+ queries: ["documentQuery", "documentQueries"].includes(ref.key) ? [ref.value] : undefined,
2323
+ refs: ["documentRef", "documentRefs", "refs"].includes(ref.key) ? [ref.value] : undefined,
2324
+ shareIds: ["shareId", "shareIds"].includes(ref.key) ? [ref.value] : undefined,
2325
+ urlIds: ["urlId", "urlIds"].includes(ref.key) ? [ref.value] : undefined,
2326
+ urls: ["url", "urls"].includes(ref.key) ? [ref.value] : undefined,
2327
+ profile: args.profile,
2328
+ limit: args.resolveLimit,
2329
+ minScore: args.minScore,
2330
+ maxAgeHours: args.maxAgeHours,
2331
+ refresh: args.refresh,
2332
+ strict: args.strict,
2333
+ strictThreshold: args.strictThreshold,
2334
+ fallbackSearch: args.fallbackSearch,
2335
+ fallbackMinScore: args.fallbackMinScore,
2336
+ fallbackLimit: args.fallbackLimit,
2337
+ fallbackMode: args.fallbackMode,
2338
+ collectionId: args.resolveCollectionId || args.collectionId,
2339
+ view: "summary",
2340
+ concurrency: args.resolveConcurrency,
2341
+ hydrateConcurrency: args.resolveHydrateConcurrency,
2342
+ maxAttempts: args.maxAttempts,
2343
+ }) || {});
2344
+
2345
+ const item = opened.result?.items?.[0] || null;
2346
+ if (item?.ok && item.document?.id) {
566
2347
  return {
567
- question,
568
- body,
569
- documentId: body.id || body.documentId || null,
2348
+ id: item.document.id,
2349
+ resultField: "documentId",
2350
+ document: item.document,
2351
+ resolution: compactValue({
2352
+ mode: item.mode || "memory",
2353
+ kind: ref.key,
2354
+ value: ref.value,
2355
+ id: item.document.id,
2356
+ title: item.document.title,
2357
+ candidate: item.candidate,
2358
+ memory: opened.result?.memory || null,
2359
+ }) || { id: item.document.id },
570
2360
  };
571
2361
  }
572
2362
 
573
- throw new CliError(`questions[${index}] must be string or object`);
2363
+ return {
2364
+ resultField: "documentId",
2365
+ error: compactValue({
2366
+ failed: {
2367
+ kind: ref.key,
2368
+ value: ref.value,
2369
+ status: item?.status || "not_found",
2370
+ error: item?.error,
2371
+ },
2372
+ candidate: item?.candidate,
2373
+ candidates: item?.candidates,
2374
+ memory: opened.result?.memory || null,
2375
+ }) || {
2376
+ failed: {
2377
+ kind: ref.key,
2378
+ value: ref.value,
2379
+ status: "not_found",
2380
+ },
2381
+ },
2382
+ };
574
2383
  }
575
2384
 
576
- function isAnswerEndpointUnsupported(err) {
577
- if (!(err instanceof ApiError)) {
578
- return false;
2385
+ function hasAnswerScopeSelectors(args = {}) {
2386
+ return !!firstAnswerReference(
2387
+ args,
2388
+ [
2389
+ "id",
2390
+ "documentId",
2391
+ "documentQuery",
2392
+ "documentRef",
2393
+ "shareId",
2394
+ "urlId",
2395
+ "url",
2396
+ "collectionId",
2397
+ "collectionQuery",
2398
+ "collectionRef",
2399
+ "userId",
2400
+ "userQuery",
2401
+ "userRef",
2402
+ ],
2403
+ [
2404
+ "documentQueries",
2405
+ "documentRefs",
2406
+ "refs",
2407
+ "shareIds",
2408
+ "urlIds",
2409
+ "urls",
2410
+ "collectionQueries",
2411
+ "collectionRefs",
2412
+ "userQueries",
2413
+ "userRefs",
2414
+ ]
2415
+ );
2416
+ }
2417
+
2418
+ async function resolveAnswerScope(ctx, args = {}) {
2419
+ const collection = await resolveAnswerEntityFilter(ctx, args, {
2420
+ type: "collection",
2421
+ idKey: "collectionId",
2422
+ resultField: "collectionId",
2423
+ queryKeys: ["collectionQuery", "collectionRef"],
2424
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
2425
+ });
2426
+ const user = await resolveAnswerEntityFilter(ctx, args, {
2427
+ type: "user",
2428
+ idKey: "userId",
2429
+ resultField: "userId",
2430
+ queryKeys: ["userQuery", "userRef"],
2431
+ arrayQueryKeys: ["userQueries", "userRefs"],
2432
+ });
2433
+ const preDocumentFilters = [collection, user].filter(Boolean);
2434
+ const failedFilter = preDocumentFilters.find((filter) => filter?.error);
2435
+ if (failedFilter) {
2436
+ return { error: failedFilter.error, resultField: failedFilter.resultField };
579
2437
  }
580
- if (err.details?.status !== 404) {
581
- return false;
2438
+
2439
+ const document = await resolveAnswerDocumentTarget(ctx, {
2440
+ ...args,
2441
+ collectionId: collection?.id || args.collectionId,
2442
+ });
2443
+
2444
+ const filters = [document, collection, user].filter(Boolean);
2445
+ const failed = filters.find((filter) => filter?.error);
2446
+ if (failed) {
2447
+ return { error: failed.error, resultField: failed.resultField };
582
2448
  }
583
- const url = String(err.details?.url || "").toLowerCase();
584
- const message = String(err.message || "").toLowerCase();
585
- return url.includes("documents.answerquestion") || message.includes("answerquestion");
2449
+
2450
+ const resolution = {};
2451
+ for (const filter of filters) {
2452
+ if (filter.resolution) {
2453
+ resolution[filter.resultField] = filter.resolution;
2454
+ }
2455
+ }
2456
+
2457
+ return {
2458
+ args: compactValue({
2459
+ ...args,
2460
+ documentId: document?.id || args.documentId || args.id,
2461
+ collectionId: collection?.id || args.collectionId,
2462
+ userId: user?.id || args.userId,
2463
+ }) || {},
2464
+ document: document?.document || null,
2465
+ resolution: Object.keys(resolution).length > 0 ? resolution : null,
2466
+ };
586
2467
  }
587
2468
 
588
- function normalizeFallbackAnswerHit(row, contextChars = 220) {
589
- const doc = row?.document || row || {};
590
- const context = typeof row?.context === "string" ? row.context : "";
591
- return compactValue({
592
- id: doc.id,
593
- title: doc.title,
594
- collectionId: doc.collectionId,
595
- parentDocumentId: doc.parentDocumentId,
596
- updatedAt: doc.updatedAt,
597
- publishedAt: doc.publishedAt,
598
- urlId: doc.urlId,
599
- ranking: row?.ranking,
600
- context: context.length > contextChars ? `${context.slice(0, contextChars)}...` : context,
601
- });
2469
+ function buildAnswerEndpointBody(args = {}, question) {
2470
+ return {
2471
+ ...buildBody(args, ["question", "query", "limit", ...ANSWER_RESOLVE_ARG_KEYS]),
2472
+ query: question,
2473
+ };
2474
+ }
2475
+
2476
+ function buildAnswerResolutionMiss(tool, ctx, question, prepared) {
2477
+ return {
2478
+ tool,
2479
+ profile: ctx.profile.id,
2480
+ result: compactValue({
2481
+ ok: false,
2482
+ status: prepared.error?.failed?.status || "not_found",
2483
+ [prepared.resultField || "filterId"]: "",
2484
+ question,
2485
+ resolution: prepared.error,
2486
+ documents: [],
2487
+ }) || {},
2488
+ };
602
2489
  }
603
2490
 
604
- async function buildAnswerFallbackResult(ctx, question, args = {}) {
2491
+ async function buildAnswerFallbackResult(ctx, question, args = {}, prepared = {}) {
605
2492
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
606
2493
  const contextChars = Math.max(80, toInteger(args.contextChars, 220));
607
2494
  const limit = Math.max(1, Math.min(8, toInteger(args.limit, 5)));
608
2495
  const scopedDocumentId = args.documentId || args.id;
609
2496
 
610
2497
  if (scopedDocumentId) {
2498
+ if (prepared.document?.id === scopedDocumentId) {
2499
+ const document = normalizeFallbackAnswerHit(prepared.document, contextChars);
2500
+ return {
2501
+ question,
2502
+ answer: "",
2503
+ noAnswerReason: "documents.answerQuestion is unsupported by this Outline deployment; returning the scoped document as retrieval evidence instead.",
2504
+ unsupported: true,
2505
+ fallbackUsed: true,
2506
+ fallbackTool: "documents.info",
2507
+ fallbackSuggestion: {
2508
+ tool: "documents.info",
2509
+ args: compactValue({
2510
+ id: scopedDocumentId,
2511
+ view: "summary",
2512
+ }),
2513
+ },
2514
+ resolution: prepared.resolution,
2515
+ documents: document ? [document] : [],
2516
+ retrieval: {
2517
+ query: question,
2518
+ result: {
2519
+ ok: true,
2520
+ data: document,
2521
+ },
2522
+ },
2523
+ };
2524
+ }
2525
+
611
2526
  const res = await ctx.client.call("documents.info", { id: scopedDocumentId }, { maxAttempts });
612
2527
  const document = normalizeFallbackAnswerHit(res.body?.data, contextChars);
613
2528
  return {
@@ -625,6 +2540,7 @@ async function buildAnswerFallbackResult(ctx, question, args = {}) {
625
2540
  }),
626
2541
  },
627
2542
  documents: document ? [document] : [],
2543
+ resolution: prepared.resolution,
628
2544
  retrieval: {
629
2545
  query: question,
630
2546
  result: compactValue({
@@ -673,6 +2589,7 @@ async function buildAnswerFallbackResult(ctx, question, args = {}) {
673
2589
  }),
674
2590
  },
675
2591
  documents,
2592
+ resolution: prepared.resolution,
676
2593
  retrieval: {
677
2594
  query: question,
678
2595
  result: compactValue({
@@ -689,10 +2606,12 @@ async function documentsAnswerTool(ctx, args = {}) {
689
2606
  throw new CliError("documents.answer requires args.question or args.query");
690
2607
  }
691
2608
 
692
- const body = {
693
- ...buildBody(args, ["question", "query", "limit"]),
694
- query: question,
695
- };
2609
+ const prepared = await resolveAnswerScope(ctx, args);
2610
+ if (prepared.error) {
2611
+ return buildAnswerResolutionMiss("documents.answer", ctx, question, prepared);
2612
+ }
2613
+
2614
+ const body = buildAnswerEndpointBody(prepared.args, question);
696
2615
 
697
2616
  try {
698
2617
  const res = await ctx.client.call("documents.answerQuestion", body, {
@@ -705,8 +2624,8 @@ async function documentsAnswerTool(ctx, args = {}) {
705
2624
  profile: ctx.profile.id,
706
2625
  result:
707
2626
  payload && typeof payload === "object"
708
- ? { question, ...payload }
709
- : { question, data: payload },
2627
+ ? compactValue({ question, resolution: prepared.resolution, ...payload }) || { question, ...payload }
2628
+ : { question, resolution: prepared.resolution, data: payload },
710
2629
  };
711
2630
  } catch (err) {
712
2631
  if (!isAnswerEndpointUnsupported(err)) {
@@ -716,7 +2635,7 @@ async function documentsAnswerTool(ctx, args = {}) {
716
2635
  return {
717
2636
  tool: "documents.answer",
718
2637
  profile: ctx.profile.id,
719
- result: await buildAnswerFallbackResult(ctx, question, args),
2638
+ result: await buildAnswerFallbackResult(ctx, question, prepared.args, prepared),
720
2639
  };
721
2640
  }
722
2641
  }
@@ -734,20 +2653,34 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
734
2653
  throw new CliError("documents.answer_batch requires args.question or args.questions[]");
735
2654
  }
736
2655
 
737
- const baseBody = buildBody(args, ["question", "questions", "query", "concurrency", "limit"]);
2656
+ const basePrepared = await resolveAnswerScope(ctx, args);
738
2657
  const includePolicies = !!args.includePolicies;
739
2658
  const maxAttempts = toInteger(args.maxAttempts, 2);
740
2659
  const concurrency = Math.max(1, Math.min(10, toInteger(args.concurrency, 3)));
741
2660
 
742
2661
  const items = await mapLimit(rawItems, concurrency, async (raw, index) => {
743
2662
  let parsed;
2663
+ let prepared;
744
2664
  try {
745
2665
  parsed = parseQuestionItem(raw, index);
746
- const body = {
747
- ...baseBody,
748
- ...parsed.body,
749
- query: parsed.question,
750
- };
2666
+ prepared = hasAnswerScopeSelectors(parsed.body)
2667
+ ? await resolveAnswerScope(ctx, { ...args, ...parsed.body })
2668
+ : basePrepared;
2669
+ if (prepared.error) {
2670
+ return {
2671
+ index,
2672
+ ok: false,
2673
+ question: parsed.question,
2674
+ documentId: parsed.documentId || null,
2675
+ error: "Unable to resolve answer scope",
2676
+ status: prepared.error?.failed?.status || "not_found",
2677
+ resolution: prepared.error,
2678
+ };
2679
+ }
2680
+ const answerArgs = hasAnswerScopeSelectors(parsed.body)
2681
+ ? prepared.args
2682
+ : compactValue({ ...prepared.args, ...parsed.body }) || prepared.args;
2683
+ const body = buildAnswerEndpointBody(answerArgs, parsed.question);
751
2684
  const res = await ctx.client.call("documents.answerQuestion", body, {
752
2685
  maxAttempts,
753
2686
  });
@@ -756,21 +2689,32 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
756
2689
  index,
757
2690
  ok: true,
758
2691
  question: parsed.question,
759
- documentId: parsed.documentId,
760
- result: payload,
2692
+ documentId: body.documentId || parsed.documentId,
2693
+ result: compactValue({ resolution: prepared.resolution, ...payload }) || payload,
761
2694
  };
762
2695
  } catch (err) {
763
2696
  if (parsed && isAnswerEndpointUnsupported(err)) {
764
2697
  try {
2698
+ if (prepared.error) {
2699
+ return {
2700
+ index,
2701
+ ok: false,
2702
+ question: parsed.question,
2703
+ documentId: parsed.documentId || null,
2704
+ error: "Unable to resolve answer scope",
2705
+ status: prepared.error?.failed?.status || "not_found",
2706
+ resolution: prepared.error,
2707
+ };
2708
+ }
2709
+ const fallbackArgs = hasAnswerScopeSelectors(parsed.body)
2710
+ ? prepared.args
2711
+ : compactValue({ ...prepared.args, ...parsed.body }) || prepared.args;
765
2712
  return {
766
2713
  index,
767
2714
  ok: true,
768
2715
  question: parsed.question,
769
- documentId: parsed.documentId,
770
- result: await buildAnswerFallbackResult(ctx, parsed.question, {
771
- ...args,
772
- ...parsed.body,
773
- }),
2716
+ documentId: fallbackArgs.documentId || parsed.documentId,
2717
+ result: await buildAnswerFallbackResult(ctx, parsed.question, fallbackArgs, prepared),
774
2718
  };
775
2719
  } catch (fallbackErr) {
776
2720
  if (fallbackErr instanceof ApiError || fallbackErr instanceof CliError) {
@@ -815,14 +2759,31 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
815
2759
  }
816
2760
 
817
2761
  async function documentsAttachmentsTool(ctx, args = {}) {
818
- const doc = await readDocumentForAttachments(ctx, args);
2762
+ const read = await readDocumentForAttachments(ctx, args);
2763
+ const doc = read.document;
2764
+ if (!doc) {
2765
+ return {
2766
+ tool: "documents.attachments",
2767
+ profile: ctx.profile.id,
2768
+ result: {
2769
+ ok: false,
2770
+ status: "not_found",
2771
+ document: null,
2772
+ resolution: read.resolution,
2773
+ total: 0,
2774
+ attachments: [],
2775
+ },
2776
+ };
2777
+ }
819
2778
  const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
820
2779
 
821
2780
  return {
822
2781
  tool: "documents.attachments",
823
2782
  profile: ctx.profile.id,
824
2783
  result: {
2784
+ ok: true,
825
2785
  document: summarizeAttachmentDocument(doc),
2786
+ resolution: read.resolution,
826
2787
  total: attachments.length,
827
2788
  attachments,
828
2789
  },
@@ -843,7 +2804,25 @@ async function attachmentsDownloadTool(ctx, args = {}) {
843
2804
  }
844
2805
 
845
2806
  async function documentsDownloadAttachmentsTool(ctx, args = {}) {
846
- const doc = await readDocumentForAttachments(ctx, args);
2807
+ const read = await readDocumentForAttachments(ctx, args);
2808
+ const doc = read.document;
2809
+ if (!doc) {
2810
+ return {
2811
+ tool: "documents.download_attachments",
2812
+ profile: ctx.profile.id,
2813
+ result: {
2814
+ ok: false,
2815
+ status: "not_found",
2816
+ document: null,
2817
+ resolution: read.resolution,
2818
+ total: 0,
2819
+ succeeded: 0,
2820
+ failed: 0,
2821
+ outputDir: path.resolve(String(args.outputDir || path.join(defaultTmpDir(), "attachments"))),
2822
+ items: [],
2823
+ },
2824
+ };
2825
+ }
847
2826
  const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
848
2827
  const concurrency = Math.max(1, Math.min(8, toInteger(args.concurrency, 3)));
849
2828
  const items = await mapLimit(attachments, concurrency, async (attachment, index) => {
@@ -871,7 +2850,9 @@ async function documentsDownloadAttachmentsTool(ctx, args = {}) {
871
2850
  tool: "documents.download_attachments",
872
2851
  profile: ctx.profile.id,
873
2852
  result: {
2853
+ ok: failed === 0,
874
2854
  document: summarizeAttachmentDocument(doc),
2855
+ resolution: read.resolution,
875
2856
  total: attachments.length,
876
2857
  succeeded: items.length - failed,
877
2858
  failed,
@@ -1289,12 +3270,239 @@ function normalizeGraphSourceIds(args = {}) {
1289
3270
  if (args.id !== undefined && args.id !== null) {
1290
3271
  values.push(args.id);
1291
3272
  }
3273
+ if (args.documentId !== undefined && args.documentId !== null) {
3274
+ values.push(args.documentId);
3275
+ }
3276
+ if (args.seedId !== undefined && args.seedId !== null) {
3277
+ values.push(args.seedId);
3278
+ }
1292
3279
  for (const id of ensureStringArray(args.ids, "ids") || []) {
1293
3280
  values.push(id);
1294
3281
  }
3282
+ for (const id of ensureStringArray(args.documentIds, "documentIds") || []) {
3283
+ values.push(id);
3284
+ }
3285
+ for (const id of ensureStringArray(args.seedIds, "seedIds") || []) {
3286
+ values.push(id);
3287
+ }
1295
3288
  return uniqueStrings(values).sort(compareIdAsc);
1296
3289
  }
1297
3290
 
3291
+ function normalizeDocumentRefValues(args = {}) {
3292
+ const queries = [];
3293
+ if (args.query !== undefined && args.query !== null) {
3294
+ queries.push(args.query);
3295
+ }
3296
+ if (args.seedQuery !== undefined && args.seedQuery !== null) {
3297
+ queries.push(args.seedQuery);
3298
+ }
3299
+ queries.push(...(ensureStringArray(args.queries, "queries") || []));
3300
+ queries.push(...(ensureStringArray(args.seedQueries, "seedQueries") || []));
3301
+
3302
+ const shareIds = [];
3303
+ if (args.shareId !== undefined && args.shareId !== null) {
3304
+ shareIds.push(args.shareId);
3305
+ }
3306
+ if (args.seedShareId !== undefined && args.seedShareId !== null) {
3307
+ shareIds.push(args.seedShareId);
3308
+ }
3309
+ shareIds.push(...(ensureStringArray(args.shareIds, "shareIds") || []));
3310
+ shareIds.push(...(ensureStringArray(args.seedShareIds, "seedShareIds") || []));
3311
+
3312
+ const urlIds = [];
3313
+ if (args.urlId !== undefined && args.urlId !== null) {
3314
+ urlIds.push(args.urlId);
3315
+ }
3316
+ if (args.seedUrlId !== undefined && args.seedUrlId !== null) {
3317
+ urlIds.push(args.seedUrlId);
3318
+ }
3319
+ urlIds.push(...(ensureStringArray(args.urlIds, "urlIds") || []));
3320
+ urlIds.push(...(ensureStringArray(args.seedUrlIds, "seedUrlIds") || []));
3321
+
3322
+ const urls = [];
3323
+ if (args.url !== undefined && args.url !== null) {
3324
+ urls.push(args.url);
3325
+ }
3326
+ if (args.seedUrl !== undefined && args.seedUrl !== null) {
3327
+ urls.push(args.seedUrl);
3328
+ }
3329
+ urls.push(...(ensureStringArray(args.urls, "urls") || []));
3330
+ urls.push(...(ensureStringArray(args.seedUrls, "seedUrls") || []));
3331
+
3332
+ return {
3333
+ refs: [
3334
+ ...(ensureStringArray(args.refs, "refs") || []),
3335
+ ...(ensureStringArray(args.seedRefs, "seedRefs") || []),
3336
+ ],
3337
+ queries,
3338
+ shareIds,
3339
+ urlIds,
3340
+ urls,
3341
+ };
3342
+ }
3343
+
3344
+ function hasDocumentRefValues(refs) {
3345
+ return Object.values(refs).some((items) =>
3346
+ Array.isArray(items) && items.some((item) => String(item || "").trim())
3347
+ );
3348
+ }
3349
+
3350
+ async function resolveDocumentIdsForRead(ctx, args = {}) {
3351
+ const exactIds = normalizeGraphSourceIds(args);
3352
+ const refs = normalizeDocumentRefValues(args);
3353
+ const resolution = {
3354
+ exactIds,
3355
+ requested: {
3356
+ refs: refs.refs.filter((item) => String(item || "").trim()),
3357
+ queries: refs.queries.filter((item) => String(item || "").trim()),
3358
+ shareIds: refs.shareIds.filter((item) => String(item || "").trim()),
3359
+ urlIds: refs.urlIds.filter((item) => String(item || "").trim()),
3360
+ urls: refs.urls.filter((item) => String(item || "").trim()),
3361
+ },
3362
+ resolved: [],
3363
+ failed: [],
3364
+ memory: null,
3365
+ };
3366
+
3367
+ if (hasDocumentRefValues(refs)) {
3368
+ const opened = await documentsOpenBatchTool(ctx, compactValue({
3369
+ refs: refs.refs,
3370
+ queries: refs.queries,
3371
+ shareIds: refs.shareIds,
3372
+ urlIds: refs.urlIds,
3373
+ urls: refs.urls,
3374
+ profile: args.profile,
3375
+ limit: args.resolveLimit,
3376
+ minScore: args.minScore,
3377
+ maxAgeHours: args.maxAgeHours,
3378
+ refresh: args.refresh,
3379
+ strict: args.strict,
3380
+ strictThreshold: args.strictThreshold,
3381
+ fallbackSearch: args.fallbackSearch,
3382
+ fallbackMinScore: args.fallbackMinScore,
3383
+ fallbackLimit: args.fallbackLimit,
3384
+ fallbackMode: args.fallbackMode,
3385
+ collectionId: args.resolveCollectionId,
3386
+ view: "summary",
3387
+ concurrency: args.resolveConcurrency,
3388
+ hydrateConcurrency: args.resolveHydrateConcurrency,
3389
+ maxAttempts: args.maxAttempts,
3390
+ }) || {});
3391
+ resolution.memory = opened.result?.memory || null;
3392
+ for (const item of opened.result?.items || []) {
3393
+ if (item?.ok && item.document?.id) {
3394
+ resolution.resolved.push({
3395
+ index: item.index,
3396
+ kind: item.kind,
3397
+ value: item.value,
3398
+ id: item.document.id,
3399
+ title: item.document.title,
3400
+ mode: item.mode,
3401
+ candidate: item.candidate,
3402
+ });
3403
+ continue;
3404
+ }
3405
+ resolution.failed.push({
3406
+ index: item?.index,
3407
+ kind: item?.kind,
3408
+ value: item?.value,
3409
+ status: item?.status || "not_found",
3410
+ candidate: item?.candidate,
3411
+ candidates: item?.candidates,
3412
+ error: item?.error,
3413
+ });
3414
+ }
3415
+ }
3416
+
3417
+ const ids = uniqueStrings([
3418
+ ...exactIds,
3419
+ ...resolution.resolved.map((item) => item.id),
3420
+ ]).sort(compareIdAsc);
3421
+
3422
+ return {
3423
+ ids,
3424
+ resolution,
3425
+ };
3426
+ }
3427
+
3428
+ async function resolveCollectionIdForRead(ctx, args = {}) {
3429
+ const exactId = args.collectionId ? String(args.collectionId).trim() : "";
3430
+ if (exactId) {
3431
+ return {
3432
+ id: exactId,
3433
+ resolution: {
3434
+ exactId,
3435
+ resolved: null,
3436
+ failed: null,
3437
+ memory: null,
3438
+ },
3439
+ };
3440
+ }
3441
+
3442
+ const refArgs = compactValue({
3443
+ query: args.collectionQuery,
3444
+ id: args.collectionRefId,
3445
+ urlId: args.collectionUrlId,
3446
+ url: args.collectionUrl,
3447
+ profile: args.profile,
3448
+ limit: args.collectionResolveLimit || args.resolveLimit,
3449
+ minScore: args.collectionMinScore ?? args.minScore,
3450
+ maxAgeHours: args.collectionMaxAgeHours ?? args.maxAgeHours,
3451
+ refresh: args.refresh,
3452
+ strict: args.strict,
3453
+ strictThreshold: args.collectionStrictThreshold ?? args.strictThreshold,
3454
+ fallbackSearch: args.fallbackSearch,
3455
+ fallbackMinScore: args.collectionFallbackMinScore ?? args.fallbackMinScore,
3456
+ fallbackLimit: args.collectionFallbackLimit ?? args.fallbackLimit,
3457
+ view: "summary",
3458
+ maxAttempts: args.maxAttempts,
3459
+ }) || {};
3460
+
3461
+ if (!refArgs.query && !refArgs.id && !refArgs.urlId && !refArgs.url) {
3462
+ return {
3463
+ id: "",
3464
+ resolution: {
3465
+ exactId: "",
3466
+ resolved: null,
3467
+ failed: null,
3468
+ memory: null,
3469
+ },
3470
+ };
3471
+ }
3472
+
3473
+ const opened = await collectionsOpenTool(ctx, refArgs);
3474
+ if (opened.result?.ok && opened.result?.collection?.id) {
3475
+ return {
3476
+ id: opened.result.collection.id,
3477
+ resolution: {
3478
+ exactId: "",
3479
+ resolved: {
3480
+ id: opened.result.collection.id,
3481
+ name: opened.result.collection.name,
3482
+ mode: opened.result.mode,
3483
+ candidate: opened.result.candidate,
3484
+ },
3485
+ failed: null,
3486
+ memory: opened.result.memory || null,
3487
+ },
3488
+ };
3489
+ }
3490
+
3491
+ return {
3492
+ id: "",
3493
+ resolution: {
3494
+ exactId: "",
3495
+ resolved: null,
3496
+ failed: {
3497
+ status: opened.result?.status || "not_found",
3498
+ candidate: opened.result?.candidate,
3499
+ candidates: opened.result?.candidates,
3500
+ },
3501
+ memory: opened.result?.memory || null,
3502
+ },
3503
+ };
3504
+ }
3505
+
1298
3506
  function normalizeGraphSearchQueries(value) {
1299
3507
  return uniqueStrings(ensureStringArray(value, "searchQueries") || []);
1300
3508
  }
@@ -2137,9 +4345,19 @@ async function collectGraphNeighbors(ctx, sourceIds, options = {}) {
2137
4345
  }
2138
4346
 
2139
4347
  async function documentsBacklinksTool(ctx, args = {}) {
2140
- const id = String(args.id || "").trim();
4348
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4349
+ const id = resolved.ids[0] || "";
2141
4350
  if (!id) {
2142
- throw new CliError("documents.backlinks requires args.id");
4351
+ return {
4352
+ tool: "documents.backlinks",
4353
+ profile: ctx.profile.id,
4354
+ result: {
4355
+ ok: false,
4356
+ status: "not_found",
4357
+ data: [],
4358
+ resolution: resolved.resolution,
4359
+ },
4360
+ };
2143
4361
  }
2144
4362
 
2145
4363
  const view = normalizeGraphView(args.view);
@@ -2165,6 +4383,13 @@ async function documentsBacklinksTool(ctx, args = {}) {
2165
4383
  };
2166
4384
  }
2167
4385
  payload = maybeDropPolicies(payload, !!args.includePolicies);
4386
+ payload = compactValue({
4387
+ ...payload,
4388
+ ok: payload?.ok,
4389
+ resolution: (resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0)
4390
+ ? resolved.resolution
4391
+ : undefined,
4392
+ }) || {};
2168
4393
 
2169
4394
  return {
2170
4395
  tool: "documents.backlinks",
@@ -2174,9 +4399,24 @@ async function documentsBacklinksTool(ctx, args = {}) {
2174
4399
  }
2175
4400
 
2176
4401
  async function documentsGraphNeighborsTool(ctx, args = {}) {
2177
- const sourceIds = normalizeGraphSourceIds(args);
4402
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4403
+ const sourceIds = resolved.ids;
2178
4404
  if (sourceIds.length === 0) {
2179
- throw new CliError("documents.graph_neighbors requires args.id or args.ids[]");
4405
+ return {
4406
+ tool: "documents.graph_neighbors",
4407
+ profile: ctx.profile.id,
4408
+ result: {
4409
+ ok: false,
4410
+ status: "not_found",
4411
+ sourceIds: [],
4412
+ resolution: resolved.resolution,
4413
+ nodeCount: 0,
4414
+ edgeCount: 0,
4415
+ nodes: [],
4416
+ edges: [],
4417
+ errors: [],
4418
+ },
4419
+ };
2180
4420
  }
2181
4421
 
2182
4422
  const includeBacklinks = args.includeBacklinks !== false;
@@ -2202,12 +4442,16 @@ async function documentsGraphNeighborsTool(ctx, args = {}) {
2202
4442
 
2203
4443
  const nodes = buildGraphNodeList(collected.nodesById, view);
2204
4444
  const edges = sortGraphEdges(collected.edges);
4445
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4446
+ ? resolved.resolution
4447
+ : undefined;
2205
4448
 
2206
4449
  return {
2207
4450
  tool: "documents.graph_neighbors",
2208
4451
  profile: ctx.profile.id,
2209
4452
  result: {
2210
4453
  sourceIds,
4454
+ ...(resolution ? { resolution } : {}),
2211
4455
  includeBacklinks,
2212
4456
  includeSearchNeighbors,
2213
4457
  searchQueries,
@@ -2222,9 +4466,32 @@ async function documentsGraphNeighborsTool(ctx, args = {}) {
2222
4466
  }
2223
4467
 
2224
4468
  async function documentsGraphReportTool(ctx, args = {}) {
2225
- const requestedSeedIds = uniqueStrings(ensureStringArray(args.seedIds, "seedIds") || []).sort(compareIdAsc);
4469
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4470
+ const requestedSeedIds = resolved.ids;
2226
4471
  if (requestedSeedIds.length === 0) {
2227
- throw new CliError("documents.graph_report requires args.seedIds[]");
4472
+ return {
4473
+ tool: "documents.graph_report",
4474
+ profile: ctx.profile.id,
4475
+ result: {
4476
+ ok: false,
4477
+ status: "not_found",
4478
+ seedIds: [],
4479
+ requestedSeedCount: 0,
4480
+ resolution: resolved.resolution,
4481
+ depth: Math.max(0, Math.min(6, toInteger(args.depth, 2))),
4482
+ exploredDepth: 0,
4483
+ maxNodes: Math.max(1, Math.min(500, toInteger(args.maxNodes, 120))),
4484
+ includeBacklinks: args.includeBacklinks !== false,
4485
+ includeSearchNeighbors: args.includeSearchNeighbors === true,
4486
+ limitPerSource: Math.max(1, Math.min(100, toInteger(args.limitPerSource, 10))),
4487
+ truncated: false,
4488
+ nodeCount: 0,
4489
+ edgeCount: 0,
4490
+ nodes: [],
4491
+ edges: [],
4492
+ errors: [],
4493
+ },
4494
+ };
2228
4495
  }
2229
4496
 
2230
4497
  const includeBacklinks = args.includeBacklinks !== false;
@@ -2323,6 +4590,9 @@ async function documentsGraphReportTool(ctx, args = {}) {
2323
4590
  (edge) => allowedIds.has(edge.sourceId) && allowedIds.has(edge.targetId)
2324
4591
  )
2325
4592
  );
4593
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4594
+ ? resolved.resolution
4595
+ : undefined;
2326
4596
 
2327
4597
  return {
2328
4598
  tool: "documents.graph_report",
@@ -2330,6 +4600,7 @@ async function documentsGraphReportTool(ctx, args = {}) {
2330
4600
  result: {
2331
4601
  seedIds,
2332
4602
  requestedSeedCount: requestedSeedIds.length,
4603
+ ...(resolution ? { resolution } : {}),
2333
4604
  depth,
2334
4605
  exploredDepth,
2335
4606
  maxNodes,
@@ -2347,9 +4618,27 @@ async function documentsGraphReportTool(ctx, args = {}) {
2347
4618
  }
2348
4619
 
2349
4620
  async function documentsIssueRefsTool(ctx, args = {}) {
2350
- const ids = normalizeIssueRefIds(args);
4621
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4622
+ const ids = resolved.ids;
2351
4623
  if (ids.length === 0) {
2352
- throw new CliError("documents.issue_refs requires args.id or args.ids[]");
4624
+ return {
4625
+ tool: "documents.issue_refs",
4626
+ profile: ctx.profile.id,
4627
+ result: {
4628
+ ok: false,
4629
+ status: "not_found",
4630
+ requestedIds: [],
4631
+ resolution: resolved.resolution,
4632
+ documentCount: 0,
4633
+ documentsWithRefs: 0,
4634
+ refCount: 0,
4635
+ keyCount: 0,
4636
+ mentionCount: 0,
4637
+ keys: [],
4638
+ documents: [],
4639
+ errors: [],
4640
+ },
4641
+ };
2353
4642
  }
2354
4643
 
2355
4644
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
@@ -2361,12 +4650,16 @@ async function documentsIssueRefsTool(ctx, args = {}) {
2361
4650
  maxAttempts,
2362
4651
  view,
2363
4652
  });
4653
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4654
+ ? resolved.resolution
4655
+ : undefined;
2364
4656
 
2365
4657
  return {
2366
4658
  tool: "documents.issue_refs",
2367
4659
  profile: ctx.profile.id,
2368
4660
  result: {
2369
4661
  requestedIds: extracted.requestedIds,
4662
+ ...(resolution ? { resolution } : {}),
2370
4663
  issueDomains: extracted.issueDomains,
2371
4664
  keyPattern: extracted.keyPattern,
2372
4665
  ...extracted.summary,
@@ -2408,10 +4701,40 @@ async function documentsIssueRefReportTool(ctx, args = {}) {
2408
4701
  };
2409
4702
  }
2410
4703
 
4704
+ async function resolveTemplateSelector(ctx, args = {}, options = {}) {
4705
+ const resolved = await resolveEntityId(ctx, args, {
4706
+ type: "template",
4707
+ outputField: options.outputField || "id",
4708
+ resultField: "templateId",
4709
+ exactKeys: options.exactKeys || [options.outputField || "id"],
4710
+ queryKeys: ["templateQuery", "templateRef", "query"],
4711
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs", "queries"],
4712
+ });
4713
+ if (resolved?.error) {
4714
+ return resolved;
4715
+ }
4716
+ if (resolved?.id) {
4717
+ return resolved;
4718
+ }
4719
+ const exact = (options.exactKeys || [options.outputField || "id"])
4720
+ .map((key) => String(args[key] || "").trim())
4721
+ .find(Boolean);
4722
+ return exact ? { id: exact, resolution: null } : { id: "" };
4723
+ }
4724
+
2411
4725
  async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2412
- const id = String(args.id || "").trim();
4726
+ const resolvedTemplate = await resolveTemplateSelector(ctx, args, {
4727
+ outputField: "id",
4728
+ exactKeys: ["id"],
4729
+ });
4730
+ if (resolvedTemplate.error) {
4731
+ throw new CliError("templates.extract_placeholders could not resolve template", {
4732
+ resolution: resolvedTemplate.error,
4733
+ });
4734
+ }
4735
+ const id = String(resolvedTemplate.id || "").trim();
2413
4736
  if (!id) {
2414
- throw new CliError("templates.extract_placeholders requires args.id");
4737
+ throw new CliError("templates.extract_placeholders requires args.id or args.templateQuery");
2415
4738
  }
2416
4739
 
2417
4740
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
@@ -2425,7 +4748,9 @@ async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2425
4748
  profile: ctx.profile.id,
2426
4749
  result: {
2427
4750
  id: template?.id ? String(template.id) : id,
4751
+ templateId: id,
2428
4752
  title: template?.title ? String(template.title) : "",
4753
+ resolution: resolvedTemplate.resolution,
2429
4754
  placeholders: stats.placeholders,
2430
4755
  counts: stats.countsByPlaceholder,
2431
4756
  meta: {
@@ -2439,16 +4764,25 @@ async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2439
4764
  }
2440
4765
 
2441
4766
  async function documentsCreateFromTemplateTool(ctx, args = {}) {
2442
- const templateId = String(args.templateId || "").trim();
2443
- if (!templateId) {
2444
- throw new CliError("documents.create_from_template requires args.templateId");
2445
- }
2446
-
2447
4767
  assertPerformAction(args, {
2448
4768
  tool: "documents.create_from_template",
2449
4769
  action: "create and optionally update a document from template",
2450
4770
  });
2451
4771
 
4772
+ const resolvedTemplate = await resolveTemplateSelector(ctx, args, {
4773
+ outputField: "templateId",
4774
+ exactKeys: ["templateId"],
4775
+ });
4776
+ if (resolvedTemplate.error) {
4777
+ throw new CliError("documents.create_from_template could not resolve template", {
4778
+ resolution: resolvedTemplate.error,
4779
+ });
4780
+ }
4781
+ const templateId = String(resolvedTemplate.id || "").trim();
4782
+ if (!templateId) {
4783
+ throw new CliError("documents.create_from_template requires args.templateId or args.templateQuery");
4784
+ }
4785
+
2452
4786
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 1));
2453
4787
  const view = normalizeTemplatePipelineView(args.view);
2454
4788
  const strictPlaceholders = args.strictPlaceholders === true;
@@ -2482,6 +4816,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2482
4816
  strictPlaceholders,
2483
4817
  publishRequested,
2484
4818
  published: publishRequested,
4819
+ templateId,
4820
+ resolution: resolvedTemplate.resolution,
2485
4821
  document: normalizeTemplatePipelineDocument(finalPayload?.data || createdDoc, view),
2486
4822
  placeholders: {
2487
4823
  providedKeys: [],
@@ -2542,6 +4878,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2542
4878
  publishRequested,
2543
4879
  published: false,
2544
4880
  safeBehavior: "left_unpublished_draft",
4881
+ templateId,
4882
+ resolution: resolvedTemplate.resolution,
2545
4883
  document: normalizeTemplatePipelineDocument(updatedDoc, view),
2546
4884
  placeholders: {
2547
4885
  providedKeys: providedPlaceholderKeys,
@@ -2587,6 +4925,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2587
4925
  strictPlaceholders,
2588
4926
  publishRequested,
2589
4927
  published,
4928
+ templateId,
4929
+ resolution: resolvedTemplate.resolution,
2590
4930
  document: normalizeTemplatePipelineDocument(finalPayload?.data || updatedDoc, view),
2591
4931
  placeholders: {
2592
4932
  providedKeys: providedPlaceholderKeys,
@@ -2849,25 +5189,60 @@ async function listCollectionDocumentIds(ctx, collectionId, maxAttempts) {
2849
5189
  }
2850
5190
 
2851
5191
  async function commentsReviewQueueTool(ctx, args = {}) {
2852
- const explicitIds = uniqueStrings(ensureStringArray(args.documentIds, "documentIds") || []);
2853
- const collectionId = args.collectionId ? String(args.collectionId) : "";
5192
+ const resolvedDocuments = await resolveDocumentIdsForRead(ctx, args);
5193
+ const documentResolution = resolvedDocuments.resolution.resolved.length > 0 || resolvedDocuments.resolution.failed.length > 0
5194
+ ? resolvedDocuments.resolution
5195
+ : undefined;
5196
+ const resolvedCollection = await resolveCollectionIdForRead(ctx, args);
5197
+ const collectionResolution = resolvedCollection.resolution.resolved || resolvedCollection.resolution.failed
5198
+ ? resolvedCollection.resolution
5199
+ : undefined;
5200
+ const collectionId = resolvedCollection.id;
2854
5201
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
2855
5202
  const includeReplies = args.includeReplies !== false;
2856
5203
  const includeAnchorText = !!args.includeAnchorText;
2857
5204
  const limitPerDocument = Math.max(1, Math.min(200, toInteger(args.limitPerDocument, 30)));
2858
5205
  const view = args.view === "full" ? "full" : "summary";
2859
5206
 
2860
- if (explicitIds.length === 0 && !collectionId) {
2861
- throw new CliError("comments.review_queue requires args.documentIds[] or args.collectionId");
5207
+ const requestedDocumentRefs = documentResolution || resolvedDocuments.resolution.exactIds.length > 0;
5208
+ const requestedCollectionRef = !!args.collectionId || !!args.collectionQuery || !!args.collectionRefId
5209
+ || !!args.collectionUrlId || !!args.collectionUrl;
5210
+ if (!requestedDocumentRefs && !requestedCollectionRef) {
5211
+ throw new CliError("comments.review_queue requires args.documentIds[], document refs, args.collectionId, or collection refs");
2862
5212
  }
2863
5213
 
2864
- let documentIds = explicitIds;
5214
+ let documentIds = resolvedDocuments.ids;
2865
5215
  let collectionScopeTruncated = false;
2866
5216
  if (documentIds.length === 0 && collectionId) {
2867
5217
  const resolved = await listCollectionDocumentIds(ctx, collectionId, maxAttempts);
2868
5218
  documentIds = resolved.ids;
2869
5219
  collectionScopeTruncated = resolved.truncated;
2870
5220
  }
5221
+ if (documentIds.length === 0) {
5222
+ return {
5223
+ tool: "comments.review_queue",
5224
+ profile: ctx.profile.id,
5225
+ result: {
5226
+ ok: false,
5227
+ status: "not_found",
5228
+ scope: {
5229
+ documentIds: [],
5230
+ collectionId,
5231
+ ...(documentResolution ? { documentResolution } : {}),
5232
+ ...(collectionResolution ? { collectionResolution } : {}),
5233
+ },
5234
+ includeReplies,
5235
+ includeAnchorText,
5236
+ limitPerDocument,
5237
+ documentCount: 0,
5238
+ rowCount: 0,
5239
+ failedDocumentCount: 0,
5240
+ truncated: false,
5241
+ rows: [],
5242
+ failures: [],
5243
+ },
5244
+ };
5245
+ }
2871
5246
 
2872
5247
  const perDocument = await mapLimit(documentIds, Math.min(6, Math.max(1, documentIds.length || 1)), async (documentId) => {
2873
5248
  try {
@@ -2940,6 +5315,8 @@ async function commentsReviewQueueTool(ctx, args = {}) {
2940
5315
  scope: {
2941
5316
  documentIds,
2942
5317
  collectionId,
5318
+ ...(documentResolution ? { documentResolution } : {}),
5319
+ ...(collectionResolution ? { collectionResolution } : {}),
2943
5320
  },
2944
5321
  includeReplies,
2945
5322
  includeAnchorText,
@@ -3380,29 +5757,42 @@ async function federatedPermissionSnapshotTool(ctx, args = {}) {
3380
5757
  };
3381
5758
  }
3382
5759
 
5760
+ // Exported for unit testing the comment data-builder and mention-resolver
5761
+ // without hitting the network.
5762
+ export const __commentInternals = {
5763
+ COMMENT_TEXT_LIMIT,
5764
+ buildCommentData,
5765
+ commentTextLength,
5766
+ splitCommentParagraphs,
5767
+ firstNameToken,
5768
+ resolveMentionToken,
5769
+ usersFromListBody,
5770
+ };
5771
+
3383
5772
  export const EXTENDED_TOOLS = {
3384
5773
  ...RPC_TOOLS,
3385
5774
  "documents.answer": {
3386
5775
  signature:
3387
- "documents.answer(args: { question?: string; query?: string; limit?: number; ...endpointArgs; includePolicies?: boolean; maxAttempts?: number })",
5776
+ "documents.answer(args: { question?: string; query?: string; documentId?: string; documentQuery?: string; refs?: string[]; collectionId?: string; collectionQuery?: string; userId?: string; userQuery?: string; limit?: number; ...endpointArgs; includePolicies?: boolean; maxAttempts?: number })",
3388
5777
  description: "Answer a question using Outline AI over the selected document scope.",
3389
5778
  usageExample: {
3390
5779
  tool: "documents.answer",
3391
5780
  args: {
3392
5781
  question: "What changed in our onboarding checklist?",
3393
- collectionId: "collection-id",
5782
+ collectionQuery: "engineering",
3394
5783
  },
3395
5784
  },
3396
5785
  bestPractices: [
3397
5786
  "Use question text that is specific enough to resolve citations quickly.",
3398
- "Scope by collectionId or documentId to reduce latency and hallucination risk.",
5787
+ "Scope by documentQuery, refs, collectionQuery, or userQuery when callers have remembered titles, URLs, collection names, or emails instead of exact IDs.",
5788
+ "Use exact collectionId, documentId, or userId when already known to avoid a memory resolution step.",
3399
5789
  "If the deployment lacks documents.answerQuestion, this wrapper returns fallback retrieval evidence and a concrete search suggestion instead of a raw 404.",
3400
5790
  ],
3401
5791
  handler: documentsAnswerTool,
3402
5792
  },
3403
5793
  "documents.answer_batch": {
3404
5794
  signature:
3405
- "documents.answer_batch(args: { question?: string; questions?: Array<string | { question?: string; query?: string; ...endpointArgs }>; limit?: number; ...endpointArgs; concurrency?: number; includePolicies?: boolean; maxAttempts?: number })",
5795
+ "documents.answer_batch(args: { question?: string; questions?: Array<string | { question?: string; query?: string; documentQuery?: string; collectionQuery?: string; userQuery?: string; ...endpointArgs }>; limit?: number; ...endpointArgs; concurrency?: number; includePolicies?: boolean; maxAttempts?: number })",
3406
5796
  description: "Run multiple documents.answerQuestion calls with per-item isolation.",
3407
5797
  usageExample: {
3408
5798
  tool: "documents.answer_batch",
@@ -3411,12 +5801,13 @@ export const EXTENDED_TOOLS = {
3411
5801
  "Where is the release checklist?",
3412
5802
  "Who owns incident postmortems?",
3413
5803
  ],
3414
- collectionId: "collection-id",
5804
+ collectionQuery: "engineering",
3415
5805
  concurrency: 2,
3416
5806
  },
3417
5807
  },
3418
5808
  bestPractices: [
3419
5809
  "Prefer small batches and low concurrency for predictable token and latency budgets.",
5810
+ "Use top-level collectionQuery/userQuery to resolve shared scope once, or per-item documentQuery when each question targets a different remembered document.",
3420
5811
  "Use per-item statuses to retry only failures.",
3421
5812
  "Unsupported answer endpoints degrade to per-item retrieval evidence rather than failing the whole batch.",
3422
5813
  ],
@@ -3424,8 +5815,8 @@ export const EXTENDED_TOOLS = {
3424
5815
  },
3425
5816
  "documents.backlinks": {
3426
5817
  signature:
3427
- "documents.backlinks(args: { id: string; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; view?: 'ids'|'summary'|'full'; includePolicies?: boolean; maxAttempts?: number })",
3428
- description: "List backlinks for a document via documents.list(backlinkDocumentId=id).",
5818
+ "documents.backlinks(args: { id?: string; query?: string; shareId?: string; urlId?: string; url?: string; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; view?: 'ids'|'summary'|'full'; includePolicies?: boolean; maxAttempts?: number })",
5819
+ description: "List backlinks for a document by exact ID or by resolving a remembered title, share ID, URL id, or URL first.",
3429
5820
  usageExample: {
3430
5821
  tool: "documents.backlinks",
3431
5822
  args: {
@@ -3435,6 +5826,7 @@ export const EXTENDED_TOOLS = {
3435
5826
  },
3436
5827
  },
3437
5828
  bestPractices: [
5829
+ "Pass query/url/urlId directly when you know the document reference but not its exact ID.",
3438
5830
  "Use view=ids for low-token planning loops, then hydrate specific documents separately.",
3439
5831
  "Use limit/offset pagination for deterministic traversal over large backlink sets.",
3440
5832
  ],
@@ -3442,8 +5834,8 @@ export const EXTENDED_TOOLS = {
3442
5834
  },
3443
5835
  "documents.graph_neighbors": {
3444
5836
  signature:
3445
- "documents.graph_neighbors(args: { id?: string; ids?: string[]; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; searchQueries?: string[]; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3446
- description: "Collect one-hop graph neighbors and deterministic edge rows for source document IDs.",
5837
+ "documents.graph_neighbors(args: { id?: string; ids?: string[]; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; searchQueries?: string[]; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
5838
+ description: "Collect one-hop graph neighbors and deterministic edge rows for source documents, resolving titles or URLs when needed.",
3447
5839
  usageExample: {
3448
5840
  tool: "documents.graph_neighbors",
3449
5841
  args: {
@@ -3455,6 +5847,7 @@ export const EXTENDED_TOOLS = {
3455
5847
  },
3456
5848
  },
3457
5849
  bestPractices: [
5850
+ "Use refs[] for mixed document titles and URLs; use ids[] when exact document IDs are already known.",
3458
5851
  "Start with a single source id and small limitPerSource, then expand incrementally.",
3459
5852
  "Enable includeSearchNeighbors only when additional semantic neighborhood expansion is needed.",
3460
5853
  ],
@@ -3462,8 +5855,8 @@ export const EXTENDED_TOOLS = {
3462
5855
  },
3463
5856
  "documents.graph_report": {
3464
5857
  signature:
3465
- "documents.graph_report(args: { seedIds: string[]; depth?: number; maxNodes?: number; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3466
- description: "Build a bounded BFS graph report with stable nodes[] and edges[] output.",
5858
+ "documents.graph_report(args: { seedIds?: string[]; seedRefs?: string[]; seedQuery?: string; seedQueries?: string[]; seedUrl?: string; seedUrls?: string[]; depth?: number; maxNodes?: number; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
5859
+ description: "Build a bounded BFS graph report with stable nodes[] and edges[] output, resolving seed titles or URLs when needed.",
3467
5860
  usageExample: {
3468
5861
  tool: "documents.graph_report",
3469
5862
  args: {
@@ -3476,6 +5869,7 @@ export const EXTENDED_TOOLS = {
3476
5869
  },
3477
5870
  },
3478
5871
  bestPractices: [
5872
+ "Use seedRefs[] for mixed seed titles and URLs; use seedIds[] when exact document IDs are already known.",
3479
5873
  "Cap maxNodes and depth to keep traversal deterministic and cost-bounded.",
3480
5874
  "Prefer view=ids for graph planning and fetch full nodes only for selected IDs.",
3481
5875
  ],
@@ -3483,9 +5877,9 @@ export const EXTENDED_TOOLS = {
3483
5877
  },
3484
5878
  "documents.issue_refs": {
3485
5879
  signature:
3486
- "documents.issue_refs(args: { id?: string; ids?: string[]; issueDomains?: string[]; keyPattern?: string; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
5880
+ "documents.issue_refs(args: { id?: string; ids?: string[]; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; issueDomains?: string[]; keyPattern?: string; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3487
5881
  description:
3488
- "Extract deterministic issue references (URL links and key-pattern matches) from one or more documents.",
5882
+ "Extract deterministic issue references (URL links and key-pattern matches) from one or more documents, resolving titles or URLs when needed.",
3489
5883
  usageExample: {
3490
5884
  tool: "documents.issue_refs",
3491
5885
  args: {
@@ -3496,6 +5890,7 @@ export const EXTENDED_TOOLS = {
3496
5890
  },
3497
5891
  },
3498
5892
  bestPractices: [
5893
+ "Use refs[] for mixed document titles and URLs; exact IDs can still go through ids[].",
3499
5894
  "Start with view=ids for low-token audits, then re-run selected docs with summary/full views.",
3500
5895
  "Provide issueDomains to reduce non-issue URL noise and keep outputs focused.",
3501
5896
  "Tune keyPattern when your tracker uses custom issue key formats.",
@@ -3526,18 +5921,18 @@ export const EXTENDED_TOOLS = {
3526
5921
  },
3527
5922
  "documents.attachments": {
3528
5923
  signature:
3529
- "documents.attachments(args: { id?: string; documentId?: string; url?: string; shareId?: string; maxAttempts?: number })",
5924
+ "documents.attachments(args: { id?: string; documentId?: string; refs?: string[]; query?: string; queries?: string[]; url?: string; urlId?: string; urlIds?: string[]; urls?: string[]; shareId?: string; shareIds?: string[]; maxAttempts?: number })",
3530
5925
  description:
3531
- "Extract embedded Outline attachment references from a document body, including images rendered through /api/attachments.redirect.",
5926
+ "Extract embedded Outline attachment references from a document body, including images rendered through /api/attachments.redirect, resolving remembered document refs when needed.",
3532
5927
  usageExample: {
3533
5928
  tool: "documents.attachments",
3534
5929
  args: {
3535
- url: "https://handbook.example.com/doc/example-title-AbCdEf1234",
5930
+ query: "example title",
3536
5931
  },
3537
5932
  },
3538
5933
  bestPractices: [
3539
- "Use this after documents.info when you need to enumerate embedded images or file links without downloading bytes.",
3540
- "Pass a document URL directly; the tool resolves the Outline URL id suffix through documents.info.",
5934
+ "Pass query, refs, url, urlId, or shareId directly when you need to enumerate embedded images or file links without a separate document open step.",
5935
+ "Use strict=true defaults for remembered titles so weak fuzzy matches return a structured miss instead of guessing.",
3541
5936
  "Follow with attachments.download or documents.download_attachments to save files locally.",
3542
5937
  ],
3543
5938
  handler: documentsAttachmentsTool,
@@ -3564,19 +5959,20 @@ export const EXTENDED_TOOLS = {
3564
5959
  },
3565
5960
  "documents.download_attachments": {
3566
5961
  signature:
3567
- "documents.download_attachments(args: { id?: string; documentId?: string; url?: string; shareId?: string; outputDir?: string; overwrite?: boolean; concurrency?: number; maxAttempts?: number })",
5962
+ "documents.download_attachments(args: { id?: string; documentId?: string; refs?: string[]; query?: string; queries?: string[]; url?: string; urlId?: string; urlIds?: string[]; urls?: string[]; shareId?: string; shareIds?: string[]; outputDir?: string; overwrite?: boolean; concurrency?: number; maxAttempts?: number })",
3568
5963
  description:
3569
- "Extract all embedded Outline attachment references from a document and save each referenced file locally.",
5964
+ "Resolve a document, extract all embedded Outline attachment references, and save each referenced file locally.",
3570
5965
  usageExample: {
3571
5966
  tool: "documents.download_attachments",
3572
5967
  args: {
3573
- url: "https://handbook.example.com/doc/example-title-AbCdEf1234",
5968
+ query: "example title",
3574
5969
  outputDir: "./outline-attachments",
3575
5970
  overwrite: true,
3576
5971
  },
3577
5972
  },
3578
5973
  bestPractices: [
3579
5974
  "Run documents.attachments first when you only need metadata or want to choose a subset.",
5975
+ "Pass query, refs, url, urlId, or shareId directly when the agent has a remembered document title or pasted URL.",
3580
5976
  "Keep concurrency modest for large image-heavy documents to avoid rate limits.",
3581
5977
  "Use overwrite=true for repeatable automation into a scratch directory.",
3582
5978
  ],
@@ -3604,15 +6000,16 @@ export const EXTENDED_TOOLS = {
3604
6000
  handler: documentsImportFileTool,
3605
6001
  },
3606
6002
  "templates.extract_placeholders": {
3607
- signature: "templates.extract_placeholders(args: { id: string; maxAttempts?: number })",
3608
- description: "Extract sorted unique placeholder keys ({{key}}) from template text nodes.",
6003
+ signature: "templates.extract_placeholders(args: { id?: string; templateQuery?: string; refs?: string[]; refresh?: boolean; maxAttempts?: number })",
6004
+ description: "Resolve a template by ID or remembered name and extract sorted unique placeholder keys ({{key}}) from template text nodes.",
3609
6005
  usageExample: {
3610
6006
  tool: "templates.extract_placeholders",
3611
6007
  args: {
3612
- id: "template-id",
6008
+ templateQuery: "incident postmortem",
3613
6009
  },
3614
6010
  },
3615
6011
  bestPractices: [
6012
+ "Pass templateQuery/templateRef/refs when the user names a template but exact ID is unknown.",
3616
6013
  "Run this before document creation to validate required placeholder keys.",
3617
6014
  "Use counts to catch repeated placeholders for deterministic pipeline checks.",
3618
6015
  ],
@@ -3620,13 +6017,13 @@ export const EXTENDED_TOOLS = {
3620
6017
  },
3621
6018
  "documents.create_from_template": {
3622
6019
  signature:
3623
- "documents.create_from_template(args: { templateId: string; title?: string; collectionId?: string; parentDocumentId?: string; publish?: boolean; placeholderValues?: Record<string,string>; strictPlaceholders?: boolean; view?: 'summary'|'full'; includePolicies?: boolean; maxAttempts?: number; performAction?: boolean })",
6020
+ "documents.create_from_template(args: { templateId?: string; templateQuery?: string; refs?: string[]; title?: string; collectionId?: string; parentDocumentId?: string; publish?: boolean; placeholderValues?: Record<string,string>; strictPlaceholders?: boolean; view?: 'summary'|'full'; includePolicies?: boolean; maxAttempts?: number; performAction?: boolean })",
3624
6021
  description:
3625
6022
  "Create from template, optionally inject placeholder values, and enforce strict unresolved-placeholder safety.",
3626
6023
  usageExample: {
3627
6024
  tool: "documents.create_from_template",
3628
6025
  args: {
3629
- templateId: "template-id",
6026
+ templateQuery: "incident postmortem",
3630
6027
  title: "Service A - Incident Postmortem",
3631
6028
  placeholderValues: {
3632
6029
  service_name: "Service A",
@@ -3638,6 +6035,7 @@ export const EXTENDED_TOOLS = {
3638
6035
  },
3639
6036
  },
3640
6037
  bestPractices: [
6038
+ "Pass templateQuery/templateRef/refs when only the template name is known; local memory can resolve and refresh the template in the same call.",
3641
6039
  "Keep strictPlaceholders=true in automation to prevent publishing unresolved template tokens.",
3642
6040
  "Provide placeholderValues as exact key-value strings and inspect unresolvedCount on every run.",
3643
6041
  "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
@@ -3646,18 +6044,19 @@ export const EXTENDED_TOOLS = {
3646
6044
  },
3647
6045
  "comments.review_queue": {
3648
6046
  signature:
3649
- "comments.review_queue(args: { documentIds?: string[]; collectionId?: string; includeAnchorText?: boolean; includeReplies?: boolean; limitPerDocument?: number; view?: 'summary'|'full'; maxAttempts?: number })",
3650
- description: "Build a deterministic comment review queue from comments.list responses.",
6047
+ "comments.review_queue(args: { documentIds?: string[]; documentId?: string; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; collectionId?: string; collectionQuery?: string; collectionRefId?: string; collectionUrlId?: string; collectionUrl?: string; includeAnchorText?: boolean; includeReplies?: boolean; limitPerDocument?: number; view?: 'summary'|'full'; maxAttempts?: number })",
6048
+ description: "Build a deterministic comment review queue from comments.list responses, resolving remembered document or collection references when needed.",
3651
6049
  usageExample: {
3652
6050
  tool: "comments.review_queue",
3653
6051
  args: {
3654
- documentIds: ["doc-1", "doc-2"],
6052
+ refs: ["incident runbook", "https://handbook.example.com/doc/oncall-escalation-AbCdEf12"],
3655
6053
  includeReplies: true,
3656
6054
  limitPerDocument: 20,
3657
6055
  },
3658
6056
  },
3659
6057
  bestPractices: [
3660
- "Scope to explicit documentIds whenever possible for predictable queue size.",
6058
+ "Use explicit documentIds for maximum predictability, or pass refs/query/url when the agent only has a remembered title or pasted Outline URL.",
6059
+ "Use collectionQuery, collectionRefId, collectionUrlId, or collectionUrl when the review queue should cover a remembered collection without a separate collections.open turn.",
3661
6060
  "Use includeReplies=true to capture full threaded review context.",
3662
6061
  "Treat truncated=true as a signal to re-run with a higher limitPerDocument.",
3663
6062
  ],