@getnote/mcp 1.10.1 → 1.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -3
- package/dist/admission.d.ts +16 -0
- package/dist/admission.d.ts.map +1 -0
- package/dist/admission.js +95 -0
- package/dist/client.d.ts +28 -4
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +212 -39
- package/dist/index.js +38 -9
- package/dist/read-retry.d.ts +3 -1
- package/dist/read-retry.d.ts.map +1 -1
- package/dist/read-retry.js +42 -3
- package/dist/upload-operation.d.ts +24 -0
- package/dist/upload-operation.d.ts.map +1 -0
- package/dist/upload-operation.js +18 -0
- package/package.json +1 -1
- package/src/admission.ts +67 -0
- package/src/client.ts +177 -41
- package/src/index.ts +40 -9
- package/src/read-retry.ts +32 -4
- package/src/upload-operation.ts +20 -0
- package/test/admission-v2.test.mjs +67 -0
- package/test/kb-batch.test.mjs +13 -0
- package/test/upload-http-boundary.test.mjs +47 -0
- package/test/upload-recovery.test.mjs +53 -0
- package/test/upload-safety.test.mjs +133 -0
- package/test/upload-v2-protocol.test.mjs +30 -0
package/src/admission.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {waitForReadRetry} from './read-retry';
|
|
3
|
+
|
|
4
|
+
// Advisory pacing is shared only inside this Node process and authorization
|
|
5
|
+
// identity. The server remains authoritative; no credentials are map keys.
|
|
6
|
+
interface Queue {
|
|
7
|
+
tail:Promise<void>; pending:number; timer?:NodeJS.Timeout;
|
|
8
|
+
rates:Map<string,number>; last:Map<string,number>; cooldowns:Map<string,number>;
|
|
9
|
+
}
|
|
10
|
+
const queues=new Map<string,Queue>();
|
|
11
|
+
const idleMilliseconds=5*60*1000;
|
|
12
|
+
export function authorizationIdentity(baseURL:string,authorization:string,clientID:string):string {
|
|
13
|
+
return createHash('sha256').update(JSON.stringify([baseURL,authorization,clientID])).digest('hex');
|
|
14
|
+
}
|
|
15
|
+
function abortable<T>(promise:Promise<T>,signal?:AbortSignal):Promise<T>{
|
|
16
|
+
signal?.throwIfAborted();
|
|
17
|
+
if(!signal)return promise;
|
|
18
|
+
return new Promise((resolve,reject)=>{
|
|
19
|
+
const abort=()=>reject(signal.reason??new Error('cancelled'));
|
|
20
|
+
signal.addEventListener('abort',abort,{once:true});
|
|
21
|
+
promise.then(resolve,reject).finally(()=>signal.removeEventListener('abort',abort));
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
export async function inAuthorizationQueue<T>(identity:string,signal:AbortSignal|undefined,work:(queue:Queue)=>Promise<T>):Promise<T>{
|
|
25
|
+
signal?.throwIfAborted();
|
|
26
|
+
let queue=queues.get(identity);
|
|
27
|
+
if(!queue){queue={tail:Promise.resolve(),pending:0,rates:new Map(),last:new Map(),cooldowns:new Map()};queues.set(identity,queue)}
|
|
28
|
+
clearTimeout(queue.timer);queue.pending++;
|
|
29
|
+
const previous=queue.tail;let release!:()=>void;
|
|
30
|
+
queue.tail=new Promise<void>(r=>release=r);
|
|
31
|
+
const slot=queue;
|
|
32
|
+
// A cancelled waiter releases its slot only after its predecessor, so a
|
|
33
|
+
// later request can never overtake a still running operation.
|
|
34
|
+
try {await abortable(previous,signal);signal?.throwIfAborted();return await work(slot)}
|
|
35
|
+
finally {
|
|
36
|
+
previous.then(release);
|
|
37
|
+
if(--slot.pending===0){slot.timer=setTimeout(()=>{if(queues.get(identity)===slot&&slot.pending===0)queues.delete(identity)},idleMilliseconds);slot.timer.unref()}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function learnPolicy(queue:Queue,data:unknown):void {
|
|
41
|
+
const value=data as {rate_limit_policy?:{rates?:unknown};runtime?:{rate_limit_policy?:{rates?:unknown}}}|undefined;
|
|
42
|
+
const rates=value?.rate_limit_policy?.rates??value?.runtime?.rate_limit_policy?.rates;
|
|
43
|
+
if(!rates||typeof rates!=='object'||Array.isArray(rates))return;
|
|
44
|
+
queue.rates.clear();
|
|
45
|
+
for(const [bucket,raw]of Object.entries(rates))learnRate(queue,bucket,(raw as {sustained_rate_per_second?:unknown})?.sustained_rate_per_second);
|
|
46
|
+
}
|
|
47
|
+
export function learnRate(queue:Queue,bucket:unknown,rate:unknown):void {
|
|
48
|
+
if(typeof bucket==='string'&&['global','read','write','write_note','upload_credential'].includes(bucket)&&typeof rate==='number'&&Number.isFinite(rate)&&rate>0)queue.rates.set(bucket,rate);
|
|
49
|
+
}
|
|
50
|
+
export function learnCooldown(queue:Queue,bucket:string,milliseconds:number):void {
|
|
51
|
+
if(!Number.isFinite(milliseconds)||milliseconds<0)return;
|
|
52
|
+
queue.cooldowns.set(bucket,Math.max(queue.cooldowns.get(bucket)??0,performance.now()+milliseconds));
|
|
53
|
+
}
|
|
54
|
+
export async function pace(queue:Queue,bucket:string,signal?:AbortSignal,maxWait=Infinity):Promise<boolean>{
|
|
55
|
+
let delay=0;const now=performance.now();
|
|
56
|
+
for(const key of ['global',bucket]){
|
|
57
|
+
delay=Math.max(delay,(queue.cooldowns.get(key)??0)-now);
|
|
58
|
+
const rate=queue.rates.get(key),last=queue.last.get(key);
|
|
59
|
+
if(rate!==undefined&&last!==undefined)delay=Math.max(delay,last+1000/rate-now);
|
|
60
|
+
}
|
|
61
|
+
if(delay>maxWait)return false;
|
|
62
|
+
const deadline=performance.now()+delay;
|
|
63
|
+
// Node clamps timer values above int32 to one millisecond. Chunk long policy
|
|
64
|
+
// waits so they remain cancellable without dispatching early.
|
|
65
|
+
for(let remaining=deadline-performance.now();remaining>0;remaining=deadline-performance.now())await waitForReadRetry(Math.min(Math.ceil(remaining),2147483647),signal);
|
|
66
|
+
signal?.throwIfAborted();const started=performance.now();queue.last.set('global',started);queue.last.set(bucket,started);return true;
|
|
67
|
+
}
|
package/src/client.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import axios, { AxiosInstance, AxiosError } from "axios";
|
|
2
2
|
import { discoveryContract, verifyDiscovery, NoteDiscoveryOptions, LookupOptions, DiscoveryKind } from "./discovery";
|
|
3
3
|
import {BatchDetailOptions,SearchOptions,normalizeBatch,validateSearchOptions,verifyExperience} from "./experience";
|
|
4
|
-
import {readRetryDelay,waitForReadRetry} from "./read-retry";
|
|
4
|
+
import {readRetryDelay,waitForReadRetry,operationBucket} from "./read-retry";
|
|
5
|
+
|
|
6
|
+
import {authorizationIdentity,inAuthorizationQueue,learnPolicy,learnRate,learnCooldown,pace} from "./admission";
|
|
7
|
+
|
|
8
|
+
import {UploadKind,UploadRuntime,UploadOperation,uploadRoutes,validateOperationID,supportsRecovery,newOperationID} from "./upload-operation";
|
|
5
9
|
|
|
6
10
|
const DEFAULT_BASE_URL = "https://openapi.biji.com/open/api/v1";
|
|
7
11
|
|
|
@@ -52,6 +56,10 @@ export function parseJsonPreservingLargeIntegerStrings(data: unknown) {
|
|
|
52
56
|
export class GetNoteAPIError extends Error {
|
|
53
57
|
httpStatus?:number;
|
|
54
58
|
waitProvided=false;
|
|
59
|
+
operationId?:string;
|
|
60
|
+
uploadKind?:UploadKind;
|
|
61
|
+
recoveryAdvice?:string;
|
|
62
|
+
queryTool?:string;
|
|
55
63
|
constructor(
|
|
56
64
|
public readonly code: number,
|
|
57
65
|
public readonly reason: string,
|
|
@@ -62,7 +70,8 @@ export class GetNoteAPIError extends Error {
|
|
|
62
70
|
public readonly constraint?: string,
|
|
63
71
|
public readonly expectedType?: string,
|
|
64
72
|
public readonly supportedValues?: string[],
|
|
65
|
-
public readonly retryAfterSeconds?: number
|
|
73
|
+
public readonly retryAfterSeconds?: number,
|
|
74
|
+
public readonly rateLimitDetail?: unknown
|
|
66
75
|
) {
|
|
67
76
|
super(message);
|
|
68
77
|
this.name = "GetNoteAPIError";
|
|
@@ -70,7 +79,7 @@ export class GetNoteAPIError extends Error {
|
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
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});
|
|
82
|
+
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),err?.rate_limit_detail),{httpStatus:status,waitProvided:err?.retry_after_seconds!==undefined||header!==undefined});
|
|
74
83
|
}
|
|
75
84
|
|
|
76
85
|
export class GetNoteClient {
|
|
@@ -84,16 +93,98 @@ export class GetNoteClient {
|
|
|
84
93
|
return this.request<unknown>("GET", "/resource/note/sprout", { id });
|
|
85
94
|
}
|
|
86
95
|
async getKnowledgeFileCapabilities() {
|
|
87
|
-
return this.
|
|
96
|
+
return this.uploadConfiguration('file');
|
|
88
97
|
}
|
|
89
|
-
async getKnowledgeFileUploadToken(mime_type: string) {
|
|
90
|
-
return this.
|
|
98
|
+
async getKnowledgeFileUploadToken(mime_type: string,operation_id?:string) {
|
|
99
|
+
return this.uploadCredential('file',{mime_type},operation_id);
|
|
91
100
|
}
|
|
101
|
+
async getKnowledgeFileUploadOperation(operation_id:string){return this.getOperation('file',operation_id)}
|
|
102
|
+
async getUploadOperation(operation_id:string){return this.getOperation('image',operation_id)}
|
|
92
103
|
async uploadKnowledgeFile(data: { topic_id: string; directory_id: string; file_name: string; file_type: string; md5: string; url: string }) {
|
|
93
104
|
return this.request<unknown>("POST", "/resource/knowledge/file/upload", undefined, data);
|
|
94
105
|
}
|
|
95
106
|
private http: AxiosInstance;
|
|
96
107
|
private requestSignal?:AbortSignal;
|
|
108
|
+
private identity:string;
|
|
109
|
+
private uploadRuntimeCache:Partial<Record<UploadKind,{runtime?:UploadRuntime;at:number}>>={};
|
|
110
|
+
|
|
111
|
+
private async uploadConfiguration(kind:UploadKind,allowRetry=true){
|
|
112
|
+
const path=uploadRoutes[kind]+(kind==='image'?'/config':'/capabilities');
|
|
113
|
+
const config=await this.request<Record<string,unknown>>('GET',path,undefined,undefined,undefined,allowRetry);
|
|
114
|
+
this.uploadRuntimeCache[kind]={runtime:config?.runtime as UploadRuntime|undefined,at:Date.now()};
|
|
115
|
+
return config;
|
|
116
|
+
}
|
|
117
|
+
private async recoveryRuntime(kind:UploadKind):Promise<UploadRuntime|undefined>{
|
|
118
|
+
if(!this.uploadRuntimeCache[kind]||Date.now()-this.uploadRuntimeCache[kind]!.at>5*60*1000){
|
|
119
|
+
try {await this.uploadConfiguration(kind,false)}catch(error){
|
|
120
|
+
// Old servers may omit config. File capabilities additionally require
|
|
121
|
+
// topic.read, while a topic.write-only grant may still issue once without
|
|
122
|
+
// claiming replay support. Explicit operation IDs still fail unsupported.
|
|
123
|
+
if(error instanceof GetNoteAPIError&&(error.httpStatus===404||kind==='file'&&error.httpStatus===403))this.uploadRuntimeCache[kind]={at:Date.now()};
|
|
124
|
+
else throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return this.uploadRuntimeCache[kind]?.runtime;
|
|
128
|
+
}
|
|
129
|
+
private operationAdvice(error:GetNoteAPIError,kind:UploadKind,id:string):GetNoteAPIError {
|
|
130
|
+
error.operationId=id;error.uploadKind=kind;
|
|
131
|
+
error.recoveryAdvice='Keep the original operation_id and query the original upload operation; do not mint a new key or upload again. Preserve uploaded objects and the same note client_request_id after save rate limits. Pending tasks are not complete.';
|
|
132
|
+
error.queryTool=kind==='image'?'get_upload_operation':'get_knowledge_file_upload_operation';
|
|
133
|
+
return error;
|
|
134
|
+
}
|
|
135
|
+
private operationFailure(kind:UploadKind,id:string,reason:string,original?:GetNoteAPIError):GetNoteAPIError {
|
|
136
|
+
const error=new GetNoteAPIError(original?.code??-1,reason,'Original upload operation is not confirmed or no longer recoverable; query its original operation_id.',original?.requestId,false,original?.field,original?.constraint,original?.expectedType,original?.supportedValues,original?.retryAfterSeconds,original?.rateLimitDetail);
|
|
137
|
+
error.httpStatus=original?.httpStatus;
|
|
138
|
+
return this.operationAdvice(error,kind,id);
|
|
139
|
+
}
|
|
140
|
+
private usableCredential(kind:UploadKind,id:string,value:unknown,outerDeadline?:string,original?:GetNoteAPIError):Record<string,unknown> {
|
|
141
|
+
if(!value||typeof value!=='object'||Array.isArray(value))throw this.operationFailure(kind,id,'credential_operation_unconfirmed',original);
|
|
142
|
+
const credential=value as Record<string,unknown>;
|
|
143
|
+
if(credential.operation_id!==undefined&&credential.operation_id!==id)throw this.operationFailure(kind,id,'credential_operation_conflict',original);
|
|
144
|
+
let deadline=outerDeadline;
|
|
145
|
+
if(credential.resume_until!==undefined){
|
|
146
|
+
if(typeof credential.resume_until!=='string'||!Number.isFinite(Date.parse(credential.resume_until)))throw this.operationFailure(kind,id,'credential_operation_unconfirmed',original);
|
|
147
|
+
if(deadline===undefined||Date.parse(credential.resume_until)<Date.parse(deadline))deadline=credential.resume_until;
|
|
148
|
+
}
|
|
149
|
+
if(deadline===undefined||!Number.isFinite(Date.parse(deadline)))throw this.operationFailure(kind,id,'credential_operation_unconfirmed',original);
|
|
150
|
+
if(Date.parse(deadline)<=Date.now())throw this.operationFailure(kind,id,'credential_operation_expired',original);
|
|
151
|
+
return {...credential,operation_id:id,resume_until:deadline};
|
|
152
|
+
}
|
|
153
|
+
private async lookupOperation(kind:UploadKind,id:string,original?:GetNoteAPIError):Promise<UploadOperation>{
|
|
154
|
+
let view:UploadOperation;
|
|
155
|
+
try {view=await this.request<UploadOperation>('GET',uploadRoutes[kind]+'/upload_operation',{operation_id:id})}
|
|
156
|
+
catch(error){throw this.operationFailure(kind,id,error instanceof GetNoteAPIError?error.reason:'credential_operation_unconfirmed',original??(error instanceof GetNoteAPIError?error:undefined))}
|
|
157
|
+
const deadline=Date.parse(view?.resume_until);
|
|
158
|
+
if(view?.operation_id!==id||view.state!=='issued'||!Number.isFinite(deadline)||deadline<=Date.now()||!view.credential||typeof view.credential!=='object'||Array.isArray(view.credential)){
|
|
159
|
+
throw this.operationFailure(kind,id,view?.state==='expired'||Number.isFinite(deadline)&&deadline<=Date.now()?'credential_operation_expired':'credential_operation_unconfirmed',original);
|
|
160
|
+
}
|
|
161
|
+
const credential=this.usableCredential(kind,id,view.credential,view.resume_until,original);
|
|
162
|
+
return {...view,resume_until:credential.resume_until as string,credential};
|
|
163
|
+
}
|
|
164
|
+
private async getOperation(kind:UploadKind,operation_id:string){
|
|
165
|
+
validateOperationID(operation_id);
|
|
166
|
+
if(!supportsRecovery(await this.recoveryRuntime(kind),kind))throw this.operationFailure(kind,operation_id,'upload_operation_unsupported');
|
|
167
|
+
return this.lookupOperation(kind,operation_id);
|
|
168
|
+
}
|
|
169
|
+
private async uploadCredential(kind:UploadKind,params:Record<string,unknown>,operation_id?:string):Promise<Record<string,unknown>>{
|
|
170
|
+
if(operation_id!==undefined)validateOperationID(operation_id);
|
|
171
|
+
const supported=supportsRecovery(await this.recoveryRuntime(kind),kind);
|
|
172
|
+
if(!supported){
|
|
173
|
+
if(operation_id!==undefined)throw this.operationFailure(kind,operation_id,'upload_operation_unsupported');
|
|
174
|
+
return this.request('GET',uploadRoutes[kind]+'/upload_token',params);
|
|
175
|
+
}
|
|
176
|
+
const id=operation_id??newOperationID();
|
|
177
|
+
try {
|
|
178
|
+
const credential=await this.request<Record<string,unknown>>('GET',uploadRoutes[kind]+'/upload_token',params,undefined,{'Idempotency-Key':id});
|
|
179
|
+
return this.usableCredential(kind,id,credential);
|
|
180
|
+
}catch(error){
|
|
181
|
+
if(error instanceof GetNoteAPIError){
|
|
182
|
+
if(!['credential_operation_unconfirmed','credential_operation_unavailable','unexpected_http_response'].includes(error.reason))throw this.operationAdvice(error,kind,id);
|
|
183
|
+
}else if(this.requestSignal?.aborted){throw this.operationFailure(kind,id,'credential_operation_unconfirmed')}
|
|
184
|
+
const recovered=await this.lookupOperation(kind,id,error instanceof GetNoteAPIError?error:undefined);
|
|
185
|
+
return {...recovered.credential,operation_id:id,resume_until:recovered.resume_until};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
97
188
|
|
|
98
189
|
withSignal(signal:AbortSignal):GetNoteClient {
|
|
99
190
|
// Per-call view shares the HTTP transport, never another call's signal.
|
|
@@ -101,16 +192,29 @@ export class GetNoteClient {
|
|
|
101
192
|
}
|
|
102
193
|
|
|
103
194
|
constructor(apiKey: string, clientId: string, baseURL?: string) {
|
|
195
|
+
const normalized=normalizeBaseURL(baseURL || process.env.GETNOTE_API_URL);
|
|
196
|
+
this.identity=authorizationIdentity(normalized,`Bearer ${apiKey}`,clientId);
|
|
104
197
|
this.http = axios.create({
|
|
105
|
-
baseURL:
|
|
198
|
+
baseURL: normalized,
|
|
106
199
|
headers: {
|
|
107
200
|
Authorization: `Bearer ${apiKey}`,
|
|
108
201
|
"X-Client-ID": clientId,
|
|
109
202
|
"Content-Type": "application/json",
|
|
110
203
|
},
|
|
111
204
|
timeout: 30000,
|
|
205
|
+
// Credential GETs issue side effects: redirects must not bypass the
|
|
206
|
+
// negotiated operation or the single-issuance recovery path.
|
|
207
|
+
maxRedirects: 0,
|
|
112
208
|
});
|
|
113
|
-
this.http.defaults.transformResponse = [
|
|
209
|
+
this.http.defaults.transformResponse = [(data, _headers, status) => {
|
|
210
|
+
try { return parseJsonPreservingLargeIntegerStrings(data); }
|
|
211
|
+
catch (error) {
|
|
212
|
+
// A legacy missing route may return plain text or HTML. Preserve its
|
|
213
|
+
// verified HTTP status instead of losing it to a JSON SyntaxError.
|
|
214
|
+
if (status !== undefined && status >= 300) return data;
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
}];
|
|
114
218
|
|
|
115
219
|
this.http.interceptors.response.use(
|
|
116
220
|
(res) => res,
|
|
@@ -121,30 +225,51 @@ export class GetNoteClient {
|
|
|
121
225
|
}
|
|
122
226
|
|
|
123
227
|
private async request<T>(
|
|
124
|
-
method:"GET"|"POST",path:string,params?:Record<string,unknown>,data?:unknown
|
|
228
|
+
method:"GET"|"POST",path:string,params?:Record<string,unknown>,data?:unknown,headers?:Record<string,string>,allowRetry=true
|
|
125
229
|
):Promise<T>{
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
230
|
+
// Snapshot caller-owned values once, before waiting or retrying.
|
|
231
|
+
params=params===undefined?undefined:structuredClone(params);
|
|
232
|
+
data=data===undefined?undefined:structuredClone(data);
|
|
233
|
+
return inAuthorizationQueue(this.identity,this.requestSignal,async queue=>{
|
|
234
|
+
let waited=0;let lastError:GetNoteAPIError|undefined;let pacingBudgetExceeded=false;
|
|
235
|
+
for(let attempt=0;;attempt++){
|
|
236
|
+
try {
|
|
237
|
+
this.requestSignal?.throwIfAborted();
|
|
238
|
+
const pacingStarted=performance.now();
|
|
239
|
+
if(!await pace(queue,operationBucket(method,path),this.requestSignal,lastError?5000-waited:Infinity)){pacingBudgetExceeded=true;throw lastError;}
|
|
240
|
+
if(lastError)waited+=performance.now()-pacingStarted;
|
|
241
|
+
const result=await this.requestOnce<T>(method,path,params,data,headers);
|
|
242
|
+
learnPolicy(queue,result);
|
|
243
|
+
return result;
|
|
244
|
+
}catch(err){
|
|
245
|
+
if(this.requestSignal?.aborted&&lastError)throw Object.assign(lastError,{cause:this.requestSignal.reason});
|
|
246
|
+
if(pacingBudgetExceeded||!(err instanceof GetNoteAPIError))throw err;
|
|
247
|
+
const detail=err.rateLimitDetail as Record<string,unknown>|null;
|
|
248
|
+
if(detail&&typeof detail==='object'&&detail.dimension==='qps')learnRate(queue,detail.bucket,detail.sustained_rate_per_second);
|
|
249
|
+
const qps=detail?.dimension==='qps'||err.rateLimitDetail===undefined&&((err.code===10202&&['qps_exceeded','qps_global_exceeded','qps_bucket_exceeded'].includes(err.reason))||(err.code===10005&&err.reason==='rate_limited'));
|
|
250
|
+
if(qps){
|
|
251
|
+
const bucket=typeof detail?.bucket==='string'&&['global','read','write','write_note','upload_credential'].includes(detail.bucket)?detail.bucket:err.reason==='qps_global_exceeded'?'global':operationBucket(method,path);
|
|
252
|
+
const waits=[0];
|
|
253
|
+
if(err.retryAfterSeconds!==undefined)waits.push(err.retryAfterSeconds*1000);
|
|
254
|
+
for(const [key,scale]of [['retry_after_ms',1],['retry_after_seconds',1000]] as const){const value=detail?.[key];if(typeof value==='number'&&Number.isSafeInteger(value)&&value>=0)waits.push(value*scale)}
|
|
255
|
+
learnCooldown(queue,bucket,Math.max(...waits));
|
|
256
|
+
}
|
|
257
|
+
const delay=allowRetry?readRetryDelay(method,path,err,attempt,waited,headers?.['Idempotency-Key']):undefined;
|
|
258
|
+
if(delay===undefined)throw err;
|
|
259
|
+
lastError=err;const start=performance.now();
|
|
260
|
+
try {await waitForReadRetry(delay,this.requestSignal)}catch(cause){throw Object.assign(err,{cause})}
|
|
261
|
+
waited+=performance.now()-start;
|
|
262
|
+
}
|
|
139
263
|
}
|
|
140
|
-
}
|
|
264
|
+
});
|
|
141
265
|
}
|
|
142
266
|
|
|
143
267
|
private async requestOnce<T>(
|
|
144
268
|
method: "GET" | "POST",
|
|
145
269
|
path: string,
|
|
146
270
|
params?: Record<string, unknown>,
|
|
147
|
-
data?: unknown
|
|
271
|
+
data?: unknown,
|
|
272
|
+
headers?:Record<string,string>
|
|
148
273
|
): Promise<T> {
|
|
149
274
|
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" };
|
|
150
275
|
const contract = method === "GET" && kinds[path] ? discoveryContract(kinds[path], params || {}) : undefined;
|
|
@@ -162,6 +287,7 @@ export class GetNoteClient {
|
|
|
162
287
|
params,
|
|
163
288
|
data,
|
|
164
289
|
signal:this.requestSignal,
|
|
290
|
+
headers,
|
|
165
291
|
});
|
|
166
292
|
|
|
167
293
|
const body = res.data;
|
|
@@ -189,7 +315,10 @@ export class GetNoteClient {
|
|
|
189
315
|
if (body?.error) {
|
|
190
316
|
throw apiFailure(body.error,body.request_id,err.response.status,err.response.headers["retry-after"]);
|
|
191
317
|
}
|
|
192
|
-
throw
|
|
318
|
+
throw apiFailure(
|
|
319
|
+
{code: -1, reason: 'unexpected_http_response', message: `HTTP ${err.response.status}: API response unavailable`},
|
|
320
|
+
undefined, err.response.status, err.response.headers["retry-after"]
|
|
321
|
+
);
|
|
193
322
|
}
|
|
194
323
|
|
|
195
324
|
throw err;
|
|
@@ -260,18 +389,12 @@ export class GetNoteClient {
|
|
|
260
389
|
// ─── Image ───────────────────────────────────────────────────────────────
|
|
261
390
|
|
|
262
391
|
async getUploadConfig() {
|
|
263
|
-
return this.
|
|
264
|
-
"GET",
|
|
265
|
-
"/resource/image/config"
|
|
266
|
-
);
|
|
392
|
+
return this.uploadConfiguration('image') as unknown as Promise<GetUploadConfigResp>;
|
|
267
393
|
}
|
|
268
394
|
|
|
269
|
-
async getUploadToken(params: { count?: number; mime_type?: string }) {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
"/resource/image/upload_token",
|
|
273
|
-
{ count: params.count, mime_type: params.mime_type }
|
|
274
|
-
);
|
|
395
|
+
async getUploadToken(params: { count?: number; mime_type?: string;operation_id?:string }) {
|
|
396
|
+
const credential=await this.uploadCredential('image',{count:params.count,mime_type:params.mime_type},params.operation_id);
|
|
397
|
+
return credential as unknown as GetUploadTokenResp;
|
|
275
398
|
}
|
|
276
399
|
|
|
277
400
|
/**
|
|
@@ -302,6 +425,9 @@ export class GetNoteClient {
|
|
|
302
425
|
|
|
303
426
|
const response = await axios.post(token.host, form, {
|
|
304
427
|
headers: form.getHeaders(),
|
|
428
|
+
signal: this.requestSignal,
|
|
429
|
+
timeout: 30000,
|
|
430
|
+
maxRedirects: 0,
|
|
305
431
|
maxBodyLength: Infinity,
|
|
306
432
|
validateStatus: () => true,
|
|
307
433
|
});
|
|
@@ -326,16 +452,22 @@ export class GetNoteClient {
|
|
|
326
452
|
*/
|
|
327
453
|
async uploadImage(
|
|
328
454
|
imageData: Buffer | Uint8Array,
|
|
329
|
-
mimeType: string = "png"
|
|
330
|
-
|
|
455
|
+
mimeType: string = "png",
|
|
456
|
+
operation_id?:string
|
|
457
|
+
): Promise<{ image_id: string; access_url: string;operation_id?:string;resume_until?:string }> {
|
|
331
458
|
// 1. 获取上传凭证(现在直接返回单个对象)
|
|
332
|
-
const token = await this.getUploadToken({ mime_type: mimeType });
|
|
459
|
+
const token = await this.getUploadToken({ mime_type: mimeType,operation_id });
|
|
333
460
|
|
|
334
461
|
// 2. 上传到 OSS
|
|
335
|
-
|
|
462
|
+
let image_id:string;
|
|
463
|
+
try {({image_id}=await this.uploadImageToOSS(token,imageData))}
|
|
464
|
+
catch(error){
|
|
465
|
+
if(token.operation_id)throw this.operationFailure('image',token.operation_id,'upload_result_unconfirmed');
|
|
466
|
+
throw error;
|
|
467
|
+
}
|
|
336
468
|
|
|
337
|
-
// 3.
|
|
338
|
-
return { image_id, access_url: token.access_url };
|
|
469
|
+
// 3. Preserve the original operation, never print the credential itself.
|
|
470
|
+
return { image_id, access_url: token.access_url,operation_id:token.operation_id,resume_until:token.resume_until };
|
|
339
471
|
}
|
|
340
472
|
|
|
341
473
|
// ─── Knowledge / Topics ─────────────────────────────────────────────────
|
|
@@ -686,10 +818,13 @@ export interface DeleteNoteTagResp {
|
|
|
686
818
|
export interface GetUploadConfigResp {
|
|
687
819
|
support_extensions: string[];
|
|
688
820
|
max_size_bytes: number;
|
|
821
|
+
runtime?:UploadRuntime;
|
|
689
822
|
}
|
|
690
823
|
|
|
691
824
|
// OSS 上传凭证(与 Web 端格式一致)
|
|
692
825
|
export interface ImageUploadToken {
|
|
826
|
+
operation_id?:string;
|
|
827
|
+
resume_until?:string;
|
|
693
828
|
accessid: string;
|
|
694
829
|
host: string;
|
|
695
830
|
policy: string;
|
|
@@ -937,6 +1072,7 @@ interface APIErrorBody {
|
|
|
937
1072
|
expected_type?: string;
|
|
938
1073
|
supported_values?: string[];
|
|
939
1074
|
retry_after_seconds?: number;
|
|
1075
|
+
rate_limit_detail?:unknown;
|
|
940
1076
|
}
|
|
941
1077
|
|
|
942
1078
|
export interface UpdateNoteResp {
|
package/src/index.ts
CHANGED
|
@@ -20,6 +20,11 @@ import { OPENAPI_MEMBERSHIP_PURCHASE_URL } from "./membership.js";
|
|
|
20
20
|
import { readFileSync, realpathSync } from "node:fs";
|
|
21
21
|
import { join, resolve, isAbsolute, sep } from "node:path";
|
|
22
22
|
|
|
23
|
+
const operationIDSchema={type:'string',pattern:'^[A-Za-z0-9._:-]{1,128}$',minLength:1,maxLength:128,description:'可选的原上传操作标识;恢复时必须复用。仅服务器协商支持时可用,不支持时明确失败。'};
|
|
24
|
+
const recoveryDescription='保留已上传对象和同一笔记 client_request_id;保存遇限流不要重新上传。凭据敏感,不得放进聊天、日志或命令参数。任务 pending/processing 不等于完成。恢复仅查询原 operation_id,不能自动申请新 key。';
|
|
25
|
+
const operationIDInput=z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/);
|
|
26
|
+
|
|
27
|
+
|
|
23
28
|
const pkg = JSON.parse(
|
|
24
29
|
readFileSync(join(__dirname, "..", "package.json"), "utf-8")
|
|
25
30
|
) as { version: string };
|
|
@@ -533,14 +538,24 @@ const TOOLS: Tool[] = [
|
|
|
533
538
|
description: "上传前查询当前配置允许的文件扩展名、MIME、大小、页数和独立日限额;不缓存为固定格式列表。",
|
|
534
539
|
inputSchema: { type: "object", properties: {} },
|
|
535
540
|
},
|
|
541
|
+
{
|
|
542
|
+
name: "get_knowledge_file_upload_operation",
|
|
543
|
+
description: "仅查询原知识库文件上传凭据操作。"+recoveryDescription,
|
|
544
|
+
inputSchema:{type:'object',properties:{operation_id:operationIDSchema},required:['operation_id']},
|
|
545
|
+
},
|
|
546
|
+
{
|
|
547
|
+
name: "get_upload_operation",
|
|
548
|
+
description: "仅查询原图片上传凭据操作。"+recoveryDescription,
|
|
549
|
+
inputSchema:{type:'object',properties:{operation_id:operationIDSchema},required:['operation_id']},
|
|
550
|
+
},
|
|
536
551
|
{
|
|
537
552
|
name: "get_knowledge_file_upload_token",
|
|
538
|
-
description: "获取一次 OSS 文件上传临时凭据。通过本地 getnote upload --token-file <file> --max-size-bytes <能力上限> 直接 PUT 到 OSS,无需再次 CLI 登录。凭据通过受控文件或 stdin 传入,不写命令参数或聊天;不要把文件字节传给云 MCP。",
|
|
539
|
-
inputSchema: { type: "object", properties: { mime_type: { type: "string", description: "能力接口返回的扩展名,如 HTML" } }, required: ["mime_type"] },
|
|
553
|
+
description: recoveryDescription+"获取一次 OSS 文件上传临时凭据。通过本地 getnote upload --token-file <file> --max-size-bytes <能力上限> 直接 PUT 到 OSS,无需再次 CLI 登录。凭据通过受控文件或 stdin 传入,不写命令参数或聊天;不要把文件字节传给云 MCP。",
|
|
554
|
+
inputSchema: { type: "object", properties: { mime_type: { type: "string", description: "能力接口返回的扩展名,如 HTML" },operation_id:operationIDSchema }, required: ["mime_type"] },
|
|
540
555
|
},
|
|
541
556
|
{
|
|
542
557
|
name: "upload_knowledge_file",
|
|
543
|
-
description: "OSS 直传成功后将原文件加入知识库,只接收元数据,不接收本地路径或 base64。返回处理中的资源不等于入库成功;用 list_topic_directories 查询同一 ID,直到 SUCCESS 或 FAIL。",
|
|
558
|
+
description: recoveryDescription+"OSS 直传成功后将原文件加入知识库,只接收元数据,不接收本地路径或 base64。返回处理中的资源不等于入库成功;用 list_topic_directories 查询同一 ID,直到 SUCCESS 或 FAIL。",
|
|
544
559
|
inputSchema: { type: "object", additionalProperties: false, properties: { topic_id: { type: "string" }, directory_id: { type: "string" }, file_name: { type: "string" }, file_type: { type: "string" }, md5: { type: "string" }, url: { type: "string" } }, required: ["topic_id", "directory_id", "file_name", "file_type", "md5", "url"] },
|
|
545
560
|
},
|
|
546
561
|
// ── Image ──
|
|
@@ -557,10 +572,11 @@ const TOOLS: Tool[] = [
|
|
|
557
572
|
{
|
|
558
573
|
name: "get_upload_token",
|
|
559
574
|
description:
|
|
560
|
-
"获取 OSS 图片上传凭证。返回 accessid/host/policy/signature 等字段,用于 multipart/form-data POST 上传图片到阿里云 OSS。上传成功后获取 image_id,再用 save_note 创建图片笔记。⚠️ mime_type 必须与实际文件格式一致,否则 OSS 签名失败。",
|
|
575
|
+
recoveryDescription+"获取 OSS 图片上传凭证。返回 accessid/host/policy/signature 等字段,用于 multipart/form-data POST 上传图片到阿里云 OSS。上传成功后获取 image_id,再用 save_note 创建图片笔记。⚠️ mime_type 必须与实际文件格式一致,否则 OSS 签名失败。",
|
|
561
576
|
inputSchema: {
|
|
562
577
|
type: "object" as const,
|
|
563
578
|
properties: {
|
|
579
|
+
operation_id:operationIDSchema,
|
|
564
580
|
mime_type: {
|
|
565
581
|
type: "string",
|
|
566
582
|
enum: ["jpg", "png", "gif", "webp", "jpeg"],
|
|
@@ -578,10 +594,11 @@ const TOOLS: Tool[] = [
|
|
|
578
594
|
{
|
|
579
595
|
name: "upload_image",
|
|
580
596
|
description:
|
|
581
|
-
"上传图片到 OSS。返回 image_url(用于创建图片笔记的 image_urls 参数)。",
|
|
597
|
+
recoveryDescription+"上传图片到 OSS。返回 image_url(用于创建图片笔记的 image_urls 参数)。",
|
|
582
598
|
inputSchema: {
|
|
583
599
|
type: "object" as const,
|
|
584
600
|
properties: {
|
|
601
|
+
operation_id:operationIDSchema,
|
|
585
602
|
image_path: {
|
|
586
603
|
type: "string",
|
|
587
604
|
description:
|
|
@@ -1007,7 +1024,9 @@ async function handleTool(
|
|
|
1007
1024
|
case "list_sprouts": return client.listSprouts(z.string().regex(/^\d{4}-\d{2}$/).parse(input.month), z.string().optional().parse(input.since_id), z.number().int().min(1).max(20).optional().parse(input.limit));
|
|
1008
1025
|
case "get_sprout": return client.getSprout(z.string().min(1).parse(input.id));
|
|
1009
1026
|
case "get_knowledge_file_capabilities": return client.getKnowledgeFileCapabilities();
|
|
1010
|
-
case "
|
|
1027
|
+
case "get_upload_operation": return client.getUploadOperation(operationIDInput.parse(input.operation_id));
|
|
1028
|
+
case "get_knowledge_file_upload_operation": return client.getKnowledgeFileUploadOperation(operationIDInput.parse(input.operation_id));
|
|
1029
|
+
case "get_knowledge_file_upload_token": return client.getKnowledgeFileUploadToken(z.string().min(1).parse(input.mime_type),operationIDInput.optional().parse(input.operation_id));
|
|
1011
1030
|
case "upload_knowledge_file": return client.uploadKnowledgeFile(z.object({ topic_id:z.string().min(1), directory_id:z.string().regex(/^\d+$/), file_name:z.string().min(1), file_type:z.string().min(1), md5:z.string().regex(/^[a-fA-F0-9]{32}$/), url:z.string().url() }).strict().parse(input));
|
|
1012
1031
|
case "get_upload_config": {
|
|
1013
1032
|
return client.getUploadConfig();
|
|
@@ -1016,6 +1035,7 @@ async function handleTool(
|
|
|
1016
1035
|
return client.getUploadToken({
|
|
1017
1036
|
mime_type: input.mime_type as string | undefined,
|
|
1018
1037
|
count: input.count as number | undefined,
|
|
1038
|
+
operation_id:operationIDInput.optional().parse(input.operation_id),
|
|
1019
1039
|
});
|
|
1020
1040
|
}
|
|
1021
1041
|
case "upload_image": {
|
|
@@ -1035,11 +1055,13 @@ async function handleTool(
|
|
|
1035
1055
|
|
|
1036
1056
|
// mime_type 传扩展名格式(如 png、jpg)
|
|
1037
1057
|
const mimeType = (input.mime_type as string) || "png";
|
|
1038
|
-
const result = await client.uploadImage(imageData, mimeType);
|
|
1058
|
+
const result = await client.uploadImage(imageData, mimeType,operationIDInput.optional().parse(input.operation_id));
|
|
1039
1059
|
return {
|
|
1040
1060
|
success: true,
|
|
1041
1061
|
image_url: result.access_url, // 用于创建图片笔记
|
|
1042
|
-
image_id: result.image_id // OSS 回调返回的 ID
|
|
1062
|
+
image_id: result.image_id, // OSS 回调返回的 ID
|
|
1063
|
+
operation_id:result.operation_id,
|
|
1064
|
+
resume_until:result.resume_until
|
|
1043
1065
|
};
|
|
1044
1066
|
}
|
|
1045
1067
|
|
|
@@ -1165,11 +1187,15 @@ async function main() {
|
|
|
1165
1187
|
|
|
1166
1188
|
try {
|
|
1167
1189
|
const result = await handleTool(name, input, client.withSignal(extra.signal));
|
|
1190
|
+
const batch = result as { failed_note_ids?: unknown[] } | null;
|
|
1191
|
+
const rejected = (name === "batch_add_notes_to_topic" || name === "remove_note_from_topic")
|
|
1192
|
+
&& Array.isArray(batch?.failed_note_ids) && batch.failed_note_ids.length > 0;
|
|
1168
1193
|
return {
|
|
1194
|
+
...(rejected ? { isError: true } : {}),
|
|
1169
1195
|
content: [
|
|
1170
1196
|
{
|
|
1171
1197
|
type: "text" as const,
|
|
1172
|
-
text: JSON.stringify(result, null, 2),
|
|
1198
|
+
text: JSON.stringify(rejected ? { ...result as object, error: true, reason: "knowledge_notes_rejected", retryable: false, message: "Some notes were rejected; inspect failed_note_ids and the actual success count. Do not retry the entire batch." } : result, null, 2),
|
|
1173
1199
|
},
|
|
1174
1200
|
],
|
|
1175
1201
|
};
|
|
@@ -1187,6 +1213,11 @@ async function main() {
|
|
|
1187
1213
|
expected_type: err.expectedType,
|
|
1188
1214
|
supported_values: err.supportedValues,
|
|
1189
1215
|
retry_after_seconds: err.retryAfterSeconds,
|
|
1216
|
+
rate_limit_detail: err.rateLimitDetail,
|
|
1217
|
+
operation_id:err.operationId,
|
|
1218
|
+
upload_kind:err.uploadKind,
|
|
1219
|
+
recovery_advice:err.recoveryAdvice,
|
|
1220
|
+
query_tool:err.queryTool,
|
|
1190
1221
|
};
|
|
1191
1222
|
if (err.code === 10201) {
|
|
1192
1223
|
errPayload.membership_url = OPENAPI_MEMBERSHIP_PURCHASE_URL;
|
package/src/read-retry.ts
CHANGED
|
@@ -1,13 +1,41 @@
|
|
|
1
|
-
export interface ReadFailure {httpStatus?:number;code:number;reason:string;retryable:boolean;retryAfterSeconds?:number;waitProvided?:boolean}
|
|
1
|
+
export interface ReadFailure {httpStatus?:number;code:number;reason:string;retryable:boolean;retryAfterSeconds?:number;waitProvided?:boolean;rateLimitDetail?:unknown}
|
|
2
2
|
const getPaths=new Set([
|
|
3
3
|
"/resource/note/list","/resource/note/detail","/resource/note/marks","/resource/note/sprouts","/resource/note/sprout",
|
|
4
4
|
"/resource/reference/list","/resource/knowledge/list","/resource/knowledge/subscribe/list","/resource/knowledge/notes","/resource/knowledge/directories",
|
|
5
|
-
"/resource/knowledge/file/capabilities","/resource/knowledge/bloggers","/resource/knowledge/blogger/contents","/resource/knowledge/blogger/content/detail",
|
|
5
|
+
"/resource/image/config","/resource/image/upload_operation","/resource/knowledge/file/upload_operation","/resource/knowledge/file/capabilities","/resource/knowledge/bloggers","/resource/knowledge/blogger/contents","/resource/knowledge/blogger/content/detail",
|
|
6
6
|
"/resource/knowledge/lives","/resource/knowledge/live/detail","/resource/rate-limit/quota"
|
|
7
7
|
]);
|
|
8
8
|
const postPaths=new Set(["/resource/recall","/resource/recall/knowledge","/resource/note/batch-detail"]);
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
const writePaths=new Set([
|
|
10
|
+
'/resource/note/save','/resource/note/delete','/resource/note/update','/resource/note/task/progress',
|
|
11
|
+
'/resource/note/tags/add','/resource/note/tags/delete','/resource/note/sharing',
|
|
12
|
+
'/resource/knowledge/create','/resource/knowledge/note/batch-add','/resource/knowledge/note/remove',
|
|
13
|
+
'/resource/knowledge/directory/create','/resource/knowledge/directory/update','/resource/knowledge/directory/delete',
|
|
14
|
+
'/resource/knowledge/blogger/follow','/resource/knowledge/live/follow','/resource/knowledge/file/upload'
|
|
15
|
+
]);
|
|
16
|
+
export function operationBucket(method:string,path:string):string {
|
|
17
|
+
if(path.endsWith('/upload_token'))return 'upload_credential';
|
|
18
|
+
if(path==='/resource/note/save')return 'write_note';
|
|
19
|
+
return method==='GET'||postPaths.has(path)?'read':'write';
|
|
20
|
+
}
|
|
21
|
+
export function readRetryDelay(method:string,path:string,error:ReadFailure,attempt:number,waited:number,idempotencyKey?:string):number|undefined {
|
|
22
|
+
if(attempt>=2||waited>=5000||error.httpStatus!==429||error.retryable!==true)return;
|
|
23
|
+
if(error.rateLimitDetail!==undefined){
|
|
24
|
+
const d=error.rateLimitDetail as Record<string,unknown>|null;
|
|
25
|
+
if(!d||typeof d!=='object'||Array.isArray(d)||d.dimension!=='qps'||d.request_execution!=='not_started'||d.retry_action!=='retry_same_operation'||d.retryable!==true)return;
|
|
26
|
+
const knownRead=method==='GET'&&getPaths.has(path)||method==='POST'&&postPaths.has(path);
|
|
27
|
+
const knownWrite=method==='POST'&&writePaths.has(path);
|
|
28
|
+
const credential=method==='GET'&&['/resource/image/upload_token','/resource/knowledge/file/upload_token'].includes(path)&&!!idempotencyKey;
|
|
29
|
+
if(!knownRead&&!knownWrite&&!credential)return;
|
|
30
|
+
const waits:number[]=[];
|
|
31
|
+
for(const [key,scale]of [['retry_after_ms',1],['retry_after_seconds',1000]] as const){
|
|
32
|
+
if(d[key]!==undefined){if(typeof d[key]!=='number'||!Number.isSafeInteger(d[key])||(d[key] as number)<0)return;waits.push((d[key] as number)*scale)}
|
|
33
|
+
}
|
|
34
|
+
if(error.waitProvided&&error.retryAfterSeconds===undefined)return;
|
|
35
|
+
if(error.retryAfterSeconds!==undefined)waits.push(error.retryAfterSeconds*1000);
|
|
36
|
+
const delay=(waits.length?Math.max(...waits):200*2**attempt)+1+Math.floor(Math.random()*50);
|
|
37
|
+
return delay<=5000-waited?delay:undefined;
|
|
38
|
+
}
|
|
11
39
|
const qpsLimit=error.code===10202&&["qps_exceeded","qps_global_exceeded","qps_bucket_exceeded"].includes(error.reason);
|
|
12
40
|
if(!qpsLimit&&!(error.code===10005&&error.reason==="rate_limited"))return;
|
|
13
41
|
if(!(method==="GET"?getPaths.has(path):method==="POST"&&postPaths.has(path)))return;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export type UploadKind='image'|'file';
|
|
4
|
+
export const uploadRoutes={image:'/resource/image',file:'/resource/knowledge/file'};
|
|
5
|
+
export interface UploadRuntime {
|
|
6
|
+
governance_enabled?:boolean;operation_replay?:boolean;idempotency_header?:string;operation_status_endpoint?:string;
|
|
7
|
+
[key:string]:unknown;
|
|
8
|
+
}
|
|
9
|
+
export interface UploadOperation {
|
|
10
|
+
operation_id:string;upload_id?:string;state:string;resume_until:string;credential?:Record<string,unknown>;
|
|
11
|
+
[key:string]:unknown;
|
|
12
|
+
}
|
|
13
|
+
export function validateOperationID(value:string):string {
|
|
14
|
+
if(typeof value!=='string'||!(/^[A-Za-z0-9._:-]{1,128}$/).test(value))throw new Error('operation_id must match ^[A-Za-z0-9._:-]{1,128}$');
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
export function supportsRecovery(runtime:UploadRuntime|undefined,kind:UploadKind):boolean {
|
|
18
|
+
return runtime?.governance_enabled===true&&runtime?.operation_replay===true&&runtime.idempotency_header==='Idempotency-Key'&&runtime.operation_status_endpoint==='/open/api/v1'+uploadRoutes[kind]+'/upload_operation';
|
|
19
|
+
}
|
|
20
|
+
export function newOperationID():string {return randomUUID()}
|