modularob-connectors 0.0.0-stage → 0.6.7
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/LICENSE +21 -0
- package/README.md +217 -2
- package/README.zh.md +218 -0
- package/client.js +1577 -0
- package/cordis.patch.yml +3 -0
- package/docs/PUBLISHING.md +53 -0
- package/icon.svg +8 -0
- package/index.js +135 -0
- package/lib/api.js +194 -0
- package/lib/cli.js +144 -0
- package/lib/obsidian.js +735 -0
- package/lib/profile-model.js +305 -0
- package/lib/profile.js +131 -0
- package/lib/skills.js +273 -0
- package/lib/tool.js +122 -0
- package/lib/update.js +268 -0
- package/lib/vendor/yaml/LICENSE +13 -0
- package/lib/vendor/yaml/dist/cli.d.ts +8 -0
- package/lib/vendor/yaml/dist/cli.mjs +201 -0
- package/lib/vendor/yaml/dist/compose/compose-collection.d.ts +11 -0
- package/lib/vendor/yaml/dist/compose/compose-collection.js +90 -0
- package/lib/vendor/yaml/dist/compose/compose-doc.d.ts +7 -0
- package/lib/vendor/yaml/dist/compose/compose-doc.js +45 -0
- package/lib/vendor/yaml/dist/compose/compose-node.d.ts +29 -0
- package/lib/vendor/yaml/dist/compose/compose-node.js +112 -0
- package/lib/vendor/yaml/dist/compose/compose-scalar.d.ts +5 -0
- package/lib/vendor/yaml/dist/compose/compose-scalar.js +88 -0
- package/lib/vendor/yaml/dist/compose/composer.d.ts +63 -0
- package/lib/vendor/yaml/dist/compose/composer.js +224 -0
- package/lib/vendor/yaml/dist/compose/resolve-block-map.d.ts +6 -0
- package/lib/vendor/yaml/dist/compose/resolve-block-map.js +117 -0
- package/lib/vendor/yaml/dist/compose/resolve-block-scalar.d.ts +11 -0
- package/lib/vendor/yaml/dist/compose/resolve-block-scalar.js +200 -0
- package/lib/vendor/yaml/dist/compose/resolve-block-seq.d.ts +6 -0
- package/lib/vendor/yaml/dist/compose/resolve-block-seq.js +51 -0
- package/lib/vendor/yaml/dist/compose/resolve-end.d.ts +6 -0
- package/lib/vendor/yaml/dist/compose/resolve-end.js +39 -0
- package/lib/vendor/yaml/dist/compose/resolve-flow-collection.d.ts +7 -0
- package/lib/vendor/yaml/dist/compose/resolve-flow-collection.js +209 -0
- package/lib/vendor/yaml/dist/compose/resolve-flow-scalar.d.ts +10 -0
- package/lib/vendor/yaml/dist/compose/resolve-flow-scalar.js +228 -0
- package/lib/vendor/yaml/dist/compose/resolve-props.d.ts +23 -0
- package/lib/vendor/yaml/dist/compose/resolve-props.js +148 -0
- package/lib/vendor/yaml/dist/compose/util-contains-newline.d.ts +2 -0
- package/lib/vendor/yaml/dist/compose/util-contains-newline.js +36 -0
- package/lib/vendor/yaml/dist/compose/util-empty-scalar-position.d.ts +2 -0
- package/lib/vendor/yaml/dist/compose/util-empty-scalar-position.js +28 -0
- package/lib/vendor/yaml/dist/compose/util-flow-indent-check.d.ts +3 -0
- package/lib/vendor/yaml/dist/compose/util-flow-indent-check.js +17 -0
- package/lib/vendor/yaml/dist/compose/util-map-includes.d.ts +4 -0
- package/lib/vendor/yaml/dist/compose/util-map-includes.js +15 -0
- package/lib/vendor/yaml/dist/doc/Document.d.ts +141 -0
- package/lib/vendor/yaml/dist/doc/Document.js +337 -0
- package/lib/vendor/yaml/dist/doc/anchors.d.ts +24 -0
- package/lib/vendor/yaml/dist/doc/anchors.js +76 -0
- package/lib/vendor/yaml/dist/doc/applyReviver.d.ts +9 -0
- package/lib/vendor/yaml/dist/doc/applyReviver.js +57 -0
- package/lib/vendor/yaml/dist/doc/createNode.d.ts +17 -0
- package/lib/vendor/yaml/dist/doc/createNode.js +90 -0
- package/lib/vendor/yaml/dist/doc/directives.d.ts +49 -0
- package/lib/vendor/yaml/dist/doc/directives.js +178 -0
- package/lib/vendor/yaml/dist/errors.d.ts +21 -0
- package/lib/vendor/yaml/dist/errors.js +62 -0
- package/lib/vendor/yaml/dist/index.d.ts +25 -0
- package/lib/vendor/yaml/dist/index.js +50 -0
- package/lib/vendor/yaml/dist/log.d.ts +3 -0
- package/lib/vendor/yaml/dist/log.js +19 -0
- package/lib/vendor/yaml/dist/nodes/Alias.d.ts +29 -0
- package/lib/vendor/yaml/dist/nodes/Alias.js +120 -0
- package/lib/vendor/yaml/dist/nodes/Collection.d.ts +73 -0
- package/lib/vendor/yaml/dist/nodes/Collection.js +151 -0
- package/lib/vendor/yaml/dist/nodes/Node.d.ts +53 -0
- package/lib/vendor/yaml/dist/nodes/Node.js +40 -0
- package/lib/vendor/yaml/dist/nodes/Pair.d.ts +22 -0
- package/lib/vendor/yaml/dist/nodes/Pair.js +39 -0
- package/lib/vendor/yaml/dist/nodes/Scalar.d.ts +47 -0
- package/lib/vendor/yaml/dist/nodes/Scalar.js +27 -0
- package/lib/vendor/yaml/dist/nodes/YAMLMap.d.ts +53 -0
- package/lib/vendor/yaml/dist/nodes/YAMLMap.js +147 -0
- package/lib/vendor/yaml/dist/nodes/YAMLSeq.d.ts +60 -0
- package/lib/vendor/yaml/dist/nodes/YAMLSeq.js +115 -0
- package/lib/vendor/yaml/dist/nodes/addPairToJSMap.d.ts +4 -0
- package/lib/vendor/yaml/dist/nodes/addPairToJSMap.js +65 -0
- package/lib/vendor/yaml/dist/nodes/identity.d.ts +23 -0
- package/lib/vendor/yaml/dist/nodes/identity.js +53 -0
- package/lib/vendor/yaml/dist/nodes/toJS.d.ts +29 -0
- package/lib/vendor/yaml/dist/nodes/toJS.js +39 -0
- package/lib/vendor/yaml/dist/options.d.ts +350 -0
- package/lib/vendor/yaml/dist/parse/cst-scalar.d.ts +64 -0
- package/lib/vendor/yaml/dist/parse/cst-scalar.js +218 -0
- package/lib/vendor/yaml/dist/parse/cst-stringify.d.ts +8 -0
- package/lib/vendor/yaml/dist/parse/cst-stringify.js +63 -0
- package/lib/vendor/yaml/dist/parse/cst-visit.d.ts +39 -0
- package/lib/vendor/yaml/dist/parse/cst-visit.js +99 -0
- package/lib/vendor/yaml/dist/parse/cst.d.ts +109 -0
- package/lib/vendor/yaml/dist/parse/cst.js +112 -0
- package/lib/vendor/yaml/dist/parse/lexer.d.ts +87 -0
- package/lib/vendor/yaml/dist/parse/lexer.js +723 -0
- package/lib/vendor/yaml/dist/parse/line-counter.d.ts +22 -0
- package/lib/vendor/yaml/dist/parse/line-counter.js +41 -0
- package/lib/vendor/yaml/dist/parse/parser.d.ts +84 -0
- package/lib/vendor/yaml/dist/parse/parser.js +980 -0
- package/lib/vendor/yaml/dist/public-api.d.ts +44 -0
- package/lib/vendor/yaml/dist/public-api.js +107 -0
- package/lib/vendor/yaml/dist/schema/Schema.d.ts +17 -0
- package/lib/vendor/yaml/dist/schema/Schema.js +39 -0
- package/lib/vendor/yaml/dist/schema/common/map.d.ts +2 -0
- package/lib/vendor/yaml/dist/schema/common/map.js +19 -0
- package/lib/vendor/yaml/dist/schema/common/null.d.ts +4 -0
- package/lib/vendor/yaml/dist/schema/common/null.js +17 -0
- package/lib/vendor/yaml/dist/schema/common/seq.d.ts +2 -0
- package/lib/vendor/yaml/dist/schema/common/seq.js +19 -0
- package/lib/vendor/yaml/dist/schema/common/string.d.ts +2 -0
- package/lib/vendor/yaml/dist/schema/common/string.js +16 -0
- package/lib/vendor/yaml/dist/schema/core/bool.d.ts +4 -0
- package/lib/vendor/yaml/dist/schema/core/bool.js +21 -0
- package/lib/vendor/yaml/dist/schema/core/float.d.ts +4 -0
- package/lib/vendor/yaml/dist/schema/core/float.js +47 -0
- package/lib/vendor/yaml/dist/schema/core/int.d.ts +4 -0
- package/lib/vendor/yaml/dist/schema/core/int.js +42 -0
- package/lib/vendor/yaml/dist/schema/core/schema.d.ts +1 -0
- package/lib/vendor/yaml/dist/schema/core/schema.js +25 -0
- package/lib/vendor/yaml/dist/schema/json/schema.d.ts +2 -0
- package/lib/vendor/yaml/dist/schema/json/schema.js +64 -0
- package/lib/vendor/yaml/dist/schema/json-schema.d.ts +69 -0
- package/lib/vendor/yaml/dist/schema/tags.d.ts +48 -0
- package/lib/vendor/yaml/dist/schema/tags.js +99 -0
- package/lib/vendor/yaml/dist/schema/types.d.ts +92 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/binary.d.ts +2 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/binary.js +70 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/bool.d.ts +7 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/bool.js +29 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/float.d.ts +4 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/float.js +50 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/int.d.ts +5 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/int.js +76 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/merge.d.ts +9 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/merge.js +71 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/omap.d.ts +22 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/omap.js +77 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/pairs.d.ts +10 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/pairs.js +82 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/schema.d.ts +1 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/schema.js +41 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/set.d.ts +28 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/set.js +96 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/timestamp.d.ts +6 -0
- package/lib/vendor/yaml/dist/schema/yaml-1.1/timestamp.js +105 -0
- package/lib/vendor/yaml/dist/stringify/foldFlowLines.d.ts +34 -0
- package/lib/vendor/yaml/dist/stringify/foldFlowLines.js +151 -0
- package/lib/vendor/yaml/dist/stringify/stringify.d.ts +21 -0
- package/lib/vendor/yaml/dist/stringify/stringify.js +132 -0
- package/lib/vendor/yaml/dist/stringify/stringifyCollection.d.ts +17 -0
- package/lib/vendor/yaml/dist/stringify/stringifyCollection.js +155 -0
- package/lib/vendor/yaml/dist/stringify/stringifyComment.d.ts +10 -0
- package/lib/vendor/yaml/dist/stringify/stringifyComment.js +24 -0
- package/lib/vendor/yaml/dist/stringify/stringifyDocument.d.ts +4 -0
- package/lib/vendor/yaml/dist/stringify/stringifyDocument.js +87 -0
- package/lib/vendor/yaml/dist/stringify/stringifyNumber.d.ts +2 -0
- package/lib/vendor/yaml/dist/stringify/stringifyNumber.js +27 -0
- package/lib/vendor/yaml/dist/stringify/stringifyPair.d.ts +3 -0
- package/lib/vendor/yaml/dist/stringify/stringifyPair.js +152 -0
- package/lib/vendor/yaml/dist/stringify/stringifyString.d.ts +9 -0
- package/lib/vendor/yaml/dist/stringify/stringifyString.js +338 -0
- package/lib/vendor/yaml/dist/test-events.d.ts +4 -0
- package/lib/vendor/yaml/dist/test-events.js +134 -0
- package/lib/vendor/yaml/dist/util.d.ts +16 -0
- package/lib/vendor/yaml/dist/util.js +28 -0
- package/lib/vendor/yaml/dist/visit.d.ts +102 -0
- package/lib/vendor/yaml/dist/visit.js +236 -0
- package/lib/vendor/yaml/package.json +97 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +62 -4
- package/profile/VAULT.md +221 -0
- package/skills/LICENSE +21 -0
- package/skills/defuddle/SKILL.md +43 -0
- package/skills/json-canvas/SKILL.md +253 -0
- package/skills/json-canvas/references/EXAMPLES.md +329 -0
- package/skills/knap/SKILL.md +102 -0
- package/skills/obsidian-bases/SKILL.md +601 -0
- package/skills/obsidian-bases/references/FUNCTIONS_REFERENCE.md +173 -0
- package/skills/obsidian-cli/SKILL.md +141 -0
- package/skills/obsidian-headless/SKILL.md +79 -0
- package/skills/obsidian-markdown/SKILL.md +202 -0
- package/skills/obsidian-markdown/references/CALLOUTS.md +58 -0
- package/skills/obsidian-markdown/references/EMBEDS.md +70 -0
- package/skills/obsidian-markdown/references/PROPERTIES.md +63 -0
package/lib/obsidian.js
ADDED
|
@@ -0,0 +1,735 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Obsidian vault discovery, per-conversation selection, and vault file access.
|
|
3
|
+
*
|
|
4
|
+
* Vaults come from Obsidian's own registry (`obsidian.json`) plus optional
|
|
5
|
+
* configured paths. The browser dropdown and the agent tool share this service,
|
|
6
|
+
* so the vault a person selects is exactly the vault the agent reads and writes.
|
|
7
|
+
*
|
|
8
|
+
* File access is vault-relative, refuses `..` and hidden segments, does not
|
|
9
|
+
* follow symlinks, and is limited to text files the connector skills create.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import fsp from 'node:fs/promises'
|
|
14
|
+
import os from 'node:os'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import { resolveCommand, runCommand } from './cli.js'
|
|
17
|
+
|
|
18
|
+
const DOCUMENT_EXTENSIONS = Object.freeze(['.md', '.canvas', '.base', '.txt'])
|
|
19
|
+
const SEARCHABLE_EXTENSIONS = Object.freeze(['.md'])
|
|
20
|
+
const DEFAULT_MAX_READ_BYTES = 400_000
|
|
21
|
+
const DEFAULT_MAX_WRITE_BYTES = 1_048_576
|
|
22
|
+
const MAX_WRITE_BYTES = 5 * 1024 * 1024
|
|
23
|
+
const STATUS_TTL_MS = 5_000
|
|
24
|
+
const MAX_SELECTIONS = 200
|
|
25
|
+
|
|
26
|
+
/** An expected, user-facing failure. */
|
|
27
|
+
export class ObsidianError extends Error {
|
|
28
|
+
/**
|
|
29
|
+
* @param {string} code - stable machine code.
|
|
30
|
+
* @param {string} message - sentence for the user or model.
|
|
31
|
+
*/
|
|
32
|
+
constructor(code, message) {
|
|
33
|
+
super(message)
|
|
34
|
+
this.name = 'ObsidianError'
|
|
35
|
+
this.code = code
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @param {string} input @param {string} [home] */
|
|
40
|
+
export function resolveHome(input, home = os.homedir()) {
|
|
41
|
+
const text = String(input ?? '').trim()
|
|
42
|
+
if (text === '~') return home
|
|
43
|
+
if (text.startsWith('~/') || text.startsWith('~\\')) return path.join(home, text.slice(2))
|
|
44
|
+
return path.resolve(text)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The default Obsidian configuration file for this platform. */
|
|
48
|
+
export function defaultObsidianConfigFile() {
|
|
49
|
+
if (typeof process.env.OBSIDIAN_CONFIG_PATH === 'string' && process.env.OBSIDIAN_CONFIG_PATH.trim().length > 0) {
|
|
50
|
+
return resolveHome(process.env.OBSIDIAN_CONFIG_PATH)
|
|
51
|
+
}
|
|
52
|
+
if (process.platform === 'darwin') {
|
|
53
|
+
return path.join(os.homedir(), 'Library', 'Application Support', 'obsidian', 'obsidian.json')
|
|
54
|
+
}
|
|
55
|
+
if (process.platform === 'win32') {
|
|
56
|
+
const appData = process.env.APPDATA ?? path.join(os.homedir(), 'AppData', 'Roaming')
|
|
57
|
+
return path.join(appData, 'obsidian', 'obsidian.json')
|
|
58
|
+
}
|
|
59
|
+
const configHome = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), '.config')
|
|
60
|
+
return path.join(configHome, 'obsidian', 'obsidian.json')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function defaultStateFile() {
|
|
64
|
+
const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
|
|
65
|
+
return path.join(home, 'obsidian-connector', 'state.json')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Normalize the plugin config.
|
|
70
|
+
* @param {unknown} raw
|
|
71
|
+
*/
|
|
72
|
+
export function normalizeConfig(raw) {
|
|
73
|
+
const config = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
|
74
|
+
const warnings = []
|
|
75
|
+
const vaults = []
|
|
76
|
+
const seen = new Set()
|
|
77
|
+
const push = (entry) => {
|
|
78
|
+
let vaultPath = ''
|
|
79
|
+
let name = ''
|
|
80
|
+
if (typeof entry === 'string') vaultPath = entry
|
|
81
|
+
else if (entry !== null && typeof entry === 'object' && typeof entry.path === 'string') {
|
|
82
|
+
vaultPath = entry.path
|
|
83
|
+
name = typeof entry.name === 'string' ? entry.name.trim() : ''
|
|
84
|
+
} else {
|
|
85
|
+
warnings.push('Ignored a vault entry that is neither a path nor an object with `path`.')
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
const resolved = resolveHome(vaultPath)
|
|
89
|
+
if (resolved.length === 0) return
|
|
90
|
+
const key = process.platform === 'win32' || process.platform === 'darwin' ? resolved.toLowerCase() : resolved
|
|
91
|
+
if (seen.has(key)) return
|
|
92
|
+
seen.add(key)
|
|
93
|
+
vaults.push({ name: name.length > 0 ? name : (path.basename(resolved) || 'Vault'), path: resolved, source: 'config' })
|
|
94
|
+
}
|
|
95
|
+
if (Array.isArray(config.vaults)) config.vaults.forEach(push)
|
|
96
|
+
const maxReadBytes = Number.isFinite(config.maxReadBytes)
|
|
97
|
+
? Math.min(Math.max(Math.trunc(Number(config.maxReadBytes)), 4096), 2_000_000)
|
|
98
|
+
: DEFAULT_MAX_READ_BYTES
|
|
99
|
+
const maxWriteBytes = Number.isFinite(config.maxWriteBytes)
|
|
100
|
+
? Math.min(Math.max(Math.trunc(Number(config.maxWriteBytes)), 1024), MAX_WRITE_BYTES)
|
|
101
|
+
: DEFAULT_MAX_WRITE_BYTES
|
|
102
|
+
return {
|
|
103
|
+
obsidianConfigFile: typeof config.obsidianConfigFile === 'string' && config.obsidianConfigFile.trim().length > 0
|
|
104
|
+
? resolveHome(config.obsidianConfigFile)
|
|
105
|
+
: defaultObsidianConfigFile(),
|
|
106
|
+
vaults,
|
|
107
|
+
allowWrite: config.allowWrite !== false,
|
|
108
|
+
maxReadBytes,
|
|
109
|
+
maxWriteBytes,
|
|
110
|
+
cliPath: typeof config.cliPath === 'string' && config.cliPath.trim().length > 0 ? config.cliPath.trim() : 'obsidian',
|
|
111
|
+
stateFile: typeof config.stateFile === 'string' && config.stateFile.trim().length > 0
|
|
112
|
+
? resolveHome(config.stateFile)
|
|
113
|
+
: defaultStateFile(),
|
|
114
|
+
warnings,
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Read Obsidian's vault registry. @param {string} file */
|
|
119
|
+
function readRegistry(file) {
|
|
120
|
+
let text
|
|
121
|
+
try {
|
|
122
|
+
text = fs.readFileSync(file, 'utf8')
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error !== null && typeof error === 'object' && error.code === 'ENOENT') {
|
|
125
|
+
return { found: false, vaults: [], cli: false, error: null }
|
|
126
|
+
}
|
|
127
|
+
return { found: false, vaults: [], cli: false, error: `Could not read ${file}: ${error instanceof Error ? error.message : String(error)}` }
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const parsed = JSON.parse(text)
|
|
131
|
+
const raw = parsed !== null && typeof parsed === 'object' && parsed.vaults !== null && typeof parsed.vaults === 'object'
|
|
132
|
+
? parsed.vaults
|
|
133
|
+
: {}
|
|
134
|
+
const vaults = Object.entries(raw)
|
|
135
|
+
.filter(([, value]) => value !== null && typeof value === 'object' && typeof value.path === 'string')
|
|
136
|
+
.map(([id, value]) => ({
|
|
137
|
+
id,
|
|
138
|
+
path: resolveHome(value.path),
|
|
139
|
+
ts: Number.isFinite(value.ts) ? Number(value.ts) : 0,
|
|
140
|
+
open: value.open === true,
|
|
141
|
+
source: 'obsidian',
|
|
142
|
+
}))
|
|
143
|
+
return { found: true, vaults, cli: parsed?.cli === true, error: null }
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return { found: true, vaults: [], cli: false, error: `Obsidian's registry is not valid JSON: ${error instanceof Error ? error.message : String(error)}` }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** @param {string} file */
|
|
150
|
+
function loadState(file) {
|
|
151
|
+
let text
|
|
152
|
+
try {
|
|
153
|
+
text = fs.readFileSync(file, 'utf8')
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error !== null && typeof error === 'object' && error.code === 'ENOENT') return { selected: {}, activeNote: true, enabled: true, error: null }
|
|
156
|
+
return { selected: {}, activeNote: true, enabled: true, error: `Could not read the saved vault selection: ${error instanceof Error ? error.message : String(error)}` }
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const parsed = JSON.parse(text)
|
|
160
|
+
const raw = parsed !== null && typeof parsed === 'object' && parsed.selected !== null && typeof parsed.selected === 'object'
|
|
161
|
+
? parsed.selected
|
|
162
|
+
: {}
|
|
163
|
+
const selected = {}
|
|
164
|
+
for (const [sessionId, vaultId] of Object.entries(raw)) {
|
|
165
|
+
if (typeof vaultId === 'string' && vaultId.length > 0) selected[sessionId] = vaultId
|
|
166
|
+
}
|
|
167
|
+
return { selected, activeNote: parsed?.activeNote !== false, enabled: parsed?.enabled !== false, error: null }
|
|
168
|
+
} catch (error) {
|
|
169
|
+
return { selected: {}, activeNote: true, enabled: true, error: `The saved vault selection is not valid JSON: ${error instanceof Error ? error.message : String(error)}` }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** @param {string} file @param {{selected: Record<string, string>, activeNote: boolean, enabled: boolean}} state */
|
|
174
|
+
async function saveState(file, state) {
|
|
175
|
+
await fsp.mkdir(path.dirname(file), { recursive: true })
|
|
176
|
+
const temporary = `${file}.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}.tmp`
|
|
177
|
+
await fsp.writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
178
|
+
await fsp.rename(temporary, file)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** @param {string} relPath */
|
|
182
|
+
function normalizeRelative(relPath) {
|
|
183
|
+
const raw = String(relPath ?? '').trim()
|
|
184
|
+
if (raw.length === 0) throw new ObsidianError('path-empty', 'A vault-relative path is required.')
|
|
185
|
+
if (raw.includes('\u0000')) throw new ObsidianError('path-invalid', 'Paths cannot contain null bytes.')
|
|
186
|
+
const forward = raw.replace(/\\/g, '/').replace(/^\.\/+/, '').replace(/^\/+/, '')
|
|
187
|
+
const segments = forward.split('/')
|
|
188
|
+
if (segments.some(part => part === '..')) throw new ObsidianError('path-outside', 'Paths must stay inside the vault.')
|
|
189
|
+
if (segments.some(part => part.startsWith('.'))) {
|
|
190
|
+
throw new ObsidianError('path-hidden', 'Hidden files and folders are not accessible through the connector.')
|
|
191
|
+
}
|
|
192
|
+
if (forward.length === 0) throw new ObsidianError('path-empty', 'A vault-relative path is required.')
|
|
193
|
+
return forward
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** @param {string} root @param {string} absolute */
|
|
197
|
+
function assertInside(root, absolute) {
|
|
198
|
+
const relative = path.relative(root, absolute)
|
|
199
|
+
if (relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))) return
|
|
200
|
+
throw new ObsidianError('path-outside', 'Paths must stay inside the vault.')
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** @param {string} root @param {string} relPath @param {{forWrite?: boolean}} [options] */
|
|
204
|
+
async function resolveInside(root, relPath, options = {}) {
|
|
205
|
+
const relative = normalizeRelative(relPath)
|
|
206
|
+
const absolute = path.resolve(root, relative)
|
|
207
|
+
assertInside(root, absolute)
|
|
208
|
+
if (options.forWrite === true) {
|
|
209
|
+
const parent = path.dirname(absolute)
|
|
210
|
+
// Check the deepest existing ancestor before creating anything, so a
|
|
211
|
+
// symlinked directory cannot redirect the mkdir outside the vault.
|
|
212
|
+
await assertExistingAncestorsInside(root, parent)
|
|
213
|
+
await fsp.mkdir(parent, { recursive: true })
|
|
214
|
+
assertInside(root, await fsp.realpath(parent))
|
|
215
|
+
if (fs.existsSync(absolute)) assertInside(root, await fsp.realpath(absolute))
|
|
216
|
+
} else {
|
|
217
|
+
assertInside(root, await fsp.realpath(absolute))
|
|
218
|
+
}
|
|
219
|
+
return absolute
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Walk up to the deepest existing directory and verify it resolves inside the vault. */
|
|
223
|
+
async function assertExistingAncestorsInside(root, absolute) {
|
|
224
|
+
let current = absolute
|
|
225
|
+
while (true) {
|
|
226
|
+
if (fs.existsSync(current)) {
|
|
227
|
+
assertInside(root, await fsp.realpath(current))
|
|
228
|
+
return
|
|
229
|
+
}
|
|
230
|
+
const parent = path.dirname(current)
|
|
231
|
+
if (parent === current) return
|
|
232
|
+
current = parent
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** @param {string} absolute @param {number} limit */
|
|
237
|
+
async function readTextCapped(absolute, limit) {
|
|
238
|
+
const handle = await fsp.open(absolute, 'r')
|
|
239
|
+
try {
|
|
240
|
+
const stat = await handle.stat()
|
|
241
|
+
const length = Math.min(stat.size, limit + 1)
|
|
242
|
+
const buffer = Buffer.alloc(length)
|
|
243
|
+
const { bytesRead } = await handle.read(buffer, 0, length, 0)
|
|
244
|
+
const bytes = buffer.subarray(0, bytesRead)
|
|
245
|
+
if (bytes.includes(0)) throw new ObsidianError('binary-file', 'Only text files can be read.')
|
|
246
|
+
let text = bytes.toString('utf8')
|
|
247
|
+
const truncated = stat.size > limit
|
|
248
|
+
if (truncated) {
|
|
249
|
+
const lastBreak = text.lastIndexOf('\n')
|
|
250
|
+
if (lastBreak > 0) text = text.slice(0, lastBreak)
|
|
251
|
+
}
|
|
252
|
+
return { text, bytes: stat.size, mtimeMs: stat.mtimeMs, truncated }
|
|
253
|
+
} finally {
|
|
254
|
+
await handle.close()
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Walk a vault, skipping hidden folders and symlinks.
|
|
260
|
+
* @param {string} root
|
|
261
|
+
* @param {{extensions: readonly string[], maxFiles?: number}} options
|
|
262
|
+
*/
|
|
263
|
+
async function walkVault(root, options) {
|
|
264
|
+
const files = []
|
|
265
|
+
const queue = ['']
|
|
266
|
+
let cursor = 0
|
|
267
|
+
while (cursor < queue.length) {
|
|
268
|
+
const relDir = queue[cursor]
|
|
269
|
+
cursor += 1
|
|
270
|
+
const absDir = relDir.length === 0 ? root : path.join(root, relDir)
|
|
271
|
+
let entries
|
|
272
|
+
try {
|
|
273
|
+
entries = await fsp.readdir(absDir, { withFileTypes: true })
|
|
274
|
+
} catch {
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
entries.sort((left, right) => left.name.localeCompare(right.name))
|
|
278
|
+
for (const entry of entries) {
|
|
279
|
+
if (entry.name.startsWith('.')) continue
|
|
280
|
+
const relative = relDir.length === 0 ? entry.name : `${relDir}/${entry.name}`
|
|
281
|
+
if (entry.isSymbolicLink()) continue
|
|
282
|
+
if (entry.isDirectory()) {
|
|
283
|
+
if (entry.name !== 'node_modules') queue.push(relative)
|
|
284
|
+
continue
|
|
285
|
+
}
|
|
286
|
+
if (!entry.isFile()) continue
|
|
287
|
+
if (!options.extensions.includes(path.extname(entry.name).toLowerCase())) continue
|
|
288
|
+
files.push(relative)
|
|
289
|
+
if (files.length >= (options.maxFiles ?? 4000)) return { files, truncated: true }
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return { files, truncated: false }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** @param {unknown} value @param {number} min @param {number} max @param {number} fallback */
|
|
296
|
+
function clampInt(value, min, max, fallback) {
|
|
297
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
|
|
298
|
+
return Math.min(Math.max(Math.trunc(value), min), max)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Create the Obsidian service.
|
|
303
|
+
* @param {unknown} rawConfig
|
|
304
|
+
* @param {{stateFile?: string, obsidianConfigFile?: string}} [options] - test overrides.
|
|
305
|
+
*/
|
|
306
|
+
export function createObsidianService(rawConfig, options = {}) {
|
|
307
|
+
const settings = normalizeConfig(rawConfig)
|
|
308
|
+
if (typeof options.stateFile === 'string') settings.stateFile = options.stateFile
|
|
309
|
+
if (typeof options.obsidianConfigFile === 'string') settings.obsidianConfigFile = options.obsidianConfigFile
|
|
310
|
+
const loaded = loadState(settings.stateFile)
|
|
311
|
+
const state = { selected: loaded.selected, activeNote: loaded.activeNote !== false, enabled: loaded.enabled !== false }
|
|
312
|
+
const stateWarning = loaded.error
|
|
313
|
+
let cache = null
|
|
314
|
+
let saveQueue = Promise.resolve()
|
|
315
|
+
|
|
316
|
+
const discover = () => {
|
|
317
|
+
const now = Date.now()
|
|
318
|
+
if (cache !== null && now - cache.at < STATUS_TTL_MS) return cache.value
|
|
319
|
+
const registry = readRegistry(settings.obsidianConfigFile)
|
|
320
|
+
const merged = []
|
|
321
|
+
const seen = new Set()
|
|
322
|
+
const add = (vault) => {
|
|
323
|
+
const key = process.platform === 'win32' || process.platform === 'darwin' ? vault.path.toLowerCase() : vault.path
|
|
324
|
+
if (seen.has(key)) return
|
|
325
|
+
seen.add(key)
|
|
326
|
+
let exists = false
|
|
327
|
+
try {
|
|
328
|
+
exists = fs.statSync(vault.path).isDirectory()
|
|
329
|
+
} catch {
|
|
330
|
+
exists = false
|
|
331
|
+
}
|
|
332
|
+
merged.push({ ...vault, name: vault.name || path.basename(vault.path) || 'Vault', exists })
|
|
333
|
+
}
|
|
334
|
+
for (const vault of registry.vaults) add(vault)
|
|
335
|
+
settings.vaults.forEach((vault, index) => add({ ...vault, id: `config:${vault.path}`, ts: -index, open: false }))
|
|
336
|
+
merged.sort((left, right) => {
|
|
337
|
+
if (left.open !== right.open) return left.open ? -1 : 1
|
|
338
|
+
if (left.ts !== right.ts) return right.ts - left.ts
|
|
339
|
+
return left.name.localeCompare(right.name)
|
|
340
|
+
})
|
|
341
|
+
// Disambiguate same-named vaults by their parent folder.
|
|
342
|
+
const counts = new Map()
|
|
343
|
+
for (const vault of merged) counts.set(vault.name, (counts.get(vault.name) ?? 0) + 1)
|
|
344
|
+
for (const vault of merged) {
|
|
345
|
+
vault.label = (counts.get(vault.name) ?? 0) > 1
|
|
346
|
+
? `${vault.name} · ${path.basename(path.dirname(vault.path))}`
|
|
347
|
+
: vault.name
|
|
348
|
+
}
|
|
349
|
+
const value = {
|
|
350
|
+
vaults: merged,
|
|
351
|
+
cli: registry.cli,
|
|
352
|
+
registryFile: settings.obsidianConfigFile,
|
|
353
|
+
registryFound: registry.found,
|
|
354
|
+
warnings: [
|
|
355
|
+
...settings.warnings,
|
|
356
|
+
...(stateWarning === null ? [] : [stateWarning]),
|
|
357
|
+
...(registry.error === null ? [] : [registry.error]),
|
|
358
|
+
],
|
|
359
|
+
}
|
|
360
|
+
cache = { at: now, value }
|
|
361
|
+
return value
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const byId = (id) => discover().vaults.find(vault => vault.id === id) ?? null
|
|
365
|
+
|
|
366
|
+
/** The explicitly selected vault for a conversation, or null. */
|
|
367
|
+
const selectedVault = (sessionId) => {
|
|
368
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return null
|
|
369
|
+
const id = state.selected[sessionId]
|
|
370
|
+
return typeof id === 'string' ? byId(id) : null
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Resolve the vault a tool call targets, with guidance when none is selected. */
|
|
374
|
+
const requireVault = (sessionId) => {
|
|
375
|
+
const id = typeof sessionId === 'string' ? state.selected[sessionId] : undefined
|
|
376
|
+
if (id === undefined) {
|
|
377
|
+
throw new ObsidianError('no-vault', 'No Obsidian vault is selected for this conversation. Ask the user to choose one from the vault dropdown in the composer.')
|
|
378
|
+
}
|
|
379
|
+
const vault = byId(id)
|
|
380
|
+
if (vault === null) {
|
|
381
|
+
throw new ObsidianError('vault-missing', 'The selected Obsidian vault is no longer registered. Ask the user to choose another one in the composer dropdown.')
|
|
382
|
+
}
|
|
383
|
+
if (!vault.exists) throw new ObsidianError('vault-folder-missing', `The selected vault folder does not exist: ${vault.path}`)
|
|
384
|
+
return vault
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Remove the conversation's vault choice. */
|
|
388
|
+
const clear = async (sessionId) => {
|
|
389
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) throw new ObsidianError('session-missing', 'A conversation id is required.')
|
|
390
|
+
if (!(sessionId in state.selected)) return { selectedId: null }
|
|
391
|
+
const operation = saveQueue.then(async () => {
|
|
392
|
+
const next = { ...state.selected }
|
|
393
|
+
delete next[sessionId]
|
|
394
|
+
await saveState(settings.stateFile, { selected: next, activeNote: state.activeNote, enabled: state.enabled })
|
|
395
|
+
state.selected = next
|
|
396
|
+
})
|
|
397
|
+
saveQueue = operation.then(() => undefined, () => undefined)
|
|
398
|
+
await operation
|
|
399
|
+
return { selectedId: null }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** The registry payload the browser dropdown reads. */
|
|
403
|
+
const list = (sessionId) => {
|
|
404
|
+
const data = discover()
|
|
405
|
+
const storedId = typeof sessionId === 'string' ? state.selected[sessionId] : undefined
|
|
406
|
+
const selected = selectedVault(sessionId)
|
|
407
|
+
return {
|
|
408
|
+
vaults: data.vaults.map(vault => ({
|
|
409
|
+
id: vault.id,
|
|
410
|
+
label: vault.label,
|
|
411
|
+
path: vault.path,
|
|
412
|
+
open: vault.open,
|
|
413
|
+
exists: vault.exists,
|
|
414
|
+
})),
|
|
415
|
+
selectedId: selected?.id ?? null,
|
|
416
|
+
enabled: state.enabled,
|
|
417
|
+
stale: typeof storedId === 'string' && selected === null,
|
|
418
|
+
cli: data.cli,
|
|
419
|
+
registryFile: data.registryFile,
|
|
420
|
+
registryFound: data.registryFound,
|
|
421
|
+
warnings: data.warnings,
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Persist the conversation's vault choice, serialized with other saves. */
|
|
426
|
+
const select = async (sessionId, vaultId) => {
|
|
427
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) throw new ObsidianError('session-missing', 'A conversation id is required.')
|
|
428
|
+
if (typeof vaultId !== 'string' || vaultId.length === 0) throw new ObsidianError('vault-id-missing', 'A vault id is required.')
|
|
429
|
+
const vault = byId(vaultId)
|
|
430
|
+
if (vault === null) throw new ObsidianError('vault-unknown', 'That Obsidian vault is not available.')
|
|
431
|
+
if (!vault.exists) throw new ObsidianError('vault-folder-missing', `The vault folder does not exist: ${vault.path}`)
|
|
432
|
+
const operation = saveQueue.then(async () => {
|
|
433
|
+
const next = { ...state.selected }
|
|
434
|
+
delete next[sessionId]
|
|
435
|
+
next[sessionId] = vaultId
|
|
436
|
+
const keys = Object.keys(next)
|
|
437
|
+
if (keys.length > MAX_SELECTIONS) {
|
|
438
|
+
for (const key of keys.slice(0, keys.length - MAX_SELECTIONS)) delete next[key]
|
|
439
|
+
}
|
|
440
|
+
await saveState(settings.stateFile, { selected: next, activeNote: state.activeNote, enabled: state.enabled })
|
|
441
|
+
// Publish in memory only after the file write succeeded, so a failed save
|
|
442
|
+
// never leaves the agent on a vault the dropdown did not accept.
|
|
443
|
+
state.selected = next
|
|
444
|
+
})
|
|
445
|
+
saveQueue = operation.then(() => undefined, () => undefined)
|
|
446
|
+
await operation
|
|
447
|
+
return { selectedId: vaultId }
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Prompt context for an agent's next assembly, empty without an explicit choice. */
|
|
451
|
+
const promptText = (sessionId) => {
|
|
452
|
+
const vault = selectedVault(sessionId)
|
|
453
|
+
if (vault === null) return ''
|
|
454
|
+
return [
|
|
455
|
+
`Obsidian vault for this conversation: "${vault.name}" at ${vault.path}.`,
|
|
456
|
+
'Use the obsidian_file tool with vault-relative paths to read, list, search, create, or update files there. Run obsidian (app CLI) with bash and pass vault="' + vault.name + '" when it needs a target; run ob (Headless) with --path "' + vault.path + '".',
|
|
457
|
+
].join('\n')
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** @param {string} sessionId @param {string} relPath */
|
|
461
|
+
const read = async (sessionId, relPath) => {
|
|
462
|
+
const vault = requireVault(sessionId)
|
|
463
|
+
const root = await fsp.realpath(vault.path)
|
|
464
|
+
const relative = normalizeRelative(relPath)
|
|
465
|
+
const extension = path.extname(relative).toLowerCase()
|
|
466
|
+
if (!DOCUMENT_EXTENSIONS.includes(extension)) {
|
|
467
|
+
throw new ObsidianError('unsupported-file', `Only ${DOCUMENT_EXTENSIONS.join(', ')} files can be read.`)
|
|
468
|
+
}
|
|
469
|
+
let absolute
|
|
470
|
+
try {
|
|
471
|
+
absolute = await resolveInside(root, relative)
|
|
472
|
+
} catch (error) {
|
|
473
|
+
if (error instanceof ObsidianError) throw error
|
|
474
|
+
throw new ObsidianError('file-missing', `No such file in the vault: ${relative}`)
|
|
475
|
+
}
|
|
476
|
+
const { text, bytes, mtimeMs, truncated } = await readTextCapped(absolute, settings.maxReadBytes)
|
|
477
|
+
return { vault: vault.name, path: relative, content: text, bytes, mtimeMs, truncated }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** @param {string} sessionId @param {{path: string, content: string, mode?: string}} request */
|
|
481
|
+
const write = async (sessionId, request) => {
|
|
482
|
+
if (!settings.allowWrite) throw new ObsidianError('write-disabled', 'Writing is disabled by this plugin\'s `allowWrite: false` config.')
|
|
483
|
+
const vault = requireVault(sessionId)
|
|
484
|
+
const root = await fsp.realpath(vault.path)
|
|
485
|
+
const relative = normalizeRelative(request?.path)
|
|
486
|
+
const extension = path.extname(relative).toLowerCase()
|
|
487
|
+
if (!DOCUMENT_EXTENSIONS.includes(extension)) {
|
|
488
|
+
throw new ObsidianError('unsupported-file', `Only ${DOCUMENT_EXTENSIONS.join(', ')} files can be written.`)
|
|
489
|
+
}
|
|
490
|
+
if (typeof request?.content !== 'string') throw new ObsidianError('content-missing', '`content` must be a string.')
|
|
491
|
+
const mode = request.mode ?? 'create'
|
|
492
|
+
if (!['create', 'overwrite', 'append'].includes(mode)) throw new ObsidianError('mode-invalid', '`mode` must be create, overwrite, or append.')
|
|
493
|
+
const bytes = Buffer.byteLength(request.content, 'utf8')
|
|
494
|
+
if (bytes > settings.maxWriteBytes) throw new ObsidianError('file-too-large', `The content exceeds the ${settings.maxWriteBytes}-byte limit.`)
|
|
495
|
+
const absolute = await resolveInside(root, relative, { forWrite: true })
|
|
496
|
+
const exists = fs.existsSync(absolute)
|
|
497
|
+
if (mode === 'create' && exists) throw new ObsidianError('file-exists', `The file already exists: ${relative}`)
|
|
498
|
+
|
|
499
|
+
if (mode === 'append' && exists) {
|
|
500
|
+
// Append at the end without a capped re-read: a large existing note keeps
|
|
501
|
+
// every byte. Add a separating newline only when the file does not end
|
|
502
|
+
// with one.
|
|
503
|
+
const stat = await fsp.stat(absolute)
|
|
504
|
+
if (stat.size + bytes > settings.maxWriteBytes) {
|
|
505
|
+
throw new ObsidianError('file-too-large', `The file would exceed the ${settings.maxWriteBytes}-byte limit.`)
|
|
506
|
+
}
|
|
507
|
+
let prefix = ''
|
|
508
|
+
if (stat.size > 0) {
|
|
509
|
+
const handle = await fsp.open(absolute, 'r')
|
|
510
|
+
try {
|
|
511
|
+
const last = Buffer.alloc(1)
|
|
512
|
+
await handle.read(last, 0, 1, stat.size - 1)
|
|
513
|
+
if (last[0] !== 0x0a) prefix = '\n'
|
|
514
|
+
} finally {
|
|
515
|
+
await handle.close()
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
await fsp.appendFile(absolute, prefix + request.content, 'utf8')
|
|
519
|
+
const updated = await fsp.stat(absolute)
|
|
520
|
+
return { vault: vault.name, path: relative, bytes: updated.size, created: false, mode }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const temporary = `${absolute}.${process.pid}.${Date.now().toString(36)}.tmp`
|
|
524
|
+
await fsp.writeFile(temporary, request.content, 'utf8')
|
|
525
|
+
await fsp.rename(temporary, absolute)
|
|
526
|
+
return { vault: vault.name, path: relative, bytes, created: !exists, mode }
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** @param {string} sessionId @param {{folder?: string, limit?: number}} request */
|
|
530
|
+
const listFiles = async (sessionId, request = {}) => {
|
|
531
|
+
const vault = requireVault(sessionId)
|
|
532
|
+
const root = await fsp.realpath(vault.path)
|
|
533
|
+
const folder = typeof request.folder === 'string' && request.folder.trim().length > 0
|
|
534
|
+
? normalizeRelative(request.folder).replace(/\/+$/, '')
|
|
535
|
+
: ''
|
|
536
|
+
const limit = clampInt(request.limit, 1, 200, 200)
|
|
537
|
+
const { files, truncated } = await walkVault(root, { extensions: ['.md', '.canvas', '.base'], maxFiles: 4000 })
|
|
538
|
+
const filtered = folder.length === 0 ? files : files.filter(file => file === folder || file.startsWith(`${folder}/`))
|
|
539
|
+
return {
|
|
540
|
+
vault: vault.name,
|
|
541
|
+
folder,
|
|
542
|
+
total: filtered.length,
|
|
543
|
+
truncated: truncated || filtered.length > limit,
|
|
544
|
+
paths: filtered.slice(0, limit),
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** @param {string} sessionId @param {{query?: string, folder?: string, limit?: number}} request */
|
|
549
|
+
const search = async (sessionId, request = {}) => {
|
|
550
|
+
const vault = requireVault(sessionId)
|
|
551
|
+
const root = await fsp.realpath(vault.path)
|
|
552
|
+
const query = typeof request.query === 'string' ? request.query.trim() : ''
|
|
553
|
+
if (query.length === 0) throw new ObsidianError('query-missing', '`query` is required.')
|
|
554
|
+
const folder = typeof request.folder === 'string' && request.folder.trim().length > 0
|
|
555
|
+
? normalizeRelative(request.folder).replace(/\/+$/, '')
|
|
556
|
+
: ''
|
|
557
|
+
const limit = clampInt(request.limit, 1, 100, 30)
|
|
558
|
+
const { files, truncated: walkTruncated } = await walkVault(root, { extensions: SEARCHABLE_EXTENSIONS, maxFiles: 4000 })
|
|
559
|
+
const matches = []
|
|
560
|
+
let scanned = 0
|
|
561
|
+
let skipped = 0
|
|
562
|
+
let truncated = walkTruncated
|
|
563
|
+
const needle = query.toLowerCase()
|
|
564
|
+
for (const relative of files) {
|
|
565
|
+
if (scanned >= 800) {
|
|
566
|
+
truncated = true
|
|
567
|
+
break
|
|
568
|
+
}
|
|
569
|
+
if (folder.length > 0 && relative !== folder && !relative.startsWith(`${folder}/`)) continue
|
|
570
|
+
const absolute = path.join(root, relative)
|
|
571
|
+
const stat = await fsp.stat(absolute).catch(() => null)
|
|
572
|
+
if (stat === null) continue
|
|
573
|
+
if (stat.size > 2 * 1024 * 1024) {
|
|
574
|
+
skipped += 1
|
|
575
|
+
truncated = true
|
|
576
|
+
continue
|
|
577
|
+
}
|
|
578
|
+
scanned += 1
|
|
579
|
+
let text
|
|
580
|
+
try {
|
|
581
|
+
text = (await readTextCapped(absolute, Math.min(stat.size, 2 * 1024 * 1024))).text
|
|
582
|
+
} catch {
|
|
583
|
+
skipped += 1
|
|
584
|
+
truncated = true
|
|
585
|
+
continue
|
|
586
|
+
}
|
|
587
|
+
const lines = text.split(/\r?\n/)
|
|
588
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
589
|
+
const line = lines[index]
|
|
590
|
+
if (!line.toLowerCase().includes(needle)) continue
|
|
591
|
+
matches.push({ path: relative, line: index + 1, text: line.trim().slice(0, 240) })
|
|
592
|
+
if (matches.length >= limit) {
|
|
593
|
+
truncated = true
|
|
594
|
+
break
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
if (matches.length >= limit) break
|
|
598
|
+
}
|
|
599
|
+
return { vault: vault.name, query, scanned, skipped, truncated, matches }
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const preferenceListeners = new Set()
|
|
603
|
+
const notifyPreferences = () => {
|
|
604
|
+
const value = { activeNote: state.activeNote, enabled: state.enabled }
|
|
605
|
+
for (const listener of preferenceListeners) {
|
|
606
|
+
try {
|
|
607
|
+
listener(value)
|
|
608
|
+
} catch {
|
|
609
|
+
// A listener must not break a completed preference write.
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** The plugin's behavior preferences. */
|
|
615
|
+
const getPreferences = () => ({ activeNote: state.activeNote, enabled: state.enabled })
|
|
616
|
+
|
|
617
|
+
/** Subscribe to preference changes; returns an unsubscribe function. */
|
|
618
|
+
const onPreferences = (listener) => {
|
|
619
|
+
if (typeof listener !== 'function') return () => {}
|
|
620
|
+
preferenceListeners.add(listener)
|
|
621
|
+
return () => preferenceListeners.delete(listener)
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** Persist the active-note preference. */
|
|
625
|
+
const setActiveNote = async (enabled) => {
|
|
626
|
+
if (typeof enabled !== 'boolean') throw new ObsidianError('setting-invalid', '`activeNote` must be a boolean.')
|
|
627
|
+
const operation = saveQueue.then(async () => {
|
|
628
|
+
await saveState(settings.stateFile, { selected: state.selected, activeNote: enabled, enabled: state.enabled })
|
|
629
|
+
state.activeNote = enabled
|
|
630
|
+
})
|
|
631
|
+
saveQueue = operation.then(() => undefined, () => undefined)
|
|
632
|
+
await operation
|
|
633
|
+
notifyPreferences()
|
|
634
|
+
return getPreferences()
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Persist the connector's master enable flag. */
|
|
638
|
+
const setEnabled = async (enabled) => {
|
|
639
|
+
if (typeof enabled !== 'boolean') throw new ObsidianError('setting-invalid', '`enabled` must be a boolean.')
|
|
640
|
+
const operation = saveQueue.then(async () => {
|
|
641
|
+
await saveState(settings.stateFile, { selected: state.selected, activeNote: state.activeNote, enabled })
|
|
642
|
+
state.enabled = enabled
|
|
643
|
+
})
|
|
644
|
+
saveQueue = operation.then(() => undefined, () => undefined)
|
|
645
|
+
await operation
|
|
646
|
+
notifyPreferences()
|
|
647
|
+
return getPreferences()
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** List folders of one vault for the settings page's path picker. */
|
|
651
|
+
const listFolders = async (vaultId) => {
|
|
652
|
+
const vault = byId(vaultId)
|
|
653
|
+
if (vault === null) throw new ObsidianError('vault-unknown', 'That Obsidian vault is not available.')
|
|
654
|
+
if (!vault.exists) throw new ObsidianError('vault-folder-missing', `The vault folder does not exist: ${vault.path}`)
|
|
655
|
+
const root = await fsp.realpath(vault.path)
|
|
656
|
+
const folders = []
|
|
657
|
+
const queue = ['']
|
|
658
|
+
while (queue.length > 0 && folders.length < 500) {
|
|
659
|
+
const relDir = queue.shift()
|
|
660
|
+
const absDir = relDir.length === 0 ? root : path.join(root, relDir)
|
|
661
|
+
let entries
|
|
662
|
+
try {
|
|
663
|
+
entries = await fsp.readdir(absDir, { withFileTypes: true })
|
|
664
|
+
} catch {
|
|
665
|
+
continue
|
|
666
|
+
}
|
|
667
|
+
entries.sort((left, right) => left.name.localeCompare(right.name))
|
|
668
|
+
for (const entry of entries) {
|
|
669
|
+
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules') continue
|
|
670
|
+
const relative = relDir.length === 0 ? entry.name : `${relDir}/${entry.name}`
|
|
671
|
+
folders.push(relative)
|
|
672
|
+
if (folders.length >= 500) break
|
|
673
|
+
queue.push(relative)
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
folders.sort((left, right) => left.localeCompare(right))
|
|
677
|
+
return { vault: vault.name, folders }
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** Ask the running Obsidian app for its active file, as a vault-relative path. */
|
|
681
|
+
const readActiveNote = async (vault) => {
|
|
682
|
+
const executable = await resolveCommand(settings.cliPath)
|
|
683
|
+
if (executable === null) return null
|
|
684
|
+
const code = 'JSON.stringify({vault:app.workspace.getActiveFile()?.vault?.getName() ?? "", path:app.workspace.getActiveFile()?.path ?? ""})'
|
|
685
|
+
let result
|
|
686
|
+
try {
|
|
687
|
+
result = await runCommand(executable, [`vault=${vault.name}`, 'eval', `code=${code}`], {
|
|
688
|
+
cwd: vault.path,
|
|
689
|
+
timeoutMs: 2500,
|
|
690
|
+
maxBytes: 64 * 1024,
|
|
691
|
+
})
|
|
692
|
+
} catch {
|
|
693
|
+
return null
|
|
694
|
+
}
|
|
695
|
+
if (!result.ok) return null
|
|
696
|
+
const line = result.stdout.trim().split(/\r?\n/).filter(Boolean).pop() ?? ''
|
|
697
|
+
const jsonText = line.startsWith('=> ') ? line.slice(3) : line
|
|
698
|
+
let parsed
|
|
699
|
+
try {
|
|
700
|
+
parsed = JSON.parse(jsonText)
|
|
701
|
+
} catch {
|
|
702
|
+
return null
|
|
703
|
+
}
|
|
704
|
+
if (!parsed || parsed.vault !== vault.name || typeof parsed.path !== 'string' || parsed.path.length === 0) return null
|
|
705
|
+
const filePath = parsed.path.replace(/^file:/, '')
|
|
706
|
+
const relative = path.relative(vault.path, filePath).replace(/\\/g, '/')
|
|
707
|
+
if (relative.length === 0 || relative.startsWith('..') || path.isAbsolute(relative)) return null
|
|
708
|
+
if (relative.split('/').some(part => part.startsWith('.'))) return null
|
|
709
|
+
return relative
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
return {
|
|
713
|
+
settings,
|
|
714
|
+
stateFile: settings.stateFile,
|
|
715
|
+
list,
|
|
716
|
+
select,
|
|
717
|
+
clear,
|
|
718
|
+
selectedVault,
|
|
719
|
+
requireVault,
|
|
720
|
+
promptText,
|
|
721
|
+
read,
|
|
722
|
+
write,
|
|
723
|
+
listFiles,
|
|
724
|
+
search,
|
|
725
|
+
getPreferences,
|
|
726
|
+
onPreferences,
|
|
727
|
+
setActiveNote,
|
|
728
|
+
setEnabled,
|
|
729
|
+
listFolders,
|
|
730
|
+
readActiveNote,
|
|
731
|
+
refresh() {
|
|
732
|
+
cache = null
|
|
733
|
+
},
|
|
734
|
+
}
|
|
735
|
+
}
|