@getnote/dsh-plugin 0.1.1 → 0.3.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/lib/index.js CHANGED
@@ -1,138 +1,310 @@
1
- import { createRequire } from "node:module";
2
1
  import { apply as apply$1 } from "@deepseek-ai/dsh-skill-filesystem";
3
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
4
3
  import Schema from "@deepseek-ai/schemastery";
5
4
  import { fileURLToPath } from "node:url";
6
- import { spawn } from "node:child_process";
7
- import { accessSync, constants } from "node:fs";
8
- import { delimiter, dirname, join } from "node:path";
9
- //#region src/cli-runner.ts
10
- const require = createRequire(import.meta.url);
11
- var GetnoteCliError = class extends Error {
12
- exitCode;
13
- stderr;
14
- constructor(message, exitCode, stderr) {
5
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ //#region src/api.ts
9
+ /** OpenAPI client ID used by this plugin for authorization. */
10
+ const DSH_CLIENT_ID = "cli_35ca47aab229ebb0c4c4dd12";
11
+ const DEFAULT_API_URL = "https://openapi.biji.com";
12
+ const MEMBERSHIP_URL = "https://www.biji.com/checkout?product_alias=9Ab36BB3ZD&spm=openapi_dsh";
13
+ var GetnoteApiError = class extends Error {
14
+ code;
15
+ status;
16
+ constructor(message, code, status) {
15
17
  super(message);
16
- this.exitCode = exitCode;
17
- this.stderr = stderr;
18
- this.name = "GetnoteCliError";
18
+ this.code = code;
19
+ this.status = status;
20
+ this.name = "GetnoteApiError";
19
21
  }
20
22
  };
21
- function resolveGetnoteBinary() {
22
- const packageJson = require.resolve("@getnote/cli/package.json");
23
- const binary = process.platform === "win32" ? "getnote.exe" : "getnote";
24
- return join(dirname(packageJson), "bin", binary);
23
+ var NotLoggedInError = class extends GetnoteApiError {
24
+ constructor() {
25
+ super("Not logged in to GetNote. Call getnote_login and ask the user to open the returned link.", "not_logged_in");
26
+ this.name = "NotLoggedInError";
27
+ }
28
+ };
29
+ function defaultCredentialPath(env = process.env) {
30
+ const dshHome = env.DSH_HOME || join(homedir(), ".dsh");
31
+ return join(dshHome, "getnote", "credentials.json");
25
32
  }
26
- function resolveGetnoteFromPath(pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM") {
27
- const extensions = process.platform === "win32" ? pathExtValue.split(";").filter(Boolean) : [""];
28
- for (const directory of pathValue.split(delimiter).filter(Boolean)) for (const extension of extensions) {
29
- const candidate = join(directory, `getnote${extension.toLowerCase()}`);
33
+ /** Normalize a base URL to the `/open/api/v1` prefix, accepting the same forms as the CLI. */
34
+ function apiBase(url) {
35
+ let base = url.replace(/\/+$/, "");
36
+ if (base.endsWith("/open/api/v1")) return base;
37
+ if (base.endsWith("/open")) return `${base}/api/v1`;
38
+ return `${base}/open/api/v1`;
39
+ }
40
+ /** Credential file stored with 0600 permissions. The key never reaches the model. */
41
+ var CredentialStore = class {
42
+ path;
43
+ constructor(path) {
44
+ this.path = path;
45
+ }
46
+ async load() {
30
47
  try {
31
- accessSync(candidate, constants.X_OK);
32
- return candidate;
33
- } catch {}
48
+ const data = JSON.parse(await readFile(this.path, "utf8"));
49
+ if (typeof data.apiKey !== "string" || !data.apiKey || typeof data.clientId !== "string" || !data.clientId) return void 0;
50
+ return {
51
+ apiKey: data.apiKey,
52
+ clientId: data.clientId,
53
+ expiresAt: data.expiresAt
54
+ };
55
+ } catch {
56
+ return;
57
+ }
58
+ }
59
+ async save(credential) {
60
+ await mkdir(dirname(this.path), {
61
+ recursive: true,
62
+ mode: 448
63
+ });
64
+ const tmp = `${this.path}.${process.pid}.tmp`;
65
+ await writeFile(tmp, JSON.stringify(credential, null, 2), { mode: 384 });
66
+ await chmod(tmp, 384);
67
+ await rename(tmp, this.path);
68
+ }
69
+ async clear() {
70
+ await rm(this.path, { force: true });
71
+ }
72
+ };
73
+ /**
74
+ * Parse JSON while keeping integers beyond Number.MAX_SAFE_INTEGER as strings.
75
+ * GetNote IDs are 64-bit; a plain JSON.parse would silently corrupt them.
76
+ */
77
+ function parseJson(text) {
78
+ let out = "";
79
+ let last = 0;
80
+ let inString = false;
81
+ for (let i = 0; i < text.length; i++) {
82
+ const ch = text[i];
83
+ if (inString) {
84
+ if (ch === "\\") i++;
85
+ else if (ch === "\"") inString = false;
86
+ continue;
87
+ }
88
+ if (ch === "\"") {
89
+ inString = true;
90
+ continue;
91
+ }
92
+ if (ch === "-" || ch >= "0" && ch <= "9") {
93
+ let j = i + 1;
94
+ while (j < text.length && /[0-9.eE+-]/.test(text[j])) j++;
95
+ const token = text.slice(i, j);
96
+ if (/^-?\d+$/.test(token) && !Number.isSafeInteger(Number(token))) {
97
+ out += `${text.slice(last, i)}"${token}"`;
98
+ last = j;
99
+ }
100
+ i = j - 1;
101
+ }
34
102
  }
103
+ return JSON.parse(last === 0 ? text : out + text.slice(last));
35
104
  }
36
- function resolveGetnoteInvocation(binaryPath) {
37
- if (binaryPath) return {
38
- command: binaryPath,
39
- prefixArgs: []
40
- };
41
- const pathBinary = resolveGetnoteFromPath();
42
- if (pathBinary) return {
43
- command: pathBinary,
44
- prefixArgs: []
45
- };
46
- try {
47
- return {
48
- command: resolveGetnoteBinary(),
49
- prefixArgs: []
50
- };
51
- } catch {
52
- return {
53
- command: process.platform === "win32" ? "npx.cmd" : "npx",
54
- prefixArgs: [
55
- "--yes",
56
- "--package",
57
- "@getnote/cli@1.5.3",
58
- "--",
59
- "getnote"
60
- ]
105
+ var GetnoteApi = class {
106
+ options;
107
+ base;
108
+ fetchImpl;
109
+ constructor(options) {
110
+ this.options = options;
111
+ this.base = apiBase(options.apiUrl);
112
+ this.fetchImpl = options.fetchImpl ?? fetch;
113
+ }
114
+ /** Environment variables override the stored credential (useful for CI and testing). */
115
+ async credential() {
116
+ const env = this.options.env ?? process.env;
117
+ if (env.GETNOTE_API_KEY) return {
118
+ apiKey: env.GETNOTE_API_KEY,
119
+ clientId: env.GETNOTE_CLIENT_ID || this.options.clientId
61
120
  };
121
+ return await this.options.store.load();
62
122
  }
63
- }
64
- async function runGetnote(args, options = {}) {
65
- const invocation = resolveGetnoteInvocation(options.binaryPath);
66
- const timeoutMs = options.timeoutMs ?? 12e4;
67
- const maxOutputBytes = options.maxOutputBytes ?? 10485760;
68
- const commandArgs = [
69
- ...invocation.prefixArgs,
70
- ...args,
71
- "--output",
72
- "json"
73
- ];
74
- return await new Promise((resolve, reject) => {
75
- const child = spawn(invocation.command, commandArgs, {
76
- env: {
77
- ...process.env,
78
- ...options.apiUrl ? { GETNOTE_API_URL: options.apiUrl } : {}
123
+ async get(path, query = {}, signal) {
124
+ const qs = new URLSearchParams();
125
+ for (const [key, value] of Object.entries(query)) {
126
+ if (value === void 0 || value === null || value === "") continue;
127
+ qs.set(key, String(value));
128
+ }
129
+ const suffix = qs.size > 0 ? `?${qs.toString()}` : "";
130
+ return await this.request("GET", `${path}${suffix}`, void 0, signal);
131
+ }
132
+ async post(path, body, signal) {
133
+ return await this.request("POST", path, body, signal);
134
+ }
135
+ /** Unauthenticated OAuth call (device code / token). Returns the raw parsed body. */
136
+ async oauth(path, body, signal) {
137
+ const response = await this.fetchImpl(`${this.base}${path}`, {
138
+ method: "POST",
139
+ headers: { "Content-Type": "application/json" },
140
+ body: JSON.stringify(body),
141
+ signal: this.signal(signal)
142
+ });
143
+ const text = await response.text();
144
+ try {
145
+ return {
146
+ status: response.status,
147
+ body: parseJson(text)
148
+ };
149
+ } catch {
150
+ return {
151
+ status: response.status,
152
+ body: text
153
+ };
154
+ }
155
+ }
156
+ signal(signal) {
157
+ const timeout = AbortSignal.timeout(this.options.timeoutMs);
158
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
159
+ }
160
+ async request(method, path, body, signal) {
161
+ const credential = await this.credential();
162
+ if (!credential) throw new NotLoggedInError();
163
+ const response = await this.fetchImpl(`${this.base}${path}`, {
164
+ method,
165
+ headers: {
166
+ Authorization: `Bearer ${credential.apiKey}`,
167
+ "X-Client-ID": credential.clientId,
168
+ "Content-Type": "application/json"
79
169
  },
80
- stdio: [
81
- "ignore",
82
- "pipe",
83
- "pipe"
84
- ],
85
- windowsHide: true,
86
- signal: options.signal
170
+ body: body === void 0 ? void 0 : JSON.stringify(body),
171
+ signal: this.signal(signal)
87
172
  });
88
- const stdout = [];
89
- const stderr = [];
90
- let outputBytes = 0;
91
- let settled = false;
92
- let timer;
93
- const finish = (callback) => {
94
- if (settled) return;
95
- settled = true;
96
- if (timer !== void 0) clearTimeout(timer);
97
- callback();
98
- };
99
- const capture = (target, chunk) => {
100
- outputBytes += chunk.length;
101
- if (outputBytes > maxOutputBytes) {
102
- child.kill("SIGTERM");
103
- finish(() => reject(new GetnoteCliError(`getnote output exceeded ${maxOutputBytes} bytes`, null, Buffer.concat(stderr).toString("utf8"))));
104
- return;
105
- }
106
- target.push(chunk);
173
+ const text = await response.text();
174
+ let parsed;
175
+ try {
176
+ parsed = parseJson(text);
177
+ } catch {
178
+ throw new GetnoteApiError(`GetNote API returned HTTP ${response.status}: ${text.slice(0, 300)}`, void 0, response.status);
179
+ }
180
+ if (parsed.success === true) return parsed.data ?? null;
181
+ if (parsed.h && parsed.h.c === 0) return parsed.c ?? null;
182
+ const code = parsed.error?.code ?? parsed.h?.c;
183
+ const message = parsed.error?.message ?? parsed.h?.e ?? `GetNote API request failed (HTTP ${response.status})`;
184
+ if (response.status === 401 || code === 10004 || code === "unauthorized") throw new GetnoteApiError(`${message}. The GetNote authorization is missing, expired, or revoked; call getnote_login to authorize again.`, code, response.status);
185
+ throw new GetnoteApiError(describeError(String(message), code, parsed.error ?? void 0, response), code, response.status);
186
+ }
187
+ };
188
+ /** Add the guidance the model needs for quota, rate-limit and membership errors. */
189
+ function describeError(message, code, error, response) {
190
+ const parts = [message];
191
+ if (error?.reason) parts.push(`(reason: ${error.reason})`);
192
+ if (code === 10201 || error?.reason === "not_member") parts.push(`This operation needs a GetNote membership: ${MEMBERSHIP_URL}`);
193
+ else if (response.status === 429 || code === 10202 || code === 10005) {
194
+ const header = Number(response.headers.get("Retry-After"));
195
+ const wait = error?.retry_after_seconds ?? error?.rate_limit_detail?.retry_after_seconds ?? (Number.isFinite(header) && header > 0 ? header : void 0);
196
+ const when = wait !== void 0 ? ` Retry after about ${wait} seconds.` : "";
197
+ parts.push(`Rate limit or quota reached.${when} Do not retry repeatedly; call getnote_quota to see the current quota.`);
198
+ }
199
+ return parts.join(" ");
200
+ }
201
+ /**
202
+ * RFC 8628-style device authorization against the GetNote OpenAPI. `start()`
203
+ * returns the link immediately; polling continues in the background and stores
204
+ * the credential once the user confirms in the browser.
205
+ */
206
+ var DeviceLogin = class {
207
+ api;
208
+ sleep;
209
+ pending;
210
+ lastResult;
211
+ lastError;
212
+ constructor(api, sleep = defaultSleep) {
213
+ this.api = api;
214
+ this.sleep = sleep;
215
+ }
216
+ get inProgress() {
217
+ return this.pending?.start;
218
+ }
219
+ async start(signal) {
220
+ if (this.pending) return this.pending.start;
221
+ const clientId = this.api.options.clientId;
222
+ const { body } = await this.api.oauth("/oauth/device/code", { client_id: clientId }, signal);
223
+ const data = typeof body === "object" && body ? body.data : void 0;
224
+ if (!data || typeof data.code !== "string" || typeof data.verification_uri !== "string") throw new GetnoteApiError(`Could not start GetNote authorization: ${(typeof body === "object" && body ? body.error?.message : String(body).slice(0, 200)) ?? "unexpected response"}`);
225
+ const start = {
226
+ verificationUri: data.verification_uri,
227
+ userCode: String(data.user_code ?? ""),
228
+ expiresIn: Number(data.expires_in ?? 600)
107
229
  };
108
- child.stdout.on("data", (chunk) => capture(stdout, chunk));
109
- child.stderr.on("data", (chunk) => capture(stderr, chunk));
110
- timer = setTimeout(() => {
111
- child.kill("SIGTERM");
112
- finish(() => reject(new GetnoteCliError(`getnote command timed out after ${timeoutMs} ms`, null, Buffer.concat(stderr).toString("utf8"))));
113
- }, timeoutMs);
114
- child.on("error", (error) => {
115
- finish(() => reject(new GetnoteCliError(`failed to start getnote: ${error.message}`, null, Buffer.concat(stderr).toString("utf8"))));
230
+ const intervalMs = Math.max(1, Number(data.interval ?? 5)) * 1e3;
231
+ const controller = new AbortController();
232
+ this.lastResult = void 0;
233
+ this.lastError = void 0;
234
+ const done = this.poll(clientId, data.code, intervalMs, start.expiresIn * 1e3, controller.signal).finally(() => {
235
+ this.pending = void 0;
116
236
  });
117
- child.on("close", (code) => {
118
- finish(() => {
119
- const stdoutText = Buffer.concat(stdout).toString("utf8").trim();
120
- const stderrText = Buffer.concat(stderr).toString("utf8").trim();
121
- if (code !== 0) {
122
- reject(new GetnoteCliError(stderrText || stdoutText || `getnote exited with code ${String(code)}`, code, stderrText));
237
+ this.pending = {
238
+ start,
239
+ done,
240
+ controller
241
+ };
242
+ return start;
243
+ }
244
+ /** Wait for the current background login (tests and graceful shutdown). */
245
+ async wait() {
246
+ await this.pending?.done;
247
+ }
248
+ cancel() {
249
+ this.pending?.controller.abort();
250
+ }
251
+ async poll(clientId, code, intervalMs, ttlMs, signal) {
252
+ const deadline = Date.now() + ttlMs;
253
+ try {
254
+ while (Date.now() < deadline) {
255
+ await this.sleep(intervalMs, signal);
256
+ let result;
257
+ try {
258
+ result = await this.api.oauth("/oauth/token", {
259
+ grant_type: "device_code",
260
+ client_id: clientId,
261
+ code
262
+ }, signal);
263
+ } catch {
264
+ if (signal.aborted) return;
265
+ continue;
266
+ }
267
+ const raw = typeof result.body === "string" ? result.body : JSON.stringify(result.body);
268
+ if (raw.includes("authorization_pending") || raw.includes("slow_down")) continue;
269
+ if (raw.includes("rejected")) {
270
+ this.lastResult = "rejected";
123
271
  return;
124
272
  }
125
- if (!stdoutText) {
126
- resolve(null);
273
+ if (raw.includes("expired_token") || raw.includes("already_consumed")) {
274
+ this.lastResult = "expired";
127
275
  return;
128
276
  }
129
- try {
130
- resolve(JSON.parse(stdoutText));
131
- } catch {
132
- resolve(stdoutText);
277
+ const data = typeof result.body === "object" ? result.body.data : void 0;
278
+ if (typeof result.body === "object" && result.body.success && data && typeof data.api_key === "string" && data.api_key) {
279
+ await this.api.options.store.save({
280
+ apiKey: data.api_key,
281
+ clientId: typeof data.client_id === "string" && data.client_id ? data.client_id : clientId,
282
+ expiresAt: typeof data.expires_at === "number" ? data.expires_at : void 0
283
+ });
284
+ this.lastResult = "authorized";
285
+ return;
133
286
  }
134
- });
135
- });
287
+ }
288
+ this.lastResult = "expired";
289
+ } catch (error) {
290
+ if (signal.aborted) return;
291
+ this.lastResult = "failed";
292
+ this.lastError = error instanceof Error ? error.message : String(error);
293
+ }
294
+ }
295
+ };
296
+ function defaultSleep(ms, signal) {
297
+ return new Promise((resolve, reject) => {
298
+ if (signal.aborted) {
299
+ reject(signal.reason);
300
+ return;
301
+ }
302
+ const timer = setTimeout(resolve, ms);
303
+ timer.unref?.();
304
+ signal.addEventListener("abort", () => {
305
+ clearTimeout(timer);
306
+ reject(signal.reason);
307
+ }, { once: true });
136
308
  });
137
309
  }
138
310
  //#endregion
@@ -140,24 +312,11 @@ async function runGetnote(args, options = {}) {
140
312
  const name = "getnote-tools";
141
313
  const inject = ["tools", "skills"];
142
314
  const Config = Schema.object({
143
- binaryPath: Schema.string().description("Optional absolute path to the getnote executable."),
144
- apiUrl: Schema.string().description("Optional GetNote OpenAPI base URL for explicit integration testing."),
145
- timeoutMs: Schema.number().min(1e3).default(12e4),
146
- maxOutputBytes: Schema.number().min(1024).default(10485760)
315
+ apiUrl: Schema.string().default(DEFAULT_API_URL).description("GetNote OpenAPI base URL. Change only for integration testing."),
316
+ clientId: Schema.string().default(DSH_CLIENT_ID).description("OpenAPI client ID used for authorization."),
317
+ credentialPath: Schema.string().description("Where the authorized API key is stored. Default: $DSH_HOME/getnote/credentials.json."),
318
+ timeoutMs: Schema.number().min(1e3).default(6e4)
147
319
  });
148
- function renderJson(value) {
149
- if (typeof value === "string") return value;
150
- return JSON.stringify(value, null, 2);
151
- }
152
- function runnerOptions(config, signal) {
153
- return {
154
- binaryPath: config.binaryPath,
155
- apiUrl: config.apiUrl,
156
- timeoutMs: config.timeoutMs,
157
- maxOutputBytes: config.maxOutputBytes,
158
- signal
159
- };
160
- }
161
320
  function textOutput() {
162
321
  return {
163
322
  schema: { type: "string" },
@@ -167,30 +326,218 @@ function textOutput() {
167
326
  }]
168
327
  };
169
328
  }
329
+ function renderJson(value) {
330
+ if (typeof value === "string") return value;
331
+ return JSON.stringify(value, null, 2);
332
+ }
170
333
  function integerInRange(value, fallback, min, max) {
171
334
  const resolved = value ?? fallback;
335
+ if (resolved === void 0) return void 0;
172
336
  if (!Number.isInteger(resolved) || resolved < min || resolved > max) throw new RangeError(`value must be an integer between ${min} and ${max}`);
173
337
  return resolved;
174
338
  }
175
- function apply(ctx, config) {
339
+ function ids(values, label, max) {
340
+ const list = [...new Set((values ?? []).map((v) => v.trim()).filter(Boolean))];
341
+ if (list.length === 0) throw new RangeError(`${label} must contain at least one ID`);
342
+ if (list.length > max) throw new RangeError(`${label} accepts at most ${max} IDs`);
343
+ return list;
344
+ }
345
+ const URL_PATTERN = /^https?:\/\/\S+$/i;
346
+ /**
347
+ * Tools that delete, publish, or overwrite user data. The plugin asks the user
348
+ * (DSH approval) before dispatching them; without an approval seam DSH turns
349
+ * the ask into a denial, so these never run unattended.
350
+ */
351
+ function confirmationReason(toolName, args) {
352
+ const a = args ?? {};
353
+ switch (toolName) {
354
+ case "getnote_delete_note": return `删除得到大脑笔记 ${String(a.note_id)}(移入回收站)`;
355
+ case "getnote_share_note": return `公开分享笔记 ${String(a.note_id)},任何拿到链接的人都能查看`;
356
+ case "getnote_update_note": {
357
+ const parts = [];
358
+ if (a.content !== void 0) parts.push("替换正文");
359
+ if (a.tags !== void 0) parts.push("替换全部标签");
360
+ return parts.length > 0 ? `${parts.join("并")}:笔记 ${String(a.note_id)}` : void 0;
361
+ }
362
+ case "getnote_kb_remove_notes": return `把 ${Array.isArray(a.note_ids) ? a.note_ids.length : 0} 条笔记移出知识库 ${String(a.topic_id)}`;
363
+ default: return;
364
+ }
365
+ }
366
+ const noteId = {
367
+ type: "string",
368
+ required: true,
369
+ description: "Note ID. Always keep it as a string."
370
+ };
371
+ const topicId = {
372
+ type: "string",
373
+ required: true,
374
+ description: "Knowledge base ID (topic_id) from getnote_list_knowledge_bases."
375
+ };
376
+ const noteFilters = {
377
+ note_type: {
378
+ type: "string",
379
+ enum: [
380
+ "plain_text",
381
+ "link",
382
+ "img_text",
383
+ "ref",
384
+ "audio",
385
+ "local_audio",
386
+ "class_audio",
387
+ "meeting",
388
+ "internal_record",
389
+ "recorder_audio",
390
+ "recorder_flash_audio"
391
+ ],
392
+ description: "Exact note type. plain_text=文本, link=链接, img_text=图片, ref=引用, audio=即时录音, local_audio=上传音频, class_audio=课堂录音, meeting=会议(含录音台/耳机), internal_record=内录, recorder_audio/recorder_flash_audio=录音卡长录音/闪念."
393
+ },
394
+ source: {
395
+ type: "string",
396
+ description: "Exact note source, e.g. vendor_moan=录音台, getseed=录音卡, dedao=得到."
397
+ },
398
+ created_from: {
399
+ type: "string",
400
+ description: "Created at or after this RFC3339 time (inclusive)."
401
+ },
402
+ created_to: {
403
+ type: "string",
404
+ description: "Created before this RFC3339 time (exclusive)."
405
+ },
406
+ edited_from: {
407
+ type: "string",
408
+ description: "Edited at or after this RFC3339 time (inclusive)."
409
+ },
410
+ edited_to: {
411
+ type: "string",
412
+ description: "Edited before this RFC3339 time (exclusive)."
413
+ }
414
+ };
415
+ function filterQuery(a) {
416
+ return {
417
+ note_type: a.note_type,
418
+ source: a.source,
419
+ created_from: a.created_from,
420
+ created_to: a.created_to,
421
+ edited_from: a.edited_from,
422
+ edited_to: a.edited_to
423
+ };
424
+ }
425
+ function hasFilters(a) {
426
+ return Object.values(filterQuery(a)).some((v) => v !== void 0 && v !== "");
427
+ }
428
+ /**
429
+ * The unfiltered note list returns a fixed page (20) regardless of `limit`.
430
+ * Trim it like the CLI does and continue from the last returned note.
431
+ */
432
+ function trimPage(page, limit) {
433
+ const data = page;
434
+ if (!data || !Array.isArray(data.notes) || data.notes.length <= limit) return page;
435
+ const notes = data.notes.slice(0, limit);
436
+ const last = notes[notes.length - 1];
437
+ const cursor = String(last?.note_id || last?.id || "");
438
+ return {
439
+ ...data,
440
+ notes,
441
+ cursor,
442
+ next_cursor: cursor,
443
+ has_more: true
444
+ };
445
+ }
446
+ function createRuntime(config, fetchImpl) {
447
+ const store = new CredentialStore(config.credentialPath || defaultCredentialPath());
448
+ const api = new GetnoteApi({
449
+ apiUrl: config.apiUrl || "https://openapi.biji.com",
450
+ clientId: config.clientId || "cli_35ca47aab229ebb0c4c4dd12",
451
+ store,
452
+ timeoutMs: config.timeoutMs ?? 6e4,
453
+ fetchImpl
454
+ });
455
+ return {
456
+ api,
457
+ login: new DeviceLogin(api)
458
+ };
459
+ }
460
+ function apply(ctx, config, runtime = createRuntime(config)) {
461
+ const { api, login } = runtime;
176
462
  apply$1(ctx, {
177
463
  providerName: "getnote",
178
464
  includeDefaultRoots: false,
179
465
  bundledSkillDir: fileURLToPath(new URL("../skills", import.meta.url))
180
466
  });
181
- ctx.tools.register(defineTool({
467
+ ctx.on("tools/pre-execute", async (exec, next) => {
468
+ const reason = confirmationReason(exec.name, exec.arguments);
469
+ if (reason) return {
470
+ kind: "ask",
471
+ reason
472
+ };
473
+ return next();
474
+ });
475
+ ctx.effect(() => () => login.cancel(), "getnote device login");
476
+ function tool(def) {
477
+ ctx.tools.register(defineTool({
478
+ name: def.name,
479
+ description: def.description,
480
+ parameters: def.parameters,
481
+ output: textOutput(),
482
+ ...def.readOnly ? { isConcurrencySafe: () => true } : {},
483
+ async execute(args, exec) {
484
+ return renderJson(await def.run(args, exec.signal));
485
+ }
486
+ }));
487
+ }
488
+ tool({
489
+ name: "getnote_login",
490
+ description: "Start GetNote (得到大脑) authorization. Returns a link and a code; show both to the user and ask them to open the link, log in, and confirm. The plugin finishes in the background; then call getnote_auth_status.",
491
+ parameters: {},
492
+ async run(_args, signal) {
493
+ if (await api.credential()) return "Already authorized with GetNote. To switch accounts, call getnote_logout first.";
494
+ const start = await login.start(signal);
495
+ const minutes = Math.max(1, Math.round(start.expiresIn / 60));
496
+ return [
497
+ "Ask the user to open this link, log in to 得到大脑, and confirm the authorization:",
498
+ start.verificationUri,
499
+ `Confirmation code shown on the page: ${start.userCode}`,
500
+ `The link expires in about ${minutes} minutes. After the user confirms, call getnote_auth_status.`
501
+ ].join("\n");
502
+ }
503
+ });
504
+ tool({
182
505
  name: "getnote_auth_status",
183
- description: "Check whether the current user is authenticated with GetNote (得到大脑).",
506
+ description: "Check whether GetNote is authorized and the authorization still works.",
184
507
  parameters: {},
185
- output: textOutput(),
186
- async execute(_args, exec) {
187
- await runGetnote(["auth", "status"], runnerOptions(config, exec.signal));
188
- return "Authenticated with GetNote.";
508
+ readOnly: true,
509
+ async run(_args, signal) {
510
+ if (!await api.credential()) {
511
+ if (login.inProgress) return `Authorization pending: the user has not confirmed yet. Link: ${login.inProgress.verificationUri}`;
512
+ if (login.lastResult === "rejected") return "The user rejected the authorization. Call getnote_login to try again.";
513
+ if (login.lastResult === "expired") return "The authorization link expired. Call getnote_login to get a new one.";
514
+ if (login.lastResult === "failed") return `Authorization failed: ${login.lastError ?? "unknown error"}. Call getnote_login to try again.`;
515
+ return "Not authorized. Call getnote_login.";
516
+ }
517
+ await api.get("/resource/rate-limit/quota", {}, signal);
518
+ return "Authorized with GetNote.";
189
519
  }
190
- }));
191
- ctx.tools.register(defineTool({
520
+ });
521
+ tool({
522
+ name: "getnote_logout",
523
+ description: "Remove the locally stored GetNote authorization. It does not revoke the grant on the server; the user can revoke it in the GetNote account settings.",
524
+ parameters: {},
525
+ async run() {
526
+ login.cancel();
527
+ await api.options.store.clear();
528
+ return "Local GetNote authorization removed.";
529
+ }
530
+ });
531
+ tool({
532
+ name: "getnote_quota",
533
+ description: "Show the account's current API quota and usage. All users can call the API; members have higher quotas.",
534
+ parameters: {},
535
+ readOnly: true,
536
+ run: (_a, signal) => api.get("/resource/rate-limit/quota", {}, signal)
537
+ });
538
+ tool({
192
539
  name: "getnote_search",
193
- description: "Semantically search notes in GetNote, optionally within one knowledge base.",
540
+ description: "Semantically search the user's notes, optionally within one knowledge base.",
194
541
  parameters: {
195
542
  query: {
196
543
  type: "string",
@@ -199,104 +546,400 @@ function apply(ctx, config) {
199
546
  },
200
547
  knowledge_base_id: {
201
548
  type: "string",
202
- description: "Optional knowledge base/topic ID."
549
+ description: "Optional knowledge base (topic) ID."
203
550
  },
204
551
  limit: {
205
552
  type: "integer",
206
553
  default: 10,
207
- description: "Maximum results, from 1 to 10."
554
+ description: "Maximum results, 1-10."
555
+ },
556
+ snippet_chars: {
557
+ type: "integer",
558
+ description: "Return snippets of at most this many characters (100-1000) instead of full bodies, to keep results compact."
208
559
  }
209
560
  },
210
- output: textOutput(),
211
- async execute(args, exec) {
212
- const limit = integerInRange(args.limit, 10, 1, 10);
213
- const cliArgs = [
214
- "search",
215
- args.query,
216
- "--limit",
217
- String(limit)
218
- ];
219
- if (args.knowledge_base_id) cliArgs.push("--kb", args.knowledge_base_id);
220
- return renderJson(await runGetnote(cliArgs, runnerOptions(config, exec.signal)));
561
+ readOnly: true,
562
+ async run(a, signal) {
563
+ const body = {
564
+ query: a.query,
565
+ top_k: integerInRange(a.limit, 10, 1, 10)
566
+ };
567
+ const snippet = integerInRange(a.snippet_chars, void 0, 100, 1e3);
568
+ if (snippet !== void 0) Object.assign(body, {
569
+ response_mode: "snippet",
570
+ max_snippet_chars: snippet
571
+ });
572
+ if (a.knowledge_base_id) {
573
+ body.topic_id = a.knowledge_base_id;
574
+ return await api.post("/resource/recall/knowledge", body, signal);
575
+ }
576
+ return await api.post("/resource/recall", body, signal);
577
+ }
578
+ });
579
+ tool({
580
+ name: "getnote_list_notes",
581
+ description: "List the user's notes, newest first, with optional filters. Paginate with next_cursor from the previous page. If a note's generation_status is present and not \"completed\", its content may be empty or partial; do not treat it as final, read the note again later.",
582
+ parameters: {
583
+ limit: {
584
+ type: "integer",
585
+ default: 20,
586
+ description: "Notes per page, 1-100."
587
+ },
588
+ cursor: {
589
+ type: "string",
590
+ description: "next_cursor returned by the previous page."
591
+ },
592
+ topic_id: {
593
+ type: "string",
594
+ description: "Only notes in this knowledge base."
595
+ },
596
+ ...noteFilters
597
+ },
598
+ readOnly: true,
599
+ async run(a, signal) {
600
+ const size = integerInRange(a.limit, 20, 1, 100);
601
+ const filtered = hasFilters(a) || Boolean(a.topic_id);
602
+ const page = await api.get("/resource/note/list", {
603
+ ...filtered ? { page_size: size } : { limit: size },
604
+ cursor: a.cursor,
605
+ topic_id: a.topic_id,
606
+ ...filterQuery(a)
607
+ }, signal);
608
+ return filtered ? page : trimPage(page, size);
221
609
  }
222
- }));
223
- ctx.tools.register(defineTool({
610
+ });
611
+ tool({
612
+ name: "getnote_get_note",
613
+ description: "Get one note in full by its string ID, including its tags (with tag IDs). For very long notes use getnote_note_outline and getnote_note_section instead. If a note's generation_status is present and not \"completed\", its content may be empty or partial; do not treat it as final, read the note again later.",
614
+ parameters: { note_id: noteId },
615
+ readOnly: true,
616
+ run: (a, signal) => api.get("/resource/note/detail", { id: a.note_id }, signal)
617
+ });
618
+ tool({
619
+ name: "getnote_note_outline",
620
+ description: "Read the outline of a long note: headings with UTF-16 offsets and a version. Use it before getnote_note_section.",
621
+ parameters: { note_id: noteId },
622
+ readOnly: true,
623
+ run: (a, signal) => api.get("/resource/note/outline", { id: a.note_id }, signal)
624
+ });
625
+ tool({
626
+ name: "getnote_note_section",
627
+ description: "Read part of a long note, at an offset returned by getnote_note_outline or around literal keywords. Never compute offsets yourself; if the version changed, read the outline again.",
628
+ parameters: {
629
+ note_id: noteId,
630
+ keyword: {
631
+ type: "string",
632
+ description: "Literal keyword(s), alternatives separated by |. Not semantic search."
633
+ },
634
+ offset: {
635
+ type: "integer",
636
+ description: "UTF-16 offset returned by the outline or a previous section."
637
+ },
638
+ limit: {
639
+ type: "integer",
640
+ description: "UTF-16 units to read (or keyword search window), 1-30000. Default 8000."
641
+ },
642
+ version: {
643
+ type: "string",
644
+ description: "Version returned by the outline."
645
+ }
646
+ },
647
+ readOnly: true,
648
+ run: (a, signal) => api.get("/resource/note/section", {
649
+ id: a.note_id,
650
+ keyword: a.keyword,
651
+ offset: integerInRange(a.offset, void 0, 0, 3e6),
652
+ limit: integerInRange(a.limit, void 0, 1, 3e4),
653
+ version: a.version
654
+ }, signal)
655
+ });
656
+ tool({
657
+ name: "getnote_read_notes",
658
+ description: "Read several notes at once within a character budget. Notes that do not fit are listed in pending_ids; read them in a follow-up call.",
659
+ parameters: {
660
+ note_ids: {
661
+ type: "array",
662
+ required: true,
663
+ items: { type: "string" },
664
+ description: "Note IDs (strings), 1-20."
665
+ },
666
+ fields: {
667
+ type: "array",
668
+ items: {
669
+ type: "string",
670
+ enum: [
671
+ "content",
672
+ "ref_content",
673
+ "reference",
674
+ "original"
675
+ ]
676
+ },
677
+ description: "Fields to return; original (transcript/original text) is opt-in."
678
+ },
679
+ max_total_chars: {
680
+ type: "integer",
681
+ description: "Total character budget, 1-64000 (server default 32000)."
682
+ }
683
+ },
684
+ readOnly: true,
685
+ run: (a, signal) => api.post("/resource/note/batch-detail", {
686
+ ids: ids(a.note_ids, "note_ids", 20),
687
+ ...a.fields && a.fields.length > 0 ? { fields: a.fields } : {},
688
+ ...a.max_total_chars !== void 0 ? { max_total_chars: integerInRange(a.max_total_chars, void 0, 1, 64e3) } : {}
689
+ }, signal)
690
+ });
691
+ tool({
692
+ name: "getnote_task_status",
693
+ description: "Check an asynchronous save task (e.g. a saved link) and get the resulting note ID.",
694
+ parameters: { task_id: {
695
+ type: "string",
696
+ required: true,
697
+ description: "task_id returned by getnote_save."
698
+ } },
699
+ readOnly: true,
700
+ run: (a, signal) => api.post("/resource/note/task/progress", { task_id: a.task_id }, signal)
701
+ });
702
+ tool({
224
703
  name: "getnote_save",
225
- description: "Save text, a URL, or a local image path as a note in GetNote.",
704
+ description: "Save a text note, a web link (processed asynchronously; check getnote_task_status), or images by HTTPS URL. Local image files are not supported.",
226
705
  parameters: {
227
706
  content: {
228
707
  type: "string",
229
- required: true,
230
- description: "Text, URL, or local image path to save."
708
+ description: "Note text, or a single http(s) URL to save as a link note."
709
+ },
710
+ image_urls: {
711
+ type: "array",
712
+ items: { type: "string" },
713
+ description: "HTTPS image URLs to save as an image note."
231
714
  },
232
715
  title: {
233
716
  type: "string",
234
- description: "Optional note title."
717
+ description: "Optional title."
235
718
  },
236
719
  tags: {
237
720
  type: "array",
238
721
  items: { type: "string" },
239
- description: "Optional note tags."
722
+ description: "Optional tags."
723
+ },
724
+ topic_id: {
725
+ type: "string",
726
+ description: "Save directly into this knowledge base."
727
+ },
728
+ parent_id: {
729
+ type: "string",
730
+ description: "Create as a child note of this note."
731
+ },
732
+ idempotency_key: {
733
+ type: "string",
734
+ description: "Reuse the same key (1-128 ASCII chars) when retrying the same save to avoid duplicates."
240
735
  }
241
736
  },
242
- output: textOutput(),
243
- async execute(args, exec) {
244
- const cliArgs = ["save", args.content];
245
- if (args.title) cliArgs.push("--title", args.title);
246
- for (const tag of args.tags ?? []) cliArgs.push("--tag", tag);
247
- return renderJson(await runGetnote(cliArgs, runnerOptions(config, exec.signal)));
737
+ async run(a, signal) {
738
+ const content = a.content?.trim() ?? "";
739
+ const images = (a.image_urls ?? []).map((u) => u.trim()).filter(Boolean);
740
+ let body;
741
+ if (images.length > 0) {
742
+ if (images.some((u) => !/^https:\/\//i.test(u))) throw new RangeError("image_urls must be https URLs");
743
+ body = {
744
+ note_type: "img_text",
745
+ image_urls: images,
746
+ ...content ? { content } : {}
747
+ };
748
+ } else if (URL_PATTERN.test(content)) body = {
749
+ note_type: "link",
750
+ link_url: content
751
+ };
752
+ else if (content) body = {
753
+ note_type: "plain_text",
754
+ content: a.content
755
+ };
756
+ else throw new RangeError("provide content or image_urls");
757
+ if (a.idempotency_key !== void 0 && !/^[\x21-\x7e]{1,128}$/.test(a.idempotency_key)) throw new RangeError("idempotency_key must be 1-128 printable ASCII characters");
758
+ return await api.post("/resource/note/save", {
759
+ ...body,
760
+ title: a.title || void 0,
761
+ tags: a.tags && a.tags.length > 0 ? a.tags : void 0,
762
+ topic_id: a.topic_id || void 0,
763
+ parent_id: a.parent_id || void 0,
764
+ client_request_id: a.idempotency_key || void 0
765
+ }, signal);
248
766
  }
249
- }));
250
- ctx.tools.register(defineTool({
251
- name: "getnote_list_notes",
252
- description: "List recent notes from GetNote.",
767
+ });
768
+ tool({
769
+ name: "getnote_update_note",
770
+ description: "Update a note's title, body (plain-text notes only), or full tag list. Replacing the body or all tags requires user confirmation.",
253
771
  parameters: {
254
- limit: {
255
- type: "integer",
256
- default: 20,
257
- description: "Number of notes, from 1 to 100."
772
+ note_id: noteId,
773
+ title: {
774
+ type: "string",
775
+ description: "New title."
258
776
  },
259
- since_id: {
777
+ content: {
260
778
  type: "string",
261
- description: "Optional pagination cursor note ID."
779
+ description: "New full body; replaces the existing body. Plain-text notes only."
780
+ },
781
+ tags: {
782
+ type: "array",
783
+ items: { type: "string" },
784
+ description: "New complete tag list; replaces all existing tags."
262
785
  }
263
786
  },
264
- output: textOutput(),
265
- async execute(args, exec) {
266
- const limit = integerInRange(args.limit, 20, 1, 100);
267
- const cliArgs = [
268
- "notes",
269
- "--limit",
270
- String(limit)
271
- ];
272
- if (args.since_id) cliArgs.push("--since-id", args.since_id);
273
- return renderJson(await runGetnote(cliArgs, runnerOptions(config, exec.signal)));
787
+ async run(a, signal) {
788
+ if (a.title === void 0 && a.content === void 0 && a.tags === void 0) throw new RangeError("provide title, content, or tags");
789
+ return await api.post("/resource/note/update", {
790
+ id: a.note_id,
791
+ ...a.title !== void 0 ? { title: a.title } : {},
792
+ ...a.content !== void 0 ? { content: a.content } : {},
793
+ ...a.tags !== void 0 ? { tags: a.tags } : {}
794
+ }, signal);
274
795
  }
275
- }));
276
- ctx.tools.register(defineTool({
277
- name: "getnote_get_note",
278
- description: "Get the complete details of one GetNote note by its string ID.",
279
- parameters: { note_id: {
280
- type: "string",
281
- required: true,
282
- description: "Note ID. Keep it as a string."
283
- } },
284
- output: textOutput(),
285
- async execute(args, exec) {
286
- return renderJson(await runGetnote(["note", args.note_id], runnerOptions(config, exec.signal)));
796
+ });
797
+ tool({
798
+ name: "getnote_add_note_tags",
799
+ description: "Add tags to a note, keeping its existing tags.",
800
+ parameters: {
801
+ note_id: noteId,
802
+ tags: {
803
+ type: "array",
804
+ required: true,
805
+ items: { type: "string" },
806
+ description: "Tag names to add."
807
+ }
808
+ },
809
+ async run(a, signal) {
810
+ const tags = [...new Set(a.tags.map((t) => t.trim()).filter(Boolean))];
811
+ if (tags.length === 0) throw new RangeError("tags must not be empty");
812
+ return await api.post("/resource/note/tags/add", {
813
+ note_id: a.note_id,
814
+ tags
815
+ }, signal);
287
816
  }
288
- }));
289
- ctx.tools.register(defineTool({
817
+ });
818
+ tool({
819
+ name: "getnote_remove_note_tag",
820
+ description: "Remove one tag from a note by tag ID (from getnote_get_note).",
821
+ parameters: {
822
+ note_id: noteId,
823
+ tag_id: {
824
+ type: "string",
825
+ required: true,
826
+ description: "Tag ID."
827
+ }
828
+ },
829
+ run: (a, signal) => api.post("/resource/note/tags/delete", {
830
+ note_id: a.note_id,
831
+ tag_id: a.tag_id
832
+ }, signal)
833
+ });
834
+ tool({
835
+ name: "getnote_delete_note",
836
+ description: "Move a note to the recycle bin (restorable in the GetNote App). Requires user confirmation.",
837
+ parameters: { note_id: noteId },
838
+ run: (a, signal) => api.post("/resource/note/delete", { note_id: a.note_id }, signal)
839
+ });
840
+ tool({
841
+ name: "getnote_share_note",
842
+ description: "Make a note public and return its share link; anyone with the link can read it. Requires user confirmation.",
843
+ parameters: {
844
+ note_id: noteId,
845
+ exclude_audio: {
846
+ type: "boolean",
847
+ description: "Do not include the audio in the shared note."
848
+ }
849
+ },
850
+ run: (a, signal) => api.post("/resource/note/sharing", {
851
+ note_id: a.note_id,
852
+ share_exclude_audio: Boolean(a.exclude_audio)
853
+ }, signal)
854
+ });
855
+ tool({
290
856
  name: "getnote_list_knowledge_bases",
291
- description: "List the current user's GetNote knowledge bases.",
292
- parameters: {},
293
- output: textOutput(),
294
- async execute(_args, exec) {
295
- return renderJson(await runGetnote(["kbs"], runnerOptions(config, exec.signal)));
296
- }
297
- }));
857
+ description: "List the user's own knowledge bases, or the ones the user subscribes to.",
858
+ parameters: {
859
+ subscribed: {
860
+ type: "boolean",
861
+ description: "List subscribed knowledge bases instead of the user's own."
862
+ },
863
+ scope: {
864
+ type: "string",
865
+ enum: [
866
+ "DEFAULT",
867
+ "CUSTOMER",
868
+ "BOOKSPACE",
869
+ "TEAMSPACE"
870
+ ],
871
+ description: "Knowledge base type. Default DEFAULT."
872
+ },
873
+ page: {
874
+ type: "integer",
875
+ description: "Page number, starting from 1."
876
+ }
877
+ },
878
+ readOnly: true,
879
+ run: (a, signal) => api.get(a.subscribed ? "/resource/knowledge/subscribe/list" : "/resource/knowledge/list", {
880
+ page: integerInRange(a.page, 1, 1, 1e5),
881
+ scope: a.scope ?? "DEFAULT"
882
+ }, signal)
883
+ });
884
+ tool({
885
+ name: "getnote_list_kb_notes",
886
+ description: "List the notes in one knowledge base, with optional filters. If a note's generation_status is present and not \"completed\", its content may be empty or partial; do not treat it as final, read the note again later.",
887
+ parameters: {
888
+ topic_id: topicId,
889
+ page: {
890
+ type: "integer",
891
+ description: "Page number, starting from 1."
892
+ },
893
+ page_size: {
894
+ type: "integer",
895
+ description: "Notes per page, 1-100."
896
+ },
897
+ ...noteFilters
898
+ },
899
+ readOnly: true,
900
+ run: (a, signal) => api.get("/resource/knowledge/notes", {
901
+ topic_id: a.topic_id,
902
+ page: integerInRange(a.page, 1, 1, 1e5),
903
+ page_size: integerInRange(a.page_size, void 0, 1, 100),
904
+ ...filterQuery(a)
905
+ }, signal)
906
+ });
907
+ tool({
908
+ name: "getnote_kb_add_notes",
909
+ description: "Add notes to a knowledge base. At most 20 per call.",
910
+ parameters: {
911
+ topic_id: topicId,
912
+ note_ids: {
913
+ type: "array",
914
+ required: true,
915
+ items: { type: "string" },
916
+ description: "Note IDs (strings), 1-20."
917
+ }
918
+ },
919
+ run: (a, signal) => api.post("/resource/knowledge/note/batch-add", {
920
+ topic_id: a.topic_id,
921
+ note_ids: ids(a.note_ids, "note_ids", 20)
922
+ }, signal)
923
+ });
924
+ tool({
925
+ name: "getnote_kb_remove_notes",
926
+ description: "Remove notes from a knowledge base; the notes themselves are kept. At most 20 per call. Requires user confirmation.",
927
+ parameters: {
928
+ topic_id: topicId,
929
+ note_ids: {
930
+ type: "array",
931
+ required: true,
932
+ items: { type: "string" },
933
+ description: "Note IDs (strings), 1-20."
934
+ }
935
+ },
936
+ run: (a, signal) => api.post("/resource/knowledge/note/remove", {
937
+ topic_id: a.topic_id,
938
+ note_ids: ids(a.note_ids, "note_ids", 20)
939
+ }, signal)
940
+ });
298
941
  }
299
942
  //#endregion
300
- export { Config, GetnoteCliError, apply, inject, name, resolveGetnoteBinary, resolveGetnoteFromPath, runGetnote };
943
+ export { Config, CredentialStore, DEFAULT_API_URL, DSH_CLIENT_ID, DeviceLogin, GetnoteApi, GetnoteApiError, MEMBERSHIP_URL, NotLoggedInError, apiBase, apply, confirmationReason, createRuntime, inject, integerInRange, name, parseJson, trimPage };
301
944
 
302
945
  //# sourceMappingURL=index.js.map