@triplef/agent 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { tool } from 'ai';
3
+ import { request as request$1 } from 'http';
4
+ import { request } from 'https';
3
5
  import { Readability } from '@mozilla/readability';
4
6
  import { parseHTML } from 'linkedom';
5
7
  import TurndownService from 'turndown';
@@ -1002,8 +1004,8 @@ var defaultSummarize = (data) => {
1002
1004
  };
1003
1005
 
1004
1006
  // src/tools/helpers/with-summary.helper.ts
1005
- function withSummary(tool26, summarize = defaultSummarize) {
1006
- const t = tool26;
1007
+ function withSummary(tool32, summarize = defaultSummarize) {
1008
+ const t = tool32;
1007
1009
  t.summarize = summarize;
1008
1010
  return t;
1009
1011
  }
@@ -1176,6 +1178,667 @@ function createMemoryTaxonomyProbeTool(deps) {
1176
1178
  }
1177
1179
  });
1178
1180
  }
1181
+ var obsidianCreateNoteSchema = z.object({
1182
+ title: z.string().trim().min(1).max(200).describe("Human-readable note title used for its H1 and filename."),
1183
+ content: z.string().max(2e5).describe("Clean Markdown body. Empty is allowed only for an explicitly requested blank starting page."),
1184
+ folder: z.string().trim().max(512).optional().describe("Optional vault-relative folder; defaults to the configured autonomous-note folder."),
1185
+ tags: z.array(z.string().trim().min(1).max(64)).max(20).optional().describe("Optional frontmatter tags.")
1186
+ });
1187
+
1188
+ // src/tools/obsidian/build-obsidian-note-content.helper.ts
1189
+ function buildObsidianNoteContent(title, content, tags = []) {
1190
+ const frontmatter = tags.length ? `---
1191
+ tags:
1192
+ ${tags.map((tag) => ` - ${JSON.stringify(tag)}`).join("\n")}
1193
+ ---
1194
+
1195
+ ` : "";
1196
+ const body = content.trim();
1197
+ return `${frontmatter}# ${title.trim()}
1198
+ ${body ? `
1199
+ ${body}
1200
+ ` : ""}`;
1201
+ }
1202
+
1203
+ // src/tools/obsidian/has-obsidian-control-characters.helper.ts
1204
+ function hasObsidianControlCharacters(value) {
1205
+ for (const character of value) {
1206
+ if (character.charCodeAt(0) <= 31) return true;
1207
+ }
1208
+ return false;
1209
+ }
1210
+
1211
+ // src/tools/obsidian/obsidian-client-error.ts
1212
+ var TLS_ERROR_CODES = /* @__PURE__ */ new Set([
1213
+ "CERT_SIGNATURE_FAILURE",
1214
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
1215
+ "ERR_TLS_CERT_ALTNAME_INVALID",
1216
+ "ERR_TLS_CERT_ALTNAME_FORMAT",
1217
+ "SELF_SIGNED_CERT_IN_CHAIN",
1218
+ "UNABLE_TO_GET_ISSUER_CERT",
1219
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
1220
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
1221
+ ]);
1222
+ var ObsidianClientError = class _ObsidianClientError extends Error {
1223
+ constructor(code, message, status, path) {
1224
+ super(message);
1225
+ this.code = code;
1226
+ this.status = status;
1227
+ this.path = path;
1228
+ this.name = "ObsidianClientError";
1229
+ }
1230
+ code;
1231
+ status;
1232
+ path;
1233
+ static from(error, path) {
1234
+ if (error instanceof _ObsidianClientError) return error;
1235
+ const candidate = error;
1236
+ const code = typeof candidate?.code === "string" ? candidate.code : "";
1237
+ const message = typeof candidate?.message === "string" ? candidate.message : String(error);
1238
+ if (/invalid url/i.test(message)) {
1239
+ return new _ObsidianClientError("invalid_input", "Obsidian base URL is invalid", void 0, path);
1240
+ }
1241
+ if (code === "ETIMEDOUT" || code === "ESOCKETTIMEDOUT") {
1242
+ return new _ObsidianClientError("timeout", "Obsidian request timed out", void 0, path);
1243
+ }
1244
+ if (TLS_ERROR_CODES.has(code) || /certificate|tls|altname/i.test(message)) {
1245
+ return new _ObsidianClientError("tls_error", "Obsidian TLS certificate validation failed", void 0, path);
1246
+ }
1247
+ return new _ObsidianClientError("unreachable", "Obsidian is unreachable", void 0, path);
1248
+ }
1249
+ };
1250
+
1251
+ // src/tools/obsidian/normalize-obsidian-folder.helper.ts
1252
+ function normalizeObsidianFolder(value) {
1253
+ const raw = value.trim();
1254
+ if (raw.includes("\\") || raw.startsWith("/") || /^[a-z]:[\\/]/i.test(raw)) {
1255
+ throw new ObsidianClientError(
1256
+ "invalid_path",
1257
+ "A safe vault-relative destination folder is required",
1258
+ void 0,
1259
+ value
1260
+ );
1261
+ }
1262
+ const input = raw.replace(/^\/+|\/+$/g, "");
1263
+ if (!input) return "";
1264
+ const segments = input.split("/");
1265
+ if (segments.some(
1266
+ (segment) => !segment || segment === "." || segment === ".." || segment.toLowerCase() === ".obsidian" || hasObsidianControlCharacters(segment)
1267
+ )) {
1268
+ throw new ObsidianClientError(
1269
+ "invalid_path",
1270
+ "A safe vault-relative destination folder is required",
1271
+ void 0,
1272
+ value
1273
+ );
1274
+ }
1275
+ if (input.length > 512) {
1276
+ throw new ObsidianClientError("invalid_path", "Obsidian folders are limited to 512 characters", void 0, value);
1277
+ }
1278
+ return input;
1279
+ }
1280
+
1281
+ // src/tools/obsidian/normalize-obsidian-note-path.helper.ts
1282
+ function normalizeObsidianNotePath(value) {
1283
+ const input = value.trim();
1284
+ const invalid = !input || input.includes("\\") || !input.toLowerCase().endsWith(".md") || input.startsWith("/") || /^[a-z]:[\\/]/i.test(input) || input.split("/").some(
1285
+ (segment) => !segment || segment === "." || segment === ".." || segment.toLowerCase() === ".obsidian" || hasObsidianControlCharacters(segment)
1286
+ );
1287
+ if (invalid) {
1288
+ throw new ObsidianClientError(
1289
+ "invalid_path",
1290
+ "A safe vault-relative Markdown note path is required",
1291
+ void 0,
1292
+ value
1293
+ );
1294
+ }
1295
+ if (input.length > 512) {
1296
+ throw new ObsidianClientError(
1297
+ "invalid_path",
1298
+ "Obsidian note paths are limited to 512 characters",
1299
+ void 0,
1300
+ value
1301
+ );
1302
+ }
1303
+ return input;
1304
+ }
1305
+
1306
+ // src/tools/obsidian/build-obsidian-note-path.helper.ts
1307
+ function buildObsidianNotePath(title, folder) {
1308
+ const filename = Array.from(title.trim()).filter((character) => !hasObsidianControlCharacters(character)).join("").replace(/[<>:"/\\|?*]/g, "-").replace(/\s+/g, " ").replace(/[. ]+$/g, "").slice(0, 200).trim();
1309
+ if (!filename) {
1310
+ return normalizeObsidianNotePath("Untitled.md");
1311
+ }
1312
+ const normalizedFolder = normalizeObsidianFolder(folder);
1313
+ return normalizeObsidianNotePath(`${normalizedFolder ? `${normalizedFolder}/` : ""}${filename}.md`);
1314
+ }
1315
+
1316
+ // src/tools/obsidian/encode-obsidian-path.helper.ts
1317
+ function encodeObsidianPath(path) {
1318
+ return path.split("/").map(encodeURIComponent).join("/");
1319
+ }
1320
+
1321
+ // src/tools/obsidian/normalize-obsidian-version.helper.ts
1322
+ function normalizeObsidianVersion(value) {
1323
+ const version = value?.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
1324
+ if (!version || /[\r\n]/.test(version)) {
1325
+ throw new ObsidianClientError("invalid_response", "Obsidian did not return a usable note revision");
1326
+ }
1327
+ return version;
1328
+ }
1329
+ var DEFAULT_MAX_RESPONSE_BYTES = 1e6;
1330
+ function obsidianRequest(config, options) {
1331
+ const url = new URL(config.baseUrl);
1332
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) {
1333
+ return Promise.reject(
1334
+ new ObsidianClientError(
1335
+ "invalid_input",
1336
+ "Obsidian base URL must be an HTTP(S) URL without credentials or fragments"
1337
+ )
1338
+ );
1339
+ }
1340
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${options.path}`;
1341
+ for (const [key, value] of Object.entries(options.query ?? {})) {
1342
+ if (value !== void 0) url.searchParams.set(key, String(value));
1343
+ }
1344
+ if (options.signal?.aborted) {
1345
+ return Promise.reject(new ObsidianClientError("unreachable", "Obsidian request was aborted"));
1346
+ }
1347
+ const headers = {
1348
+ Accept: "application/json, text/markdown",
1349
+ Authorization: `Bearer ${config.apiKey ?? ""}`,
1350
+ ...options.headers
1351
+ };
1352
+ if (options.body !== void 0) {
1353
+ headers["Content-Length"] = String(Buffer.byteLength(options.body));
1354
+ }
1355
+ return new Promise((resolve, reject) => {
1356
+ const fail = (error) => {
1357
+ if (totalTimeout) clearTimeout(totalTimeout);
1358
+ reject(ObsidianClientError.from(error));
1359
+ };
1360
+ const request$2 = (url.protocol === "https:" ? request : request$1)(
1361
+ url,
1362
+ {
1363
+ method: options.method,
1364
+ headers,
1365
+ timeout: config.requestTimeoutMs,
1366
+ signal: options.signal,
1367
+ agent: false,
1368
+ ...url.protocol === "https:" && config.caCertificate ? { ca: config.caCertificate } : {}
1369
+ },
1370
+ (response) => {
1371
+ const chunks = [];
1372
+ let bytes = 0;
1373
+ response.on("data", (chunk) => {
1374
+ if (options.discardBody) return;
1375
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1376
+ bytes += buffer.length;
1377
+ if (bytes > (options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES)) {
1378
+ fail(new ObsidianClientError("response_too_large", "Obsidian response exceeded the safe size limit"));
1379
+ response.destroy();
1380
+ return;
1381
+ }
1382
+ chunks.push(buffer);
1383
+ });
1384
+ response.on("error", fail);
1385
+ response.on("aborted", () => fail(new ObsidianClientError("unreachable", "Obsidian response was interrupted")));
1386
+ response.on("end", () => {
1387
+ if (totalTimeout) clearTimeout(totalTimeout);
1388
+ if (!response.complete) {
1389
+ fail(new ObsidianClientError("unreachable", "Obsidian response was incomplete"));
1390
+ return;
1391
+ }
1392
+ resolve({
1393
+ status: response.statusCode ?? 0,
1394
+ headers: response.headers,
1395
+ body: Buffer.concat(chunks).toString("utf8")
1396
+ });
1397
+ });
1398
+ }
1399
+ );
1400
+ request$2.on("timeout", () => {
1401
+ request$2.destroy(new ObsidianClientError("timeout", "Obsidian request timed out"));
1402
+ });
1403
+ request$2.on("error", fail);
1404
+ const totalTimeout = setTimeout(() => {
1405
+ request$2.destroy(new ObsidianClientError("timeout", "Obsidian request timed out"));
1406
+ }, config.requestTimeoutMs);
1407
+ if (options.body !== void 0) request$2.write(options.body);
1408
+ request$2.end();
1409
+ });
1410
+ }
1411
+
1412
+ // src/tools/obsidian/resolve-obsidian-status-error.helper.ts
1413
+ function resolveObsidianStatusError(status, conflictCode) {
1414
+ if (status === 400) return "invalid_input";
1415
+ if (status === 401) return "unauthorized";
1416
+ if (status === 403) return "forbidden";
1417
+ if (status === 404) return "not_found";
1418
+ if (status === 409 || status === 412) return conflictCode;
1419
+ return "http_error";
1420
+ }
1421
+
1422
+ // src/tools/obsidian/obsidian-client.ts
1423
+ var MAX_NOTE_CHARS = 2e5;
1424
+ var ObsidianClient = class {
1425
+ constructor(config) {
1426
+ this.config = config;
1427
+ }
1428
+ config;
1429
+ async getServerInfo(signal) {
1430
+ const response = await obsidianRequest(this.config, {
1431
+ method: "GET",
1432
+ path: "/",
1433
+ signal,
1434
+ maxResponseBytes: 1e5
1435
+ });
1436
+ this.assertStatus(response, 200);
1437
+ return this.parseJson(response);
1438
+ }
1439
+ async search(input, signal) {
1440
+ const response = await obsidianRequest(this.config, {
1441
+ method: "POST",
1442
+ path: "/search/simple/",
1443
+ signal,
1444
+ query: {
1445
+ query: input.query,
1446
+ maxResults: input.maxResults ?? 20,
1447
+ maxMatchesPerFile: input.maxMatchesPerFile ?? 5,
1448
+ contextLength: input.contextLength ?? 200
1449
+ }
1450
+ });
1451
+ this.assertStatus(response, 200);
1452
+ const data = this.parseJson(response);
1453
+ const valid = Array.isArray(data) && data.every(
1454
+ (entry) => entry && typeof entry.filename === "string" && typeof entry.score === "number" && (entry.matches ?? []).every(
1455
+ (match) => typeof match.context === "string" && Number.isFinite(match.match?.start) && Number.isFinite(match.match?.end)
1456
+ )
1457
+ );
1458
+ if (!valid) {
1459
+ throw new ObsidianClientError(
1460
+ "invalid_response",
1461
+ "Obsidian returned an invalid search response",
1462
+ response.status
1463
+ );
1464
+ }
1465
+ const allResults = data.map((entry) => ({
1466
+ path: entry.filename,
1467
+ score: entry.score,
1468
+ totalMatches: entry.totalMatches,
1469
+ matches: (entry.matches ?? []).map((match) => ({
1470
+ context: match.context,
1471
+ start: match.match.start,
1472
+ end: match.match.end
1473
+ }))
1474
+ }));
1475
+ const results = allResults.filter((entry) => entry.path.toLowerCase().endsWith(".md"));
1476
+ const reportedTotal = Number(this.header(response, "total-results"));
1477
+ const totalResults = Number.isFinite(reportedTotal) && reportedTotal >= 0 ? reportedTotal : results.length;
1478
+ return {
1479
+ ok: true,
1480
+ query: input.query,
1481
+ results,
1482
+ totalResults,
1483
+ limited: totalResults > results.length || results.some((entry) => entry.totalMatches !== void 0 && entry.totalMatches > entry.matches.length)
1484
+ };
1485
+ }
1486
+ async read(input, signal) {
1487
+ const path = normalizeObsidianNotePath(input.path);
1488
+ const response = await this.readResponse(path, input.heading, input.scope, signal);
1489
+ if (response.body.length > MAX_NOTE_CHARS) {
1490
+ throw new ObsidianClientError(
1491
+ "response_too_large",
1492
+ "Obsidian note exceeds the safe whole-read limit",
1493
+ void 0,
1494
+ path
1495
+ );
1496
+ }
1497
+ const version = normalizeObsidianVersion(this.header(response, "etag"));
1498
+ let documentMap;
1499
+ if (input.includeDocumentMap) {
1500
+ const mapResponse = await obsidianRequest(this.config, {
1501
+ method: "GET",
1502
+ path: `/vault/${encodeObsidianPath(path)}`,
1503
+ headers: { Accept: "application/vnd.olrapi.document-map+json" },
1504
+ signal
1505
+ });
1506
+ this.assertStatus(mapResponse, 200, path);
1507
+ const map = this.parseJson(mapResponse);
1508
+ documentMap = {
1509
+ headings: map.headings ?? {},
1510
+ blocks: map.blocks ?? [],
1511
+ frontmatterFields: map.frontmatterFields ?? [],
1512
+ version: normalizeObsidianVersion(map.version)
1513
+ };
1514
+ if (documentMap.version !== version) {
1515
+ throw new ObsidianClientError(
1516
+ "revision_conflict",
1517
+ "Obsidian note changed while it was being read; retry the read",
1518
+ 412,
1519
+ path
1520
+ );
1521
+ }
1522
+ }
1523
+ return { ok: true, path, content: response.body, version, documentMap };
1524
+ }
1525
+ async create(input, signal) {
1526
+ const path = buildObsidianNotePath(input.title, input.folder ?? this.config.vaultFolder);
1527
+ const response = await obsidianRequest(this.config, {
1528
+ method: "PUT",
1529
+ path: `/vault/${encodeObsidianPath(path)}`,
1530
+ signal,
1531
+ headers: {
1532
+ "Content-Type": "text/markdown; charset=utf-8",
1533
+ "If-None-Match": "*"
1534
+ },
1535
+ body: buildObsidianNoteContent(input.title, input.content, input.tags)
1536
+ });
1537
+ this.assertStatus(response, 204, path, "already_exists");
1538
+ return {
1539
+ ok: true,
1540
+ created: true,
1541
+ path,
1542
+ version: normalizeObsidianVersion(this.header(response, "etag"))
1543
+ };
1544
+ }
1545
+ async update(input, signal) {
1546
+ const path = normalizeObsidianNotePath(input.path);
1547
+ const version = normalizeObsidianVersion(input.version);
1548
+ const isReplace = input.mode === "replaceNote";
1549
+ const instruction = input.mode === "patchHeading" ? {
1550
+ targetType: "heading",
1551
+ target: input.target,
1552
+ operation: input.operation,
1553
+ scope: input.scope ?? "content",
1554
+ content: input.content,
1555
+ createTargetIfMissing: input.createTargetIfMissing
1556
+ } : input.mode === "patchFrontmatter" ? {
1557
+ targetType: "frontmatter",
1558
+ target: input.target,
1559
+ operation: input.operation,
1560
+ value: input.value,
1561
+ createTargetIfMissing: input.createTargetIfMissing
1562
+ } : void 0;
1563
+ const response = await obsidianRequest(this.config, {
1564
+ method: isReplace ? "PUT" : "PATCH",
1565
+ discardBody: !isReplace,
1566
+ path: `/vault/${encodeObsidianPath(path)}`,
1567
+ signal,
1568
+ headers: {
1569
+ "Content-Type": isReplace ? "text/markdown; charset=utf-8" : "application/json",
1570
+ "If-Match": `"${version}"`
1571
+ },
1572
+ body: isReplace ? input.content : JSON.stringify(instruction)
1573
+ });
1574
+ this.assertStatus(response, isReplace ? 204 : 200, path);
1575
+ return {
1576
+ ok: true,
1577
+ updated: true,
1578
+ path,
1579
+ version: normalizeObsidianVersion(this.header(response, "etag"))
1580
+ };
1581
+ }
1582
+ async delete(pathInput, versionInput, signal) {
1583
+ const path = normalizeObsidianNotePath(pathInput);
1584
+ const version = normalizeObsidianVersion(versionInput);
1585
+ const response = await obsidianRequest(this.config, {
1586
+ method: "DELETE",
1587
+ path: `/vault/${encodeObsidianPath(path)}`,
1588
+ signal,
1589
+ query: { permanent: "false" },
1590
+ headers: { "If-Match": `"${version}"` }
1591
+ });
1592
+ this.assertStatus(response, 204, path);
1593
+ return { ok: true, deleted: true, path, permanent: false };
1594
+ }
1595
+ async open(pathInput, newLeaf = false, signal) {
1596
+ const path = normalizeObsidianNotePath(pathInput);
1597
+ const existing = await obsidianRequest(this.config, {
1598
+ method: "GET",
1599
+ path: `/vault/${encodeObsidianPath(path)}`,
1600
+ headers: { Accept: "application/vnd.olrapi.document-map+json" },
1601
+ maxResponseBytes: 1e5,
1602
+ discardBody: true,
1603
+ signal
1604
+ });
1605
+ this.assertStatus(existing, 200, path);
1606
+ const response = await obsidianRequest(this.config, {
1607
+ method: "POST",
1608
+ path: `/open/${encodeObsidianPath(path)}`,
1609
+ signal,
1610
+ query: { newLeaf }
1611
+ });
1612
+ this.assertStatus(response, 200, path);
1613
+ return { ok: true, opened: true, path, newLeaf };
1614
+ }
1615
+ readResponse(path, heading, scope = "content", signal) {
1616
+ const suffix = heading?.length ? `/heading/${heading.map(encodeURIComponent).join("/")}` : "";
1617
+ return obsidianRequest(this.config, {
1618
+ method: "GET",
1619
+ path: `/vault/${encodeObsidianPath(path)}${suffix}`,
1620
+ headers: {
1621
+ Accept: "text/markdown",
1622
+ ...heading?.length ? { "Target-Scope": scope } : {}
1623
+ },
1624
+ maxResponseBytes: 1e6,
1625
+ signal
1626
+ }).then((response) => {
1627
+ this.assertStatus(response, 200, path);
1628
+ return response;
1629
+ });
1630
+ }
1631
+ header(response, name) {
1632
+ const value = response.headers[name];
1633
+ return Array.isArray(value) ? value[0] : value;
1634
+ }
1635
+ parseJson(response) {
1636
+ try {
1637
+ return JSON.parse(response.body);
1638
+ } catch {
1639
+ throw new ObsidianClientError("invalid_response", "Obsidian returned invalid JSON", response.status);
1640
+ }
1641
+ }
1642
+ assertStatus(response, expected, path, conflictCode = "revision_conflict") {
1643
+ if (response.status === expected) return;
1644
+ const code = resolveObsidianStatusError(response.status, conflictCode);
1645
+ const messages = {
1646
+ invalid_input: "Obsidian rejected the request",
1647
+ unauthorized: "Obsidian rejected the API key",
1648
+ forbidden: "Obsidian refused access to this path",
1649
+ not_found: "Obsidian note was not found",
1650
+ already_exists: "Obsidian note already exists",
1651
+ revision_conflict: "Obsidian note changed; re-read it before retrying",
1652
+ http_error: `Obsidian returned HTTP ${response.status}`
1653
+ };
1654
+ throw new ObsidianClientError(code, messages[code], response.status, path);
1655
+ }
1656
+ };
1657
+
1658
+ // src/tools/obsidian/create-obsidian-client.helper.ts
1659
+ function createObsidianClient(deps) {
1660
+ const config = deps.getLiveConfig().obsidian;
1661
+ if (!config?.enabled || !config.baseUrl || !config.apiKey) {
1662
+ throw new ObsidianClientError("disabled", "Obsidian integration is not enabled and fully configured");
1663
+ }
1664
+ return new ObsidianClient(config);
1665
+ }
1666
+
1667
+ // src/tools/obsidian/to-obsidian-error-result.helper.ts
1668
+ function toObsidianErrorResult(error, path) {
1669
+ const normalized = ObsidianClientError.from(error, path);
1670
+ return {
1671
+ ok: false,
1672
+ code: normalized.code,
1673
+ message: normalized.message,
1674
+ path: normalized.path ?? path,
1675
+ status: normalized.status
1676
+ };
1677
+ }
1678
+
1679
+ // src/tools/obsidian/create-note.tool.ts
1680
+ function createObsidianCreateNoteTool(deps) {
1681
+ return tool({
1682
+ description: "Create a clean, curated Obsidian Markdown note without overwriting an existing path. Use a descriptive title and the configured default folder unless the user specified another destination.",
1683
+ inputSchema: obsidianCreateNoteSchema,
1684
+ execute: async (input, options) => {
1685
+ try {
1686
+ deps.logger.log(`Obsidian create ${input.title}`);
1687
+ return await createObsidianClient(deps).create(input, options.abortSignal);
1688
+ } catch (error) {
1689
+ return toObsidianErrorResult(error);
1690
+ }
1691
+ }
1692
+ });
1693
+ }
1694
+ var obsidianDeleteNoteSchema = z.object({
1695
+ path: z.string().trim().min(1).max(512).describe("Exact note path explicitly selected by the user."),
1696
+ version: z.string().trim().min(1).max(512).describe("Current revision from a fresh read.")
1697
+ });
1698
+ function createObsidianDeleteNoteTool(deps) {
1699
+ return tool({
1700
+ description: "Move one explicitly user-selected Obsidian note to trash using a fresh read revision. Never use autonomously, never permanently delete, and stop on a revision conflict.",
1701
+ inputSchema: obsidianDeleteNoteSchema,
1702
+ execute: async (input, options) => {
1703
+ try {
1704
+ deps.logger.log(`Obsidian delete ${input.path} (trash)`);
1705
+ return await createObsidianClient(deps).delete(input.path, input.version, options.abortSignal);
1706
+ } catch (error) {
1707
+ return toObsidianErrorResult(error, input.path);
1708
+ }
1709
+ }
1710
+ });
1711
+ }
1712
+ var obsidianOpenNoteSchema = z.object({
1713
+ path: z.string().trim().min(1).max(512).describe("Exact existing Markdown path to open."),
1714
+ newLeaf: z.boolean().optional().describe("Open a new Obsidian leaf; default false.")
1715
+ });
1716
+ function createObsidianOpenNoteTool(deps) {
1717
+ return tool({
1718
+ description: "Open an existing note in the connected Obsidian UI after verifying it exists. Only use when the user explicitly asks to open a note; never use as an implicit create operation.",
1719
+ inputSchema: obsidianOpenNoteSchema,
1720
+ execute: async (input, options) => {
1721
+ try {
1722
+ deps.logger.log(`Obsidian open ${input.path}`);
1723
+ return await createObsidianClient(deps).open(input.path, input.newLeaf, options.abortSignal);
1724
+ } catch (error) {
1725
+ return toObsidianErrorResult(error, input.path);
1726
+ }
1727
+ }
1728
+ });
1729
+ }
1730
+ var obsidianReadNoteSchema = z.object({
1731
+ path: z.string().trim().min(1).max(512).describe("Exact vault-relative Markdown path."),
1732
+ heading: z.array(z.string().min(1).max(300)).min(1).max(20).optional().describe("Exact heading path copied from the document map."),
1733
+ scope: z.enum(["content", "markerAndContent"]).optional().describe("Read a heading body or its complete subtree."),
1734
+ includeDocumentMap: z.boolean().optional().describe("Include heading/block/frontmatter targets and their current version.")
1735
+ }).superRefine((input, context) => {
1736
+ if (input.heading && input.includeDocumentMap) {
1737
+ context.addIssue({
1738
+ code: "custom",
1739
+ message: "A heading read and includeDocumentMap are mutually exclusive"
1740
+ });
1741
+ }
1742
+ });
1743
+ function createObsidianReadNoteTool(deps) {
1744
+ return tool({
1745
+ description: "Read the latest Obsidian Markdown content and revision. Always read before updating or deleting. Optionally retrieve the document map for targeted heading/frontmatter edits.",
1746
+ inputSchema: obsidianReadNoteSchema,
1747
+ execute: async (input, options) => {
1748
+ try {
1749
+ deps.logger.log(`Obsidian read ${input.path}`);
1750
+ return await createObsidianClient(deps).read(input, options.abortSignal);
1751
+ } catch (error) {
1752
+ return toObsidianErrorResult(error, input.path);
1753
+ }
1754
+ }
1755
+ });
1756
+ }
1757
+ var obsidianSearchNotesSchema = z.object({
1758
+ query: z.string().trim().min(1).max(500).describe("Obsidian full-text search query."),
1759
+ maxResults: z.number().int().min(1).max(50).optional().describe("Maximum files; default 20."),
1760
+ maxMatchesPerFile: z.number().int().min(1).max(10).optional().describe("Maximum matches per file; default 5."),
1761
+ contextLength: z.number().int().min(1).max(500).optional().describe("Snippet context characters; default 200.")
1762
+ });
1763
+ function createObsidianSearchNotesTool(deps) {
1764
+ return tool({
1765
+ description: "Search the connected Obsidian vault for Markdown notes. Returns bounded paths, scores, and snippets; read a selected note for its full current content.",
1766
+ inputSchema: obsidianSearchNotesSchema,
1767
+ execute: async (input, options) => {
1768
+ try {
1769
+ deps.logger.log(`Obsidian search for "${input.query}"`);
1770
+ return await createObsidianClient(deps).search(input, options.abortSignal);
1771
+ } catch (error) {
1772
+ return toObsidianErrorResult(error);
1773
+ }
1774
+ }
1775
+ });
1776
+ }
1777
+
1778
+ // src/tools/obsidian/summarize-obsidian-result.helper.ts
1779
+ function summarizeObsidianResult(result) {
1780
+ const data = result;
1781
+ return {
1782
+ ok: data.ok,
1783
+ code: data.code,
1784
+ path: data.path,
1785
+ resultCount: Array.isArray(data.results) ? data.results.length : void 0,
1786
+ created: data.created,
1787
+ updated: data.updated,
1788
+ deleted: data.deleted,
1789
+ opened: data.opened,
1790
+ permanent: data.permanent
1791
+ };
1792
+ }
1793
+ var updateBase = {
1794
+ path: z.string().trim().min(1).max(512),
1795
+ version: z.string().trim().min(1).max(512).describe("Revision returned by the latest Obsidian read.")
1796
+ };
1797
+ var obsidianUpdateNoteSchema = z.discriminatedUnion("mode", [
1798
+ z.object({
1799
+ ...updateBase,
1800
+ mode: z.literal("replaceNote"),
1801
+ content: z.string().max(2e5).describe("Complete latest-note replacement, only after a whole-note read.")
1802
+ }),
1803
+ z.object({
1804
+ ...updateBase,
1805
+ mode: z.literal("patchHeading"),
1806
+ target: z.array(z.string().min(1).max(300)).min(1).max(20).describe("Exact heading path from the document map."),
1807
+ operation: z.enum(["append", "prepend", "replace", "delete"]),
1808
+ scope: z.enum(["content", "markerAndContent"]).optional(),
1809
+ content: z.string().max(2e5).optional(),
1810
+ createTargetIfMissing: z.boolean().optional()
1811
+ }),
1812
+ z.object({
1813
+ ...updateBase,
1814
+ mode: z.literal("patchFrontmatter"),
1815
+ target: z.string().trim().min(1).max(200),
1816
+ operation: z.enum(["append", "prepend", "replace", "delete"]),
1817
+ value: z.unknown().optional(),
1818
+ createTargetIfMissing: z.boolean().optional()
1819
+ })
1820
+ ]).superRefine((input, context) => {
1821
+ if (input.mode === "patchHeading" && input.operation !== "delete" && typeof input.content !== "string") {
1822
+ context.addIssue({ code: "custom", message: "content is required for this heading operation" });
1823
+ }
1824
+ if (input.mode === "patchFrontmatter" && input.operation !== "delete" && input.value === void 0) {
1825
+ context.addIssue({ code: "custom", message: "value is required for this frontmatter operation" });
1826
+ }
1827
+ });
1828
+ function createObsidianUpdateNoteTool(deps) {
1829
+ return tool({
1830
+ description: "Update an Obsidian note with its latest read revision. Prefer targeted heading/frontmatter patches over whole-note replacement. A 412 conflict means re-read and preserve the user\u2019s latest edits; never force-overwrite.",
1831
+ inputSchema: obsidianUpdateNoteSchema,
1832
+ execute: async (input, options) => {
1833
+ try {
1834
+ deps.logger.log(`Obsidian update ${input.path} (${input.mode})`);
1835
+ return await createObsidianClient(deps).update(input, options.abortSignal);
1836
+ } catch (error) {
1837
+ return toObsidianErrorResult(error, input.path);
1838
+ }
1839
+ }
1840
+ });
1841
+ }
1179
1842
  var serperBusinessReviewsSearchSchema = z.object({
1180
1843
  query: z.string().optional().describe(
1181
1844
  "The exact business or place name, ideally with its location, named explicitly and resolved from the conversation. Used when neither placeId nor cid is known."
@@ -1931,4 +2594,4 @@ function createYoutubeVideoSearch(deps) {
1931
2594
  });
1932
2595
  }
1933
2596
 
1934
- export { BRIGHT_DATA_TIMEOUT_MS, HEADERS, MIN_IMAGE_HEIGHT, MIN_IMAGE_WIDTH, RECENCY_DESCRIPTION, SEARCH_RETRIES, SEARCH_TIMEOUT_MS, SOURCE, STANDALONE_QUERY_DESCRIPTION, STANDALONE_QUERY_TOOL_CLAUSE, applyLocaleParams, applyRecencyParam, brightDataImageSearchSchema, brightDataNewsSearchSchema, brightDataPlacesSearchSchema, brightDataShoppingSearchSchema, brightDataVideoSearchSchema, brightDataWebSearchSchema, brightDataWebpageScrapeSchema, buildGoogleUrl, buildYoutubeThumbnailUrl, createBrightDataImageSearch, createBrightDataNewsSearch, createBrightDataPlacesSearch, createBrightDataShoppingSearch, createBrightDataVideoSearch, createBrightDataWebSearch, createBrightDataWebpageScrape, createEncyclopediaReadTool, createEncyclopediaSearchTool, createMemoryCognitionDeleteTool, createMemoryCognitionForgetTool, createMemoryPartitionDeleteTool, createMemoryPartitionRecallTool, createMemoryTaxonomyProbeTool, createSerperBusinessReviewsSearch, createSerperImageSearch, createSerperNewsSearch, createSerperPlacesSearch, createSerperShoppingSearch, createSerperVideoSearch, createSerperWebSearch, createSerperWebpageScrape, createVariantRequestTool, createWebFetchTool, createYoutubeVideoSearch, encyclopediaReadSchema, encyclopediaSearchSchema, engineEnabled, extractArticleText, fetchWithTimeout, isGoogleHostUrl, localizedQuerySuffix, meetsMinimumImageDimensions, memoryCognitionDeleteSchema, memoryCognitionForgetSchema, memoryPartitionDeleteSchema, memoryPartitionRecallSchema, memoryTaxonomyProbeSchema, pickMerchantResult, requestBrightData, resolveSerperShopOfferLinks, serperBusinessReviewsSearchSchema, serperImageSearchSchema, serperNewsSearchSchema, serperPlacesSearchSchema, serperShoppingSearchSchema, serperVideoSearchSchema, serperWebSearchSchema, serperWebpageScrapeSchema, storeHostToken, summarizeContent, summarizeFound, summarizeResults, tbsSizeLabelForPixels, variantRequestSchema, webFetchSchema, withSummary, youtubeVideoSearchSchema };
2597
+ export { BRIGHT_DATA_TIMEOUT_MS, HEADERS, MIN_IMAGE_HEIGHT, MIN_IMAGE_WIDTH, ObsidianClient, ObsidianClientError, RECENCY_DESCRIPTION, SEARCH_RETRIES, SEARCH_TIMEOUT_MS, SOURCE, STANDALONE_QUERY_DESCRIPTION, STANDALONE_QUERY_TOOL_CLAUSE, applyLocaleParams, applyRecencyParam, brightDataImageSearchSchema, brightDataNewsSearchSchema, brightDataPlacesSearchSchema, brightDataShoppingSearchSchema, brightDataVideoSearchSchema, brightDataWebSearchSchema, brightDataWebpageScrapeSchema, buildGoogleUrl, buildYoutubeThumbnailUrl, createBrightDataImageSearch, createBrightDataNewsSearch, createBrightDataPlacesSearch, createBrightDataShoppingSearch, createBrightDataVideoSearch, createBrightDataWebSearch, createBrightDataWebpageScrape, createEncyclopediaReadTool, createEncyclopediaSearchTool, createMemoryCognitionDeleteTool, createMemoryCognitionForgetTool, createMemoryPartitionDeleteTool, createMemoryPartitionRecallTool, createMemoryTaxonomyProbeTool, createObsidianCreateNoteTool, createObsidianDeleteNoteTool, createObsidianOpenNoteTool, createObsidianReadNoteTool, createObsidianSearchNotesTool, createObsidianUpdateNoteTool, createSerperBusinessReviewsSearch, createSerperImageSearch, createSerperNewsSearch, createSerperPlacesSearch, createSerperShoppingSearch, createSerperVideoSearch, createSerperWebSearch, createSerperWebpageScrape, createVariantRequestTool, createWebFetchTool, createYoutubeVideoSearch, encyclopediaReadSchema, encyclopediaSearchSchema, engineEnabled, extractArticleText, fetchWithTimeout, isGoogleHostUrl, localizedQuerySuffix, meetsMinimumImageDimensions, memoryCognitionDeleteSchema, memoryCognitionForgetSchema, memoryPartitionDeleteSchema, memoryPartitionRecallSchema, memoryTaxonomyProbeSchema, normalizeObsidianFolder, normalizeObsidianNotePath, obsidianCreateNoteSchema, obsidianDeleteNoteSchema, obsidianOpenNoteSchema, obsidianReadNoteSchema, obsidianSearchNotesSchema, obsidianUpdateNoteSchema, pickMerchantResult, requestBrightData, resolveSerperShopOfferLinks, serperBusinessReviewsSearchSchema, serperImageSearchSchema, serperNewsSearchSchema, serperPlacesSearchSchema, serperShoppingSearchSchema, serperVideoSearchSchema, serperWebSearchSchema, serperWebpageScrapeSchema, storeHostToken, summarizeContent, summarizeFound, summarizeObsidianResult, summarizeResults, tbsSizeLabelForPixels, variantRequestSchema, webFetchSchema, withSummary, youtubeVideoSearchSchema };