@getnote/mcp 1.9.1 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -27
- package/dist/client.d.ts +67 -5
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +78 -4
- package/dist/discovery.d.ts +9 -1
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +34 -5
- package/dist/experience.d.ts +25 -0
- package/dist/experience.d.ts.map +1 -0
- package/dist/experience.js +46 -0
- package/dist/index.js +32 -6
- package/dist/read-retry.d.ts +11 -0
- package/dist/read-retry.d.ts.map +1 -0
- package/dist/read-retry.js +36 -0
- package/package.json +1 -1
- package/src/client.ts +91 -26
- package/src/discovery.ts +23 -6
- package/src/experience.ts +31 -0
- package/src/index.ts +32 -6
- package/src/read-retry.ts +27 -0
- package/test/error-metadata.test.mjs +47 -0
- package/test/experience.test.mjs +43 -0
- package/test/read-retry.test.mjs +38 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare function decimalID(value: string): string;
|
|
3
|
+
declare const batchSchema: z.ZodObject<{
|
|
4
|
+
ids: z.ZodArray<z.ZodString, "many">;
|
|
5
|
+
fields: z.ZodOptional<z.ZodArray<z.ZodEnum<["content", "ref_content", "reference", "original"]>, "many">>;
|
|
6
|
+
max_total_chars: z.ZodOptional<z.ZodNumber>;
|
|
7
|
+
}, "strict", z.ZodTypeAny, {
|
|
8
|
+
ids: string[];
|
|
9
|
+
fields?: ("content" | "ref_content" | "reference" | "original")[] | undefined;
|
|
10
|
+
max_total_chars?: number | undefined;
|
|
11
|
+
}, {
|
|
12
|
+
ids: string[];
|
|
13
|
+
fields?: ("content" | "ref_content" | "reference" | "original")[] | undefined;
|
|
14
|
+
max_total_chars?: number | undefined;
|
|
15
|
+
}>;
|
|
16
|
+
export type BatchDetailOptions = z.infer<typeof batchSchema>;
|
|
17
|
+
export declare function normalizeBatch(input: BatchDetailOptions): BatchDetailOptions;
|
|
18
|
+
export interface SearchOptions {
|
|
19
|
+
response_mode?: string;
|
|
20
|
+
max_snippet_chars?: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function validateSearchOptions(input: SearchOptions): void;
|
|
23
|
+
export declare function verifyExperience(body: unknown, path: string, request: unknown): void;
|
|
24
|
+
export {};
|
|
25
|
+
//# sourceMappingURL=experience.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"experience.d.ts","sourceRoot":"","sources":["../src/experience.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AAEtB,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAG/C;AACD,QAAA,MAAM,WAAW;;;;;;;;;;;;EAA+M,CAAC;AACjO,MAAM,MAAM,kBAAkB,GAAC,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC;AAC3D,wBAAgB,cAAc,CAAC,KAAK,EAAC,kBAAkB,GAAE,kBAAkB,CAI1E;AACD,MAAM,WAAW,aAAa;IAAE,aAAa,CAAC,EAAC,MAAM,CAAC;IAAA,iBAAiB,CAAC,EAAC,MAAM,CAAA;CAAC;AAChF,wBAAgB,qBAAqB,CAAC,KAAK,EAAC,aAAa,GAAE,IAAI,CAI9D;AACD,wBAAgB,gBAAgB,CAAC,IAAI,EAAC,OAAO,EAAC,IAAI,EAAC,MAAM,EAAC,OAAO,EAAC,OAAO,GAAE,IAAI,CAW9E"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.decimalID = decimalID;
|
|
4
|
+
exports.normalizeBatch = normalizeBatch;
|
|
5
|
+
exports.validateSearchOptions = validateSearchOptions;
|
|
6
|
+
exports.verifyExperience = verifyExperience;
|
|
7
|
+
const zod_1 = require("zod");
|
|
8
|
+
function decimalID(value) {
|
|
9
|
+
if (!/^\d+$/.test(value) || BigInt(value) <= 0n || BigInt(value) > 9223372036854775807n)
|
|
10
|
+
throw new Error("ID must be a positive signed-64-bit decimal string");
|
|
11
|
+
return BigInt(value).toString();
|
|
12
|
+
}
|
|
13
|
+
const batchSchema = zod_1.z.object({ ids: zod_1.z.array(zod_1.z.string()).min(1).max(200), fields: zod_1.z.array(zod_1.z.enum(["content", "ref_content", "reference", "original"])).optional(), max_total_chars: zod_1.z.number().int().min(1).max(64000).optional() }).strict();
|
|
14
|
+
function normalizeBatch(input) {
|
|
15
|
+
const out = batchSchema.parse(input);
|
|
16
|
+
out.ids = [...new Set(out.ids.map(decimalID))];
|
|
17
|
+
if (out.ids.length > 20)
|
|
18
|
+
throw new Error("batch supports at most20 unique IDs");
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
function validateSearchOptions(input) {
|
|
22
|
+
if (input.response_mode === undefined && input.max_snippet_chars === undefined)
|
|
23
|
+
return;
|
|
24
|
+
if (input.response_mode !== "snippet")
|
|
25
|
+
throw new Error("response_mode must be snippet when requesting snippets");
|
|
26
|
+
if (input.max_snippet_chars !== undefined && (!Number.isInteger(input.max_snippet_chars) || input.max_snippet_chars < 100 || input.max_snippet_chars > 1000))
|
|
27
|
+
throw new Error("max_snippet_chars must be 100..1000");
|
|
28
|
+
}
|
|
29
|
+
function verifyExperience(body, path, request) {
|
|
30
|
+
const input = request;
|
|
31
|
+
const cap = path === "/resource/note/batch-detail" ? "note.batch_detail.v1" : input?.response_mode === "snippet" ? "search.snippet.v1" : undefined;
|
|
32
|
+
if (!cap)
|
|
33
|
+
return;
|
|
34
|
+
const parsed = zod_1.z.object({ meta: zod_1.z.object({ capabilities: zod_1.z.array(zod_1.z.string()) }), data: zod_1.z.record(zod_1.z.unknown()) }).safeParse(body);
|
|
35
|
+
if (!parsed.success || !parsed.data.meta.capabilities.includes(cap))
|
|
36
|
+
throw new Error(`server does not support ${cap}; new mode was not accepted`);
|
|
37
|
+
const data = parsed.data.data;
|
|
38
|
+
if (cap === "note.batch_detail.v1") {
|
|
39
|
+
const items = zod_1.z.array(zod_1.z.object({ note_id: zod_1.z.string(), status: zod_1.z.string().min(1) })).parse(data.items);
|
|
40
|
+
if (items.length !== input?.ids?.length || items.some((item, i) => item.note_id !== input.ids?.[i]))
|
|
41
|
+
throw new Error("batch response lost identities or order");
|
|
42
|
+
}
|
|
43
|
+
else if (data.response_mode !== "snippet" || data.max_snippet_chars !== (input?.max_snippet_chars ?? 400))
|
|
44
|
+
throw new Error("server ignored snippet options");
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=experience.js.map
|
package/dist/index.js
CHANGED
|
@@ -134,9 +134,11 @@ function snowflakeID(value, field) {
|
|
|
134
134
|
const noteDiscoveryProperties = {
|
|
135
135
|
page: { type: "integer", minimum: 1, description: "知识库内可用页码;与 cursor 互斥" },
|
|
136
136
|
source: { type: "string", description: "来源平台精确筛选,如 dedao" },
|
|
137
|
-
note_type: { type: "string", description: "
|
|
137
|
+
note_type: { type: "string", description: "真实类型精确筛选:ref=引用划线,audio=即时/普通录音,local_audio=上传音频文件,class_audio=自己录制的课堂笔记,meeting=会议,internal_record=内录,recorder_audio/recorder_flash_audio=录音卡长录音/闪念。录音不默认限定dedao或课程。" },
|
|
138
138
|
reference_resource_type: { type: "string", description: "引用资源类型,如 ebook、course_article、audio_book" },
|
|
139
139
|
reference_resource_id: { type: "string", description: "引用资源 ID,必须字符串;同时传 source 和 reference_resource_type" },
|
|
140
|
+
reference_course_type: { type: "string", description: "课程容器类型,当前66;与reference_course_id配对,source=dedao,个人笔记,不与topic_id组合" },
|
|
141
|
+
reference_course_id: { type: "string", description: "真实课程容器ID字符串,来自list_reference_resources;不使用课节resource_id替代" },
|
|
140
142
|
reference_article_url: { type: "string", description: "文章 URL 精确筛选,保留 query 和 fragment" },
|
|
141
143
|
topic_id: { type: "string", description: "知识库 ID,限定授权范围" },
|
|
142
144
|
page_size: { type: "integer", minimum: 1, maximum: 100, description: "每页 1–100 条,默认 20" },
|
|
@@ -148,11 +150,25 @@ const knowledgeLookupProperties = {
|
|
|
148
150
|
book_id: { type: "string", description: "书籍 ID 字符串,限 BOOKSPACE" },
|
|
149
151
|
page_size: noteDiscoveryProperties.page_size,
|
|
150
152
|
};
|
|
153
|
+
const snippetProperties = {
|
|
154
|
+
response_mode: { type: "string", enum: ["snippet"], description: "显式摘要模式;不传保持旧正文。需search.snippet.v1,不支持课程内语义筛选" },
|
|
155
|
+
max_snippet_chars: { type: "integer", minimum: 100, maximum: 1000, description: "每个命中的Unicode码点上限,默认400;需response_mode=snippet,full只表示完整片段" },
|
|
156
|
+
};
|
|
151
157
|
const TOOLS = [
|
|
158
|
+
{
|
|
159
|
+
name: "list_reference_resources",
|
|
160
|
+
description: "按课程名/老师定位有个人笔记的得到课程,不需要知识库。query仅课程名exact/prefix,author精确,二者AND且至少一个;用返回course_type+course_id筛选list_notes。核对reference.resources.v1与applied_filters,空页has_more=true仍沿next_cursor继续。保留每页partial/warnings及候选metadata_state;course_directory_no_lessons表示目录缺课节,末页has_more=false仍不能宣称找全老师的全部课程。total未知,不冒充全站课程列表或课程内语义搜索。",
|
|
161
|
+
inputSchema: { type: "object", properties: { source: { type: "string", enum: ["dedao"] }, resource_type: { type: "string", enum: ["course"] }, query: { type: "string", description: "课程名,author可单独提供" }, author: { type: "string", description: "老师准确姓名,与query为AND" }, match_mode: { type: "string", enum: ["exact", "prefix"], description: "只控制课程名,默认exact" }, page_size: noteDiscoveryProperties.page_size, cursor: { type: "string", description: "原样保留的游标,继续时保持全部筛选" } }, required: ["source", "resource_type"], additionalProperties: false },
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
name: "get_notes",
|
|
165
|
+
description: "单次后端批量读取最多20个去重个人笔记ID,保持顺序。默认content/ref_content/reference,original需显式选择;引用原文ref_content,content是评论。默认32000/最多64000Unicode码点及1MiB。逐条保留ok/unavailable/failed/deferred_budget、content_state、pending_ids和partial,成功调用不代表每条读完;整条超预算按需改用旧get_note,不自动并发20次。不批量开放知识库共享权限。需note.batch_detail.v1。",
|
|
166
|
+
inputSchema: { type: "object", properties: { ids: { type: "array", items: { type: "string", description: "正int64十进制字符串,不能传JS Number" }, minItems: 1, maxItems: 200 }, fields: { type: "array", items: { type: "string", enum: ["content", "ref_content", "reference", "original"] } }, max_total_chars: { type: "integer", minimum: 1, maximum: 64000, description: "正文Unicode码点预算,默认32000;不会截断成功项" } }, required: ["ids"], additionalProperties: false },
|
|
167
|
+
},
|
|
152
168
|
// ── Notes ──
|
|
153
169
|
{
|
|
154
170
|
name: "list_notes",
|
|
155
|
-
description: "
|
|
171
|
+
description: "按来源、引用资源或知识库查找笔记。列表只返回定位信息;少量个人笔记正文按需用get_notes,知识库共享笔记保持get_note原权限路径。新查询核对meta.capabilities、applied_filters并按pagination.next_cursor翻页;partial/warnings未解决时末页也不代表来源完整。书库无匹配可按note_type=ref列定位信息,在真实reference中核对书籍作者/书名/book_id;保留时间、平台和知识库范围,平台未知不自加dedao,一次发现最多5页,未遍历完说明未查完。book_info.author与reference.author冲突须分别标注,候选不直接认定作者身份。total_count=null表示未知。",
|
|
156
172
|
inputSchema: {
|
|
157
173
|
type: "object",
|
|
158
174
|
properties: {
|
|
@@ -365,7 +381,7 @@ const TOOLS = [
|
|
|
365
381
|
// ── Knowledge / Topics ──
|
|
366
382
|
{
|
|
367
383
|
name: "list_topics",
|
|
368
|
-
description: "
|
|
384
|
+
description: "获取用户创建、拥有或加入的知识库列表,默认DEFAULT;查书名/书籍作者显式scope=BOOKSPACE,query只匹配书名、author匹配书籍作者,二者AND,只有作者线索就只传author。返回topics[]、has_more、total,完整分页并核对book_info。无匹配且用户未限定只查自有时,用list_subscribe_topics保留全部条件补查;仍无匹配再按list_notes的引用来源路线补查,不能把空书库当账号没有划线。用户限定具体知识库时保留原范围;来源作者冲突保留为待核验候选。",
|
|
369
385
|
inputSchema: {
|
|
370
386
|
type: "object",
|
|
371
387
|
properties: {
|
|
@@ -726,7 +742,7 @@ const TOOLS = [
|
|
|
726
742
|
// ── Knowledge / Subscribe ──
|
|
727
743
|
{
|
|
728
744
|
name: "list_subscribe_topics",
|
|
729
|
-
description: "
|
|
745
|
+
description: "获取当前用户真实订阅的他人知识库,不含自己创建的库。默认DEFAULT;书籍显式BOOKSPACE,保留query/author/book_id及分页。自有书库无匹配时可补查这里;仍无匹配且用户未限定只查订阅库时,按list_notes的个人引用来源路线核对候选,保留已知平台/时间,不能把空库当没有笔记。返回topics[]、has_more、total。",
|
|
730
746
|
inputSchema: {
|
|
731
747
|
type: "object",
|
|
732
748
|
properties: {
|
|
@@ -762,6 +778,7 @@ const TOOLS = [
|
|
|
762
778
|
inputSchema: {
|
|
763
779
|
type: "object",
|
|
764
780
|
properties: {
|
|
781
|
+
...snippetProperties,
|
|
765
782
|
query: {
|
|
766
783
|
type: "string",
|
|
767
784
|
description: "搜索关键词或语义描述(必填)",
|
|
@@ -781,6 +798,7 @@ const TOOLS = [
|
|
|
781
798
|
inputSchema: {
|
|
782
799
|
type: "object",
|
|
783
800
|
properties: {
|
|
801
|
+
...snippetProperties,
|
|
784
802
|
topic_id: {
|
|
785
803
|
type: "string",
|
|
786
804
|
description: "知识库 ID(来自 list_topics 的 topic_id 字段)(必填)",
|
|
@@ -801,6 +819,8 @@ const TOOLS = [
|
|
|
801
819
|
];
|
|
802
820
|
async function handleTool(name, input, client) {
|
|
803
821
|
switch (name) {
|
|
822
|
+
case "list_reference_resources": return client.listReferenceResources(input);
|
|
823
|
+
case "get_notes": return client.getNotes(input);
|
|
804
824
|
// ── Notes ──
|
|
805
825
|
case "list_notes": {
|
|
806
826
|
const cursor = input.cursor;
|
|
@@ -1073,12 +1093,16 @@ async function handleTool(name, input, client) {
|
|
|
1073
1093
|
// ── Recall / Search ──
|
|
1074
1094
|
case "recall": {
|
|
1075
1095
|
return client.recall({
|
|
1096
|
+
response_mode: input.response_mode,
|
|
1097
|
+
max_snippet_chars: input.max_snippet_chars,
|
|
1076
1098
|
query: input.query,
|
|
1077
1099
|
top_k: input.top_k,
|
|
1078
1100
|
});
|
|
1079
1101
|
}
|
|
1080
1102
|
case "recall_knowledge": {
|
|
1081
1103
|
return client.recallKnowledge({
|
|
1104
|
+
response_mode: input.response_mode,
|
|
1105
|
+
max_snippet_chars: input.max_snippet_chars,
|
|
1082
1106
|
topic_id: input.topic_id,
|
|
1083
1107
|
query: input.query,
|
|
1084
1108
|
top_k: input.top_k,
|
|
@@ -1106,11 +1130,11 @@ async function main() {
|
|
|
1106
1130
|
tools: TOOLS,
|
|
1107
1131
|
}));
|
|
1108
1132
|
// Call tool
|
|
1109
|
-
server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
|
|
1133
|
+
server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
|
|
1110
1134
|
const { name, arguments: args } = request.params;
|
|
1111
1135
|
const input = (args ?? {});
|
|
1112
1136
|
try {
|
|
1113
|
-
const result = await handleTool(name, input, client);
|
|
1137
|
+
const result = await handleTool(name, input, client.withSignal(extra.signal));
|
|
1114
1138
|
return {
|
|
1115
1139
|
content: [
|
|
1116
1140
|
{
|
|
@@ -1132,6 +1156,8 @@ async function main() {
|
|
|
1132
1156
|
field: err.field,
|
|
1133
1157
|
constraint: err.constraint,
|
|
1134
1158
|
expected_type: err.expectedType,
|
|
1159
|
+
supported_values: err.supportedValues,
|
|
1160
|
+
retry_after_seconds: err.retryAfterSeconds,
|
|
1135
1161
|
};
|
|
1136
1162
|
if (err.code === 10201) {
|
|
1137
1163
|
errPayload.membership_url = membership_js_1.OPENAPI_MEMBERSHIP_PURCHASE_URL;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface ReadFailure {
|
|
2
|
+
httpStatus?: number;
|
|
3
|
+
code: number;
|
|
4
|
+
reason: string;
|
|
5
|
+
retryable: boolean;
|
|
6
|
+
retryAfterSeconds?: number;
|
|
7
|
+
waitProvided?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare function readRetryDelay(method: string, path: string, error: ReadFailure, attempt: number, waited: number): number | undefined;
|
|
10
|
+
export declare function waitForReadRetry(delay: number, signal?: AbortSignal): Promise<void>;
|
|
11
|
+
//# sourceMappingURL=read-retry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read-retry.d.ts","sourceRoot":"","sources":["../src/read-retry.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAAE,UAAU,CAAC,EAAC,MAAM,CAAC;IAAA,IAAI,EAAC,MAAM,CAAC;IAAA,MAAM,EAAC,MAAM,CAAC;IAAA,SAAS,EAAC,OAAO,CAAC;IAAA,iBAAiB,CAAC,EAAC,MAAM,CAAC;IAAA,YAAY,CAAC,EAAC,OAAO,CAAA;CAAC;AAQ7I,wBAAgB,cAAc,CAAC,MAAM,EAAC,MAAM,EAAC,IAAI,EAAC,MAAM,EAAC,KAAK,EAAC,WAAW,EAAC,OAAO,EAAC,MAAM,EAAC,MAAM,EAAC,MAAM,GAAE,MAAM,GAAC,SAAS,CAUxH;AACD,wBAAsB,gBAAgB,CAAC,KAAK,EAAC,MAAM,EAAC,MAAM,CAAC,EAAC,WAAW,GAAE,OAAO,CAAC,IAAI,CAAC,CAOrF"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readRetryDelay = readRetryDelay;
|
|
4
|
+
exports.waitForReadRetry = waitForReadRetry;
|
|
5
|
+
const getPaths = new Set([
|
|
6
|
+
"/resource/note/list", "/resource/note/detail", "/resource/note/marks", "/resource/note/sprouts", "/resource/note/sprout",
|
|
7
|
+
"/resource/reference/list", "/resource/knowledge/list", "/resource/knowledge/subscribe/list", "/resource/knowledge/notes", "/resource/knowledge/directories",
|
|
8
|
+
"/resource/knowledge/file/capabilities", "/resource/knowledge/bloggers", "/resource/knowledge/blogger/contents", "/resource/knowledge/blogger/content/detail",
|
|
9
|
+
"/resource/knowledge/lives", "/resource/knowledge/live/detail", "/resource/rate-limit/quota"
|
|
10
|
+
]);
|
|
11
|
+
const postPaths = new Set(["/resource/recall", "/resource/recall/knowledge", "/resource/note/batch-detail"]);
|
|
12
|
+
function readRetryDelay(method, path, error, attempt, waited) {
|
|
13
|
+
if (attempt >= 2 || waited >= 5000 || error.httpStatus !== 429 || !error.retryable)
|
|
14
|
+
return;
|
|
15
|
+
const qpsLimit = error.code === 10202 && ["qps_exceeded", "qps_global_exceeded", "qps_bucket_exceeded"].includes(error.reason);
|
|
16
|
+
if (!qpsLimit && !(error.code === 10005 && error.reason === "rate_limited"))
|
|
17
|
+
return;
|
|
18
|
+
if (!(method === "GET" ? getPaths.has(path) : method === "POST" && postPaths.has(path)))
|
|
19
|
+
return;
|
|
20
|
+
if (error.waitProvided && error.retryAfterSeconds === undefined)
|
|
21
|
+
return;
|
|
22
|
+
const wait = error.retryAfterSeconds;
|
|
23
|
+
if (wait !== undefined && (!Number.isSafeInteger(wait) || wait < 0 || wait > (5000 - waited) / 1000))
|
|
24
|
+
return;
|
|
25
|
+
const delay = (wait === undefined ? 200 * 2 ** attempt : wait * 1000) + 1 + Math.floor(Math.random() * 50);
|
|
26
|
+
return delay <= 5000 - waited ? delay : undefined;
|
|
27
|
+
}
|
|
28
|
+
async function waitForReadRetry(delay, signal) {
|
|
29
|
+
signal?.throwIfAborted();
|
|
30
|
+
await new Promise((resolve, reject) => {
|
|
31
|
+
const abort = () => { clearTimeout(timer); signal?.removeEventListener("abort", abort); reject(signal?.reason ?? new Error("cancelled")); };
|
|
32
|
+
const timer = setTimeout(() => { signal?.removeEventListener("abort", abort); resolve(); }, delay);
|
|
33
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=read-retry.js.map
|
package/package.json
CHANGED
package/src/client.ts
CHANGED
|
@@ -1,8 +1,26 @@
|
|
|
1
1
|
import axios, { AxiosInstance, AxiosError } from "axios";
|
|
2
2
|
import { discoveryContract, verifyDiscovery, NoteDiscoveryOptions, LookupOptions, DiscoveryKind } from "./discovery";
|
|
3
|
+
import {BatchDetailOptions,SearchOptions,normalizeBatch,validateSearchOptions,verifyExperience} from "./experience";
|
|
4
|
+
import {readRetryDelay,waitForReadRetry} from "./read-retry";
|
|
3
5
|
|
|
4
6
|
const DEFAULT_BASE_URL = "https://openapi.biji.com/open/api/v1";
|
|
5
7
|
|
|
8
|
+
function retryAfterSeconds(body: unknown, header: unknown): number | undefined {
|
|
9
|
+
let wait = typeof body === "number" && Number.isSafeInteger(body) && body >= 0 ? body : undefined;
|
|
10
|
+
if (typeof header !== "string" || !header.trim()) return wait;
|
|
11
|
+
const value = header.trim();
|
|
12
|
+
let seconds: number | undefined;
|
|
13
|
+
if (/^\d+$/.test(value)) {
|
|
14
|
+
const parsed = Number(value);
|
|
15
|
+
if (Number.isSafeInteger(parsed)) seconds = parsed;
|
|
16
|
+
} else if (/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)) {
|
|
17
|
+
const date = Date.parse(value);
|
|
18
|
+
if (Number.isFinite(date)) seconds = Math.max(0, Math.ceil((date - Date.now()) / 1000));
|
|
19
|
+
}
|
|
20
|
+
if (seconds !== undefined) wait = Math.max(wait ?? 0, seconds);
|
|
21
|
+
return wait;
|
|
22
|
+
}
|
|
23
|
+
|
|
6
24
|
function normalizeBaseURL(value?: string): string {
|
|
7
25
|
const base = (value || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
8
26
|
if (base.endsWith("/open/api/v1")) return base;
|
|
@@ -32,6 +50,8 @@ export function parseJsonPreservingLargeIntegerStrings(data: unknown) {
|
|
|
32
50
|
}
|
|
33
51
|
|
|
34
52
|
export class GetNoteAPIError extends Error {
|
|
53
|
+
httpStatus?:number;
|
|
54
|
+
waitProvided=false;
|
|
35
55
|
constructor(
|
|
36
56
|
public readonly code: number,
|
|
37
57
|
public readonly reason: string,
|
|
@@ -40,13 +60,19 @@ export class GetNoteAPIError extends Error {
|
|
|
40
60
|
public readonly retryable: boolean = false,
|
|
41
61
|
public readonly field?: string,
|
|
42
62
|
public readonly constraint?: string,
|
|
43
|
-
public readonly expectedType?: string
|
|
63
|
+
public readonly expectedType?: string,
|
|
64
|
+
public readonly supportedValues?: string[],
|
|
65
|
+
public readonly retryAfterSeconds?: number
|
|
44
66
|
) {
|
|
45
67
|
super(message);
|
|
46
68
|
this.name = "GetNoteAPIError";
|
|
47
69
|
}
|
|
48
70
|
}
|
|
49
71
|
|
|
72
|
+
function apiFailure(err:APIErrorBody|undefined,requestID:string|undefined,status:number,header:unknown):GetNoteAPIError {
|
|
73
|
+
return Object.assign(new GetNoteAPIError(err?.code??-1,err?.reason??"unknown",err?.message??"API request failed",requestID,err?.retryable??false,err?.field,err?.constraint,err?.expected_type,err?.supported_values,retryAfterSeconds(err?.retry_after_seconds,header)),{httpStatus:status,waitProvided:err?.retry_after_seconds!==undefined||header!==undefined});
|
|
74
|
+
}
|
|
75
|
+
|
|
50
76
|
export class GetNoteClient {
|
|
51
77
|
async getNoteMarks(note_id: string) {
|
|
52
78
|
return this.request<unknown>("GET", "/resource/note/marks", { note_id });
|
|
@@ -67,6 +93,12 @@ export class GetNoteClient {
|
|
|
67
93
|
return this.request<unknown>("POST", "/resource/knowledge/file/upload", undefined, data);
|
|
68
94
|
}
|
|
69
95
|
private http: AxiosInstance;
|
|
96
|
+
private requestSignal?:AbortSignal;
|
|
97
|
+
|
|
98
|
+
withSignal(signal:AbortSignal):GetNoteClient {
|
|
99
|
+
// Per-call view shares the HTTP transport, never another call's signal.
|
|
100
|
+
return Object.assign(Object.create(Object.getPrototypeOf(this)),this,{requestSignal:signal});
|
|
101
|
+
}
|
|
70
102
|
|
|
71
103
|
constructor(apiKey: string, clientId: string, baseURL?: string) {
|
|
72
104
|
this.http = axios.create({
|
|
@@ -89,12 +121,32 @@ export class GetNoteClient {
|
|
|
89
121
|
}
|
|
90
122
|
|
|
91
123
|
private async request<T>(
|
|
124
|
+
method:"GET"|"POST",path:string,params?:Record<string,unknown>,data?:unknown
|
|
125
|
+
):Promise<T>{
|
|
126
|
+
let waited=0;let lastError:GetNoteAPIError|undefined;
|
|
127
|
+
for(let attempt=0;;attempt++){
|
|
128
|
+
try {
|
|
129
|
+
this.requestSignal?.throwIfAborted();
|
|
130
|
+
return await this.requestOnce<T>(method,path,params,data);
|
|
131
|
+
}catch(err){
|
|
132
|
+
if(this.requestSignal?.aborted&&lastError)throw Object.assign(lastError,{cause:this.requestSignal.reason});
|
|
133
|
+
if(!(err instanceof GetNoteAPIError))throw err;
|
|
134
|
+
const delay=readRetryDelay(method,path,err,attempt,waited);
|
|
135
|
+
if(delay===undefined)throw err;
|
|
136
|
+
lastError=err;const start=performance.now();
|
|
137
|
+
try {await waitForReadRetry(delay,this.requestSignal)}catch(cause){throw Object.assign(err,{cause})}
|
|
138
|
+
waited+=performance.now()-start;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private async requestOnce<T>(
|
|
92
144
|
method: "GET" | "POST",
|
|
93
145
|
path: string,
|
|
94
146
|
params?: Record<string, unknown>,
|
|
95
147
|
data?: unknown
|
|
96
148
|
): Promise<T> {
|
|
97
|
-
const kinds: Record<string, DiscoveryKind> = { "/resource/note/list": "notes", "/resource/note/detail": "detail", "/resource/knowledge/notes": "topicNotes", "/resource/knowledge/list": "topics", "/resource/knowledge/subscribe/list": "topics" };
|
|
149
|
+
const kinds: Record<string, DiscoveryKind> = { "/resource/note/list": "notes", "/resource/note/detail": "detail", "/resource/knowledge/notes": "topicNotes", "/resource/knowledge/list": "topics", "/resource/knowledge/subscribe/list": "topics", "/resource/reference/list":"references" };
|
|
98
150
|
const contract = method === "GET" && kinds[path] ? discoveryContract(kinds[path], params || {}) : undefined;
|
|
99
151
|
if (contract) params = contract.params;
|
|
100
152
|
try {
|
|
@@ -109,24 +161,17 @@ export class GetNoteClient {
|
|
|
109
161
|
url: path,
|
|
110
162
|
params,
|
|
111
163
|
data,
|
|
164
|
+
signal:this.requestSignal,
|
|
112
165
|
});
|
|
113
166
|
|
|
114
167
|
const body = res.data;
|
|
115
168
|
if (!body.success) {
|
|
116
169
|
const err = body.error;
|
|
117
|
-
throw
|
|
118
|
-
err?.code ?? -1,
|
|
119
|
-
err?.reason ?? "unknown",
|
|
120
|
-
err?.message ?? "API request failed",
|
|
121
|
-
body.request_id,
|
|
122
|
-
err?.retryable ?? false,
|
|
123
|
-
err?.field,
|
|
124
|
-
err?.constraint,
|
|
125
|
-
err?.expected_type
|
|
126
|
-
);
|
|
170
|
+
throw apiFailure(err,body.request_id,res.status,res.headers["retry-after"]);
|
|
127
171
|
}
|
|
128
172
|
|
|
129
173
|
if (contract) verifyDiscovery(body, contract);
|
|
174
|
+
verifyExperience(body,path,data);
|
|
130
175
|
// Keep the verified envelope capabilities visible to the Agent.
|
|
131
176
|
if (body.meta?.capabilities && typeof body.data === "object" && body.data !== null && !Array.isArray(body.data)) {
|
|
132
177
|
return { ...body.data, meta: body.meta };
|
|
@@ -142,16 +187,7 @@ export class GetNoteClient {
|
|
|
142
187
|
request_id?: string;
|
|
143
188
|
};
|
|
144
189
|
if (body?.error) {
|
|
145
|
-
throw
|
|
146
|
-
body.error.code,
|
|
147
|
-
body.error.reason,
|
|
148
|
-
body.error.message,
|
|
149
|
-
body.request_id,
|
|
150
|
-
body.error.retryable ?? false,
|
|
151
|
-
body.error.field,
|
|
152
|
-
body.error.constraint,
|
|
153
|
-
body.error.expected_type
|
|
154
|
-
);
|
|
190
|
+
throw apiFailure(body.error,body.request_id,err.response.status,err.response.headers["retry-after"]);
|
|
155
191
|
}
|
|
156
192
|
throw new Error(`HTTP ${err.response.status}: ${err.message}`);
|
|
157
193
|
}
|
|
@@ -166,6 +202,14 @@ export class GetNoteClient {
|
|
|
166
202
|
return this.request<ListNotesResp>("GET", "/resource/note/list", { ...params });
|
|
167
203
|
}
|
|
168
204
|
|
|
205
|
+
async listReferenceResources(params:{source:string;resource_type:string;query?:string;author?:string;match_mode?:string;page_size?:number;cursor?:string}){
|
|
206
|
+
return this.request<ReferenceResourcesResp>("GET","/resource/reference/list",params);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async getNotes(body:BatchDetailOptions){
|
|
210
|
+
return this.request<BatchDetailResp>("POST","/resource/note/batch-detail",undefined,normalizeBatch(body));
|
|
211
|
+
}
|
|
212
|
+
|
|
169
213
|
async getNote(id: string | number, image_quality?: string) {
|
|
170
214
|
return this.request<GetNoteResp>("GET", "/resource/note/detail", { id, image_quality });
|
|
171
215
|
}
|
|
@@ -445,11 +489,13 @@ export class GetNoteClient {
|
|
|
445
489
|
|
|
446
490
|
// ─── Recall / Search ─────────────────────────────────────────────────────
|
|
447
491
|
|
|
448
|
-
async recall(body: { query: string; top_k?: number }) {
|
|
492
|
+
async recall(body: { query: string; top_k?: number }&SearchOptions) {
|
|
493
|
+
validateSearchOptions(body);
|
|
449
494
|
return this.request<RecallResp>("POST", "/resource/recall", undefined, body);
|
|
450
495
|
}
|
|
451
496
|
|
|
452
|
-
async recallKnowledge(body: { topic_id: string; query: string; top_k?: number }) {
|
|
497
|
+
async recallKnowledge(body: { topic_id: string; query: string; top_k?: number }&SearchOptions) {
|
|
498
|
+
validateSearchOptions(body);
|
|
453
499
|
return this.request<RecallResp>("POST", "/resource/recall/knowledge", undefined, body);
|
|
454
500
|
}
|
|
455
501
|
}
|
|
@@ -463,6 +509,7 @@ export interface TagInfo {
|
|
|
463
509
|
}
|
|
464
510
|
|
|
465
511
|
export interface NoteReference {
|
|
512
|
+
course?:{type:string;id:string;title?:string;author?:string;[key:string]:unknown};
|
|
466
513
|
source: string; resource_type: string; ptype: number; resource_id?: string;
|
|
467
514
|
title?: string; author?: string; url?: string; original_note_id?: string;
|
|
468
515
|
is_source_private: boolean; book_id?: string;
|
|
@@ -479,6 +526,7 @@ export interface DiscoveryMetadata {
|
|
|
479
526
|
metadata_state?: { reference: string; topics: string };
|
|
480
527
|
}
|
|
481
528
|
export interface DiscoveryResponse {
|
|
529
|
+
total_scope?:string;
|
|
482
530
|
meta?: { capabilities: string[]; timestamp?: number };
|
|
483
531
|
pagination?: { mode: "page" | "cursor"; page: number | null; page_size: number; returned_count: number; total_count: number | null; has_more: boolean; next_page: number | null; next_cursor: string | null };
|
|
484
532
|
applied_filters?: Record<string, unknown>;
|
|
@@ -887,6 +935,8 @@ interface APIErrorBody {
|
|
|
887
935
|
field?: string;
|
|
888
936
|
constraint?: string;
|
|
889
937
|
expected_type?: string;
|
|
938
|
+
supported_values?: string[];
|
|
939
|
+
retry_after_seconds?: number;
|
|
890
940
|
}
|
|
891
941
|
|
|
892
942
|
export interface UpdateNoteResp {
|
|
@@ -900,9 +950,9 @@ export interface UpdateNoteResp {
|
|
|
900
950
|
export interface RecallResultItem {
|
|
901
951
|
note_id?: string;
|
|
902
952
|
resource_id?: string;
|
|
903
|
-
note_type:
|
|
953
|
+
note_type: string;
|
|
904
954
|
title: string;
|
|
905
|
-
content
|
|
955
|
+
content?: string;
|
|
906
956
|
created_at: string;
|
|
907
957
|
page_no?: number;
|
|
908
958
|
resource_type?: string;
|
|
@@ -911,9 +961,14 @@ export interface RecallResultItem {
|
|
|
911
961
|
snippet?: string;
|
|
912
962
|
snippet_source?: string;
|
|
913
963
|
score?: number | null;
|
|
964
|
+
truncated?:boolean;
|
|
965
|
+
content_state?:{content:string;snippet:string};
|
|
914
966
|
}
|
|
915
967
|
|
|
916
968
|
export interface RecallResp extends DiscoveryResponse {
|
|
969
|
+
response_mode?:string;
|
|
970
|
+
max_snippet_chars?:number;
|
|
971
|
+
max_total_bytes?:number;
|
|
917
972
|
results: RecallResultItem[];
|
|
918
973
|
result_mode?: string;
|
|
919
974
|
is_exhaustive?: boolean;
|
|
@@ -921,3 +976,13 @@ export interface RecallResp extends DiscoveryResponse {
|
|
|
921
976
|
distinct_note_count?: number;
|
|
922
977
|
partial?: boolean;
|
|
923
978
|
}
|
|
979
|
+
|
|
980
|
+
export interface ReferenceResourcesResp extends DiscoveryResponse {
|
|
981
|
+
resources:Array<{source:string;resource_type:string;course_type:string;course_id:string;title:string;author:string;url:string;has_notes:boolean;metadata_state:string;[key:string]:unknown}>;
|
|
982
|
+
partial:boolean;
|
|
983
|
+
}
|
|
984
|
+
export interface BatchDetailResp extends DiscoveryResponse {
|
|
985
|
+
items:Array<{note_id:string;status:string;note?:Record<string,unknown>;[key:string]:unknown}>;
|
|
986
|
+
pending_ids:string[];
|
|
987
|
+
total_chars:number;max_total_chars:number;max_total_bytes:number;partial:boolean;
|
|
988
|
+
}
|
package/src/discovery.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import {decimalID} from "./experience";
|
|
2
3
|
|
|
3
4
|
const text = z.string().trim().min(1);
|
|
4
5
|
const integer = z.number().int().positive();
|
|
@@ -6,6 +7,7 @@ const times = ["created_from", "created_to", "edited_from", "edited_to", "record
|
|
|
6
7
|
export const noteSelectors = {
|
|
7
8
|
source: text.optional(), note_type: text.optional(),
|
|
8
9
|
reference_resource_type: text.optional(), reference_resource_id: text.optional(),
|
|
10
|
+
reference_course_type: text.optional(), reference_course_id: text.optional(),
|
|
9
11
|
reference_article_url: z.string().url().refine(v => /^https?:\/\//.test(v)).optional(),
|
|
10
12
|
topic_id: text.optional(), page_size: integer.max(100).optional(),
|
|
11
13
|
created_from: text.optional(), created_to: text.optional(), edited_from: text.optional(), edited_to: text.optional(),
|
|
@@ -15,7 +17,7 @@ export type NoteDiscoveryOptions = z.infer<ReturnType<typeof noteSchema>>;
|
|
|
15
17
|
function noteSchema() { return z.object({ ...noteSelectors, page: integer.optional(), cursor: z.string().min(1).optional() }).strict(); }
|
|
16
18
|
const lookupSchema = z.object({ page: integer.optional(), scope: z.enum(["DEFAULT", "CUSTOMER", "BOOKSPACE", "TEAMSPACE"]).optional(), query: text.optional(), author: text.optional(), book_id: text.optional(), page_size: integer.max(100).optional() }).strict();
|
|
17
19
|
export type LookupOptions = z.infer<typeof lookupSchema>;
|
|
18
|
-
export type DiscoveryKind = "notes" | "topicNotes" | "topics" | "detail";
|
|
20
|
+
export type DiscoveryKind = "notes" | "topicNotes" | "topics" | "detail" | "references";
|
|
19
21
|
export type DiscoveryContract = { params: Record<string, unknown>; filters: Record<string, string>; capabilities: string[]; kind: DiscoveryKind };
|
|
20
22
|
|
|
21
23
|
export function normalizeLookup(value: string): string {
|
|
@@ -40,14 +42,18 @@ function timestamp(value: string): { text: string; epoch: bigint } {
|
|
|
40
42
|
export function discoveryContract(kind: DiscoveryKind, input: Record<string, unknown>): DiscoveryContract | undefined {
|
|
41
43
|
const values = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== undefined));
|
|
42
44
|
const legacy = kind === "topics" ? ["page", "scope"] : kind === "detail" ? ["id", "image_quality"] : kind === "topicNotes" ? ["topic_id", "page"] : ["cursor"];
|
|
43
|
-
if (
|
|
45
|
+
if (kind!=="references"&&!Object.keys(values).some(k => !legacy.includes(k))) return undefined;
|
|
44
46
|
let params: Record<string, unknown>;
|
|
45
47
|
const filters: Record<string, string> = {};
|
|
46
48
|
if (kind === "detail") {
|
|
47
49
|
params = z.object({ id: z.union([text, z.number().int().safe()]), image_quality: z.enum(["original"]).optional() }).strict().parse(values);
|
|
48
50
|
return { params, filters, capabilities: ["note.reference.v1"], kind };
|
|
49
51
|
}
|
|
50
|
-
if (kind === "
|
|
52
|
+
if (kind === "references") {
|
|
53
|
+
params=z.object({source:z.literal("dedao"),resource_type:z.literal("course"),query:text.optional(),author:text.optional(),match_mode:z.enum(["exact","prefix"]).default("exact"),page_size:integer.max(100).default(20),cursor:text.max(4096).optional()}).strict().parse(values);
|
|
54
|
+
if(!params.query&&!params.author)throw new Error("course lookup requires query or author");
|
|
55
|
+
for(const key of ["query","author"])if(typeof params[key]==="string"&&Array.from(params[key] as string).length>200)throw new Error("course lookup exceeds input budget");
|
|
56
|
+
} else if (kind === "topics") {
|
|
51
57
|
params = { scope: "DEFAULT", page: 1, page_size: 20, ...lookupSchema.parse(values) };
|
|
52
58
|
if (params.scope !== "BOOKSPACE" && (params.author || params.book_id)) throw new Error("author and book_id require BOOKSPACE");
|
|
53
59
|
for (const key of ["query", "author"]) if (typeof params[key] === "string") params[key] = normalizeLookup(params[key] as string);
|
|
@@ -55,6 +61,10 @@ export function discoveryContract(kind: DiscoveryKind, input: Record<string, unk
|
|
|
55
61
|
params = { page_size: 20, ...(kind === "topicNotes" ? { page: 1 } : {}), ...noteSchema().parse(values) };
|
|
56
62
|
if (kind === "topicNotes" && !params.topic_id) throw new Error("topic_id is required");
|
|
57
63
|
if (params.page && (!params.topic_id || params.cursor)) throw new Error("page requires topic_id and cannot be combined with cursor");
|
|
64
|
+
if(params.reference_course_type||params.reference_course_id){
|
|
65
|
+
if(params.reference_course_type!=="66"||!params.reference_course_id||params.source!=="dedao"||params.topic_id)throw new Error("course requires source=dedao, paired type66 and ID; topic intersection unsupported");
|
|
66
|
+
params.reference_course_id=decimalID(String(params.reference_course_id));
|
|
67
|
+
}
|
|
58
68
|
if (params.reference_resource_id) {
|
|
59
69
|
if (!params.source || !params.reference_resource_type) throw new Error("reference ID requires source and resource type");
|
|
60
70
|
const id = String(params.reference_resource_id);
|
|
@@ -66,9 +76,11 @@ export function discoveryContract(kind: DiscoveryKind, input: Record<string, unk
|
|
|
66
76
|
}
|
|
67
77
|
for (const [key, value] of Object.entries(params)) if (!["cursor", "page", "page_size"].includes(key)) filters[key] = String(value);
|
|
68
78
|
const capabilities = ["pagination.v1"];
|
|
69
|
-
if
|
|
79
|
+
if(kind==="references")capabilities.push("reference.resources.v1");
|
|
80
|
+
else if (kind === "topics") capabilities.push("knowledge.lookup.v1");
|
|
70
81
|
else if (Object.keys(filters).length) capabilities.push("note.filters.v1");
|
|
71
|
-
if (kind !== "topics") capabilities.push("note.reference.v1");
|
|
82
|
+
if (kind !== "topics"&&kind!=="references") capabilities.push("note.reference.v1");
|
|
83
|
+
if(params.reference_course_type||params.reference_course_id)capabilities.push("note.course_filter.v1");
|
|
72
84
|
return { params, filters, capabilities, kind };
|
|
73
85
|
}
|
|
74
86
|
|
|
@@ -84,8 +96,13 @@ export function verifyDiscovery(body: unknown, contract: DiscoveryContract): voi
|
|
|
84
96
|
if (!applied.success) throw new Error("server did not return applied_filters");
|
|
85
97
|
for (const [key, value] of Object.entries(contract.filters)) if (applied.data[key] !== value) throw new Error(`server did not apply ${key}`);
|
|
86
98
|
const p = z.object({ mode: z.enum(["page", "cursor"]), page: integer.nullable(), page_size: integer.max(100), returned_count: z.number().int().nonnegative(), total_count: z.number().int().nonnegative().nullable(), has_more: z.boolean(), next_page: integer.nullable(), next_cursor: z.string().min(1).nullable() }).parse(data.pagination);
|
|
87
|
-
const items = data[contract.kind === "topics" ? "topics" : "notes"];
|
|
99
|
+
const items = data[contract.kind === "topics" ? "topics" : contract.kind==="references"?"resources":"notes"];
|
|
88
100
|
const page = contract.params.page;
|
|
89
101
|
if (!Array.isArray(items) || p.mode !== (page ? "page" : "cursor") || p.page_size !== contract.params.page_size || p.returned_count !== items.length || items.length > p.page_size || (p.total_count !== null && p.total_count < items.length) || (page && p.page !== page)) throw new Error("invalid discovery pagination response");
|
|
90
102
|
if (p.has_more ? (page ? p.next_page !== Number(page) + 1 || p.next_cursor !== null : !p.next_cursor || p.next_page !== null) : p.next_page !== null || p.next_cursor !== null) throw new Error("invalid discovery continuation");
|
|
103
|
+
if(contract.kind==="references"){
|
|
104
|
+
if(p.total_count!==null)throw new Error("course reference total must be unknown");
|
|
105
|
+
if(p.has_more&&p.next_cursor===contract.params.cursor)throw new Error("reference cursor did not advance");
|
|
106
|
+
for(const item of items){const v=z.object({course_type:text,course_id:text}).parse(item);decimalID(v.course_id)}
|
|
107
|
+
}
|
|
91
108
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {z} from "zod";
|
|
2
|
+
|
|
3
|
+
export function decimalID(value: string): string {
|
|
4
|
+
if (!/^\d+$/.test(value) || BigInt(value) <= 0n || BigInt(value) > 9223372036854775807n) throw new Error("ID must be a positive signed-64-bit decimal string");
|
|
5
|
+
return BigInt(value).toString();
|
|
6
|
+
}
|
|
7
|
+
const batchSchema=z.object({ids:z.array(z.string()).min(1).max(200),fields:z.array(z.enum(["content","ref_content","reference","original"])).optional(),max_total_chars:z.number().int().min(1).max(64000).optional()}).strict();
|
|
8
|
+
export type BatchDetailOptions=z.infer<typeof batchSchema>;
|
|
9
|
+
export function normalizeBatch(input:BatchDetailOptions):BatchDetailOptions {
|
|
10
|
+
const out=batchSchema.parse(input);out.ids=[...new Set(out.ids.map(decimalID))];
|
|
11
|
+
if(out.ids.length>20)throw new Error("batch supports at most20 unique IDs");
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
export interface SearchOptions {response_mode?:string;max_snippet_chars?:number}
|
|
15
|
+
export function validateSearchOptions(input:SearchOptions):void {
|
|
16
|
+
if(input.response_mode===undefined&&input.max_snippet_chars===undefined)return;
|
|
17
|
+
if(input.response_mode!=="snippet")throw new Error("response_mode must be snippet when requesting snippets");
|
|
18
|
+
if(input.max_snippet_chars!==undefined&&(!Number.isInteger(input.max_snippet_chars)||input.max_snippet_chars<100||input.max_snippet_chars>1000))throw new Error("max_snippet_chars must be 100..1000");
|
|
19
|
+
}
|
|
20
|
+
export function verifyExperience(body:unknown,path:string,request:unknown):void {
|
|
21
|
+
const input=request as (SearchOptions&{ids?:string[]})|undefined;
|
|
22
|
+
const cap=path==="/resource/note/batch-detail"?"note.batch_detail.v1":input?.response_mode==="snippet"?"search.snippet.v1":undefined;
|
|
23
|
+
if(!cap)return;
|
|
24
|
+
const parsed=z.object({meta:z.object({capabilities:z.array(z.string())}),data:z.record(z.unknown())}).safeParse(body);
|
|
25
|
+
if(!parsed.success||!parsed.data.meta.capabilities.includes(cap))throw new Error(`server does not support ${cap}; new mode was not accepted`);
|
|
26
|
+
const data=parsed.data.data;
|
|
27
|
+
if(cap==="note.batch_detail.v1"){
|
|
28
|
+
const items=z.array(z.object({note_id:z.string(),status:z.string().min(1)})).parse(data.items);
|
|
29
|
+
if(items.length!==input?.ids?.length||items.some((item,i)=>item.note_id!==input.ids?.[i]))throw new Error("batch response lost identities or order");
|
|
30
|
+
}else if(data.response_mode!=="snippet"||data.max_snippet_chars!==(input?.max_snippet_chars??400))throw new Error("server ignored snippet options");
|
|
31
|
+
}
|