dsh-snip 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +107 -7
  3. package/index.js +437 -6
  4. package/package.json +31 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ - Screen `sourceApp` for secrets and validate it: non-strings, control
6
+ characters, labels over 80 characters and secret-looking labels are rejected
7
+ with `SNIP_BAD_SOURCE_APP`; empty labels become `unknown`. Persisted
8
+ snapshots are re-sanitized on load.
9
+ - Persist before committing: `add`, `forget`, `clear` and expiry sweeps build
10
+ the next ledger state, write it, and only then replace memory. A failed write
11
+ now throws `SNIP_STATE_WRITE_FAILED` and leaves both memory and disk at the
12
+ previous state instead of letting them diverge.
13
+ - Confirm and test the redaction boundary: `search` only scans stored (already
14
+ redacted) text, and `forget` leaves no in-memory index or snapshot residue.
15
+ - Add failure-injection tests for a read-only state directory and regression
16
+ tests for `sourceApp`, search-after-redaction and forget-after-reload.
17
+
18
+ ## 0.1.0
19
+
20
+ - Implement `SnipService` with `add`, `list`, `search`, `get`, `forget` and
21
+ `clear`, plus stable `clipboard://<id>` handles.
22
+ - Exclude secrets by default: `sk-...`, `ghp_...` / `github_pat_...`,
23
+ `AKIA...` / `ASIA...`, PEM/PGP private keys, `password=...`, API keys,
24
+ bearer tokens, JWTs and common provider tokens. Matching input is never
25
+ stored; only `[redacted:<reason>]` is kept and `redacted` is `true`.
26
+ - Add a 24-hour default TTL, a 200-entry cap and a 64 KiB per-entry cap with
27
+ automatic expiry and oldest-first eviction.
28
+ - Add optional atomic JSON snapshots through `stateFile` (temporary file plus
29
+ `rename`, mode `0600`, re-screened on load).
30
+ - Provide `ctx.snip` and six plain-object agent tools: `snip_add`,
31
+ `snip_search`, `snip_get`, `snip_list`, `snip_forget`, `snip_clear`.
32
+ - 0.1.0 is a ledger only: no OS clipboard polling, no background capture, no
33
+ network access and no encryption yet.
34
+ - Add `node --test` coverage for CRUD, handles, redaction, TTL/eviction,
35
+ persistence and tool registration.
36
+
3
37
  ## 0.0.1
4
38
 
5
39
  - Reserve the `dsh-snip` package name.
package/README.md CHANGED
@@ -1,9 +1,17 @@
1
1
  # Snip · `dsh-snip`
2
2
 
3
- > Encrypted, searchable clipboard ledger for DeepSeek Harness with secret exclusion and agent handles.
3
+ > A local-first clipboard ledger for DeepSeek Harness with secret exclusion and
4
+ > `clipboard://` agent handles.
4
5
 
5
- **Status: 0.0.1 name reservation.** The working design lives in the
6
- [dsh-os design notes](https://github.com/PerryLink/dsh-os#readme). A functional MVP is planned for 0.1.0.
6
+ **Status: 0.1.1 (MVP). A ledger, not a background listener.** Snip records a
7
+ clipping only when a caller explicitly invokes `snip.add(...)` or the `snip_add`
8
+ agent tool. 0.1.1 has no OS clipboard polling, no `snip_capture`, no network
9
+ access and no encryption yet. Secret-looking text is excluded by default.
10
+ Everything stays on this machine: entries live in process memory, plus an
11
+ optional local JSON snapshot when `stateFile` is configured.
12
+
13
+ In one sentence: **0.1.1 is a ledger, not a background listener; it excludes
14
+ secrets by default and stores clippings locally.**
7
15
 
8
16
  **Not affiliated with DeepSeek.** DeepSeek and DeepSeek Harness are trademarks
9
17
  of their respective owners.
@@ -14,8 +22,100 @@ of their respective owners.
14
22
  dsh plugin --profile web add dsh-snip
15
23
  ```
16
24
 
17
- ## Design
25
+ The bundle patch mounts the plugin and provides `ctx.snip`.
26
+
27
+ ## Host service
28
+
29
+ ```js
30
+ const snip = ctx.get('snip')
31
+
32
+ const clip = snip.add({ text: 'SELECT * FROM users', sourceApp: 'psql' })
33
+ // { id, handle: 'clipboard://<id>', kind: 'text', preview, createdAt, expiresAt, redacted }
34
+
35
+ snip.get(clip.handle).text // original text, or '[redacted:<reason>]'
36
+ snip.search('select') // newest-first summaries
37
+ snip.list({ kind: 'text', limit: 20 })
38
+ snip.forget(clip.id) // true when it existed
39
+ snip.clear() // number removed
40
+ ```
41
+
42
+ `add()` accepts `{ text, kind = 'text', sourceApp = 'unknown', sensitivity = 'normal' }`.
43
+ Supported kinds are `text`, `html`, `link` and `color`; sensitivities are
44
+ `normal`, `sensitive` and `secret` (`secret` always redacts). Handles are
45
+ `clipboard://<id>` and are accepted anywhere an id is accepted. `get()` returns
46
+ `null` for an unknown, expired or forgotten id. `sourceApp` is trimmed, limited
47
+ to 80 characters and rejected with `SNIP_BAD_SOURCE_APP` when it is not a
48
+ string, contains control characters or matches a secret pattern; an empty label
49
+ becomes `unknown`.
50
+
51
+ ## Agent tools
52
+
53
+ The plugin registers six plain-object tools (no `@deepseek-ai/dsh-tools`
54
+ dependency):
55
+
56
+ | Tool | Arguments | Result |
57
+ | --- | --- | --- |
58
+ | `snip_add` | `text` (required), `kind`, `sourceApp`, `sensitivity` | `{ id, handle, kind, preview, createdAt, expiresAt, redacted }` |
59
+ | `snip_search` | `query` (required), `limit` | `{ query, entries }` |
60
+ | `snip_get` | `id` (id or `clipboard://` handle) | full entry including `text` |
61
+ | `snip_list` | `kind`, `limit` | `{ entries }` |
62
+ | `snip_forget` | `id` | `{ ok, removed }` |
63
+ | `snip_clear` | none | `{ removed }` |
64
+
65
+ `entries` are newest-first summaries (`id`, `handle`, `kind`, `preview`,
66
+ `createdAt`, `expiresAt`, `redacted`). `snip_get` returns the full text, which
67
+ then becomes part of the append-only conversation session log — read only what
68
+ you need.
69
+
70
+ ## Configuration
71
+
72
+ | Option | Default | Meaning |
73
+ | --- | --- | --- |
74
+ | `excludeSecrets` | `true` | Detect secrets and store only the redaction marker. |
75
+ | `ttlMs` | `86400000` (24 h) | Entry lifetime; expired entries are swept on access. |
76
+ | `maxEntries` | `200` | Oldest entries are evicted when the cap is exceeded. |
77
+ | `maxBytes` | `65536` (64 KiB) | Larger `add()` calls fail with `SNIP_TOO_LARGE`. |
78
+ | `stateFile` | unset | Optional JSON snapshot path, written atomically. |
79
+
80
+ Expiry and the entry cap are applied automatically on `add`, `list`, `search`,
81
+ `get`, `forget` and on mount.
82
+
83
+ ## Secret exclusion and local storage
84
+
85
+ - With `excludeSecrets` on (the default), a hit is **not stored at all**: the
86
+ ledger keeps only `[redacted:<reason>]` as the text/preview and marks
87
+ `redacted: true`. Supported patterns include `sk-...`, `ghp_...` /
88
+ `github_pat_...`, `AKIA...` / `ASIA...`, PEM/PGP private keys,
89
+ `password=...`, `api_key=...`, bearer tokens, JWTs, Slack, Stripe and Google
90
+ API keys.
91
+ - Detection is best-effort, not a guarantee. Set `excludeSecrets: false` to
92
+ opt out (not recommended). `sensitivity: 'secret'` is a caller-side override
93
+ that always redacts. `sourceApp` is metadata, not a secret store: labels are
94
+ screened for the same patterns and rejected when they look like a secret,
95
+ independently of `excludeSecrets`.
96
+ - `search` only scans the stored text, so a redacted secret's original value
97
+ can never be found through search; `get` returns only `[redacted:<reason>]`.
98
+ `forget` deletes the map entry and the next snapshot, so no index residue or
99
+ on-disk copy remains.
100
+ - When `stateFile` is set, each mutation writes the snapshot through a
101
+ temporary file and `rename` (atomic replace, mode `0600`) **before** the
102
+ in-memory ledger is updated. If the write fails, the call throws
103
+ `SNIP_STATE_WRITE_FAILED` and both memory and disk keep the previous state.
104
+ The snapshot is plain JSON and is **not encrypted in 0.1.1** — protect it
105
+ like any local secret. A snapshot written with detection disabled is
106
+ re-screened on load, and bad `sourceApp` metadata is replaced with `unknown`.
107
+ - 0.1.1 performs no network I/O and does not read the OS clipboard. There is no
108
+ background capture, watcher or timer.
109
+
110
+ ## Development
111
+
112
+ ```sh
113
+ cd packages/snip
114
+ node --test
115
+ ```
116
+
117
+ Pure ESM JavaScript, Node 22+, no runtime dependencies and no build step.
118
+
119
+ ## License
18
120
 
19
- - Host seam: `ctx.snip` (planned)
20
- - Agent tools and CLI are declared in the package's design doc.
21
- - License: MIT.
121
+ MIT. See [LICENSE](./LICENSE).
package/index.js CHANGED
@@ -1,13 +1,444 @@
1
1
  /**
2
- * dsh-snip — Encrypted, searchable clipboard ledger for DeepSeek Harness with secret exclusion and agent handles.
2
+ * dsh-snip — local-first clipboard ledger for DeepSeek Harness.
3
3
  *
4
- * 0.0.1 placeholder: the bundle loads and provides a stable package name.
5
- * The functional implementation lands in 0.1.0.
4
+ * 0.1.1 records explicit `add` calls only: no clipboard polling, no network,
5
+ * no encryption yet. Secret-looking text is not stored unless the caller
6
+ * explicitly disables `excludeSecrets`.
6
7
  * @module dsh-snip
7
8
  */
9
+ import { randomUUID } from 'node:crypto'
10
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { dirname } from 'node:path'
8
12
 
9
- /** Cordis plugin name. */
10
13
  export const name = 'dsh-snip'
14
+ export const inject = ['tools']
11
15
 
12
- /** Mount the plugin. The 0.0.1 placeholder intentionally has no side effects. */
13
- export function apply() {}
16
+ const DAY_MS = 86_400_000
17
+ const PREVIEW_CHARS = 140
18
+ const HANDLE_PREFIX = 'clipboard://'
19
+ const MAX_SOURCE_APP = 80
20
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/
21
+ const KINDS = new Set(['text', 'html', 'link', 'color'])
22
+ const SENSITIVITIES = new Set(['normal', 'sensitive', 'secret'])
23
+
24
+ /** Ordered: first match wins. Reasons are stable for `[redacted:<reason>]`. */
25
+ const SECRET_PATTERNS = [
26
+ ['private-key', /-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/],
27
+ ['openai-key', /\bsk-[A-Za-z0-9_-]{6,}\b/],
28
+ ['github-token', /\b(?:gh[pousr]_[A-Za-z0-9]{6,}|github_pat_[A-Za-z0-9_]{6,})\b/],
29
+ ['aws-access-key', /\b(?:AKIA|ASIA)[0-9A-Z]{8,}\b/],
30
+ ['slack-token', /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/],
31
+ ['google-api-key', /\bAIza[0-9A-Za-z_-]{10,}\b/],
32
+ ['stripe-key', /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/],
33
+ ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],
34
+ ['bearer-token', /\bBearer\s+[A-Za-z0-9._~+/-]{10,}=*/],
35
+ ['password', /\b(?:password|passwd|pwd)"?\s*[:=]\s*(?:"[^"]{3,}"|'[^']{3,}'|[^\s'"]{3,})/i],
36
+ ['api-key', /\b(?:api[_-]?key|apikey)"?\s*[:=]\s*(?:"[^"]{8,}"|'[^']{8,}'|[^\s'"]{8,})/i],
37
+ ['credential', /\b(?:secret|token|access[_-]?key)"?\s*[:=]\s*(?:"[^"]{6,}"|'[^']{6,}'|[^\s'"]{6,})/i],
38
+ ]
39
+
40
+ function fail(code, message) {
41
+ const error = new Error(message)
42
+ error.code = code
43
+ return error
44
+ }
45
+
46
+ function positiveInt(value, fallback) {
47
+ const number = Number(value)
48
+ return Number.isFinite(number) && number >= 1 ? Math.floor(number) : fallback
49
+ }
50
+
51
+ function requestedLimit(value, fallback) {
52
+ if (value == null) return fallback
53
+ const number = Number(value)
54
+ return Number.isFinite(number) && number >= 1 ? Math.min(Math.floor(number), fallback) : fallback
55
+ }
56
+
57
+ function previewOf(text) {
58
+ const flat = text.replace(/\s+/g, ' ').trim()
59
+ return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS - 1)}…` : flat
60
+ }
61
+
62
+ function handleOf(id) {
63
+ return `${HANDLE_PREFIX}${id}`
64
+ }
65
+
66
+ function resolveId(value) {
67
+ if (typeof value !== 'string') throw fail('SNIP_BAD_ID', 'snip: id must be a string')
68
+ const id = value.startsWith(HANDLE_PREFIX) ? value.slice(HANDLE_PREFIX.length) : value
69
+ if (!id) throw fail('SNIP_BAD_ID', 'snip: id must not be empty')
70
+ return id
71
+ }
72
+
73
+ function summaryOf(entry) {
74
+ return {
75
+ id: entry.id,
76
+ handle: handleOf(entry.id),
77
+ kind: entry.kind,
78
+ preview: entry.preview,
79
+ createdAt: entry.createdAt,
80
+ expiresAt: entry.expiresAt,
81
+ redacted: entry.redacted,
82
+ }
83
+ }
84
+
85
+ function isContext(value) {
86
+ return Boolean(value && typeof value === 'object' && ('provide' in value || 'get' in value || 'tools' in value))
87
+ }
88
+
89
+ /** Return the first secret pattern reason found in `text`, or null. */
90
+ export function detectSecret(text) {
91
+ if (typeof text !== 'string') return null
92
+ for (const [reason, pattern] of SECRET_PATTERNS) {
93
+ if (pattern.test(text)) return reason
94
+ }
95
+ return null
96
+ }
97
+
98
+ /**
99
+ * Validate the source application label. Labels are metadata, never a secret
100
+ * store: anything secret-looking is rejected instead of silently stored.
101
+ */
102
+ function normalizeSourceApp(value) {
103
+ if (value === undefined || value === null) return 'unknown'
104
+ if (typeof value !== 'string') throw fail('SNIP_BAD_SOURCE_APP', 'snip: sourceApp must be a string')
105
+ const label = value.trim()
106
+ if (label === '') return 'unknown'
107
+ if (label.length > MAX_SOURCE_APP) {
108
+ throw fail('SNIP_BAD_SOURCE_APP', `snip: sourceApp must be at most ${MAX_SOURCE_APP} characters`)
109
+ }
110
+ if (CONTROL_CHARS.test(label)) {
111
+ throw fail('SNIP_BAD_SOURCE_APP', 'snip: sourceApp must not contain control characters')
112
+ }
113
+ if (detectSecret(label)) {
114
+ throw fail('SNIP_BAD_SOURCE_APP', 'snip: sourceApp must not contain secret-looking text')
115
+ }
116
+ return label
117
+ }
118
+
119
+ /** Loading a snapshot tolerates bad metadata: drop it instead of failing mount. */
120
+ function safeSourceApp(value) {
121
+ try {
122
+ return normalizeSourceApp(value)
123
+ } catch {
124
+ return 'unknown'
125
+ }
126
+ }
127
+
128
+ /** In-memory ledger with optional atomic JSON snapshot. */
129
+ export class SnipService {
130
+ #entries = new Map()
131
+ #stateFile
132
+ #ttlMs
133
+ #maxEntries
134
+ #maxBytes
135
+ #excludeSecrets
136
+ #now
137
+
138
+ constructor(ctxOrConfig = {}, maybeConfig) {
139
+ const config = isContext(ctxOrConfig) ? (maybeConfig ?? {}) : (ctxOrConfig ?? {})
140
+ this.#ttlMs = positiveInt(config.ttlMs ?? config.ttl, DAY_MS)
141
+ this.#maxEntries = positiveInt(config.maxEntries, 200)
142
+ this.#maxBytes = positiveInt(config.maxBytes, 64 * 1024)
143
+ this.#excludeSecrets = config.excludeSecrets !== false
144
+ this.#now = typeof config.now === 'function' ? config.now : () => Date.now()
145
+ this.#stateFile = typeof config.stateFile === 'string' && config.stateFile.length > 0 ? config.stateFile : null
146
+ if (this.#stateFile) this.#load()
147
+ const next = new Map(this.#entries)
148
+ const swept = this.#sweep(next)
149
+ if (this.#stateFile) this.#commit(next)
150
+ else if (swept > 0) this.#entries = next
151
+ }
152
+
153
+ /** Store one clipping; return its stable handle and metadata. */
154
+ add(input = {}) {
155
+ const args = input ?? {}
156
+ const text = args.text
157
+ if (typeof text !== 'string') throw fail('SNIP_BAD_TEXT', 'snip: text must be a string')
158
+ if (text.trim().length === 0) throw fail('SNIP_EMPTY_TEXT', 'snip: text must not be empty')
159
+ if (Buffer.byteLength(text, 'utf8') > this.#maxBytes) {
160
+ throw fail('SNIP_TOO_LARGE', `snip: text exceeds maxBytes (${this.#maxBytes})`)
161
+ }
162
+
163
+ const kind = args.kind ?? 'text'
164
+ if (typeof kind !== 'string' || !KINDS.has(kind)) {
165
+ throw fail('SNIP_BAD_KIND', 'snip: unsupported kind')
166
+ }
167
+ const sensitivity = args.sensitivity ?? 'normal'
168
+ if (typeof sensitivity !== 'string' || !SENSITIVITIES.has(sensitivity)) {
169
+ throw fail('SNIP_BAD_SENSITIVITY', 'snip: unsupported sensitivity')
170
+ }
171
+ const sourceApp = normalizeSourceApp(args.sourceApp)
172
+
173
+ const reason = sensitivity === 'secret'
174
+ ? 'sensitivity'
175
+ : this.#excludeSecrets ? detectSecret(text) : null
176
+ const storedText = reason ? `[redacted:${reason}]` : text
177
+ const timestamp = this.#now()
178
+ const entry = {
179
+ id: randomUUID(),
180
+ kind,
181
+ text: storedText,
182
+ preview: previewOf(storedText),
183
+ sourceApp,
184
+ sensitivity,
185
+ createdAt: new Date(timestamp).toISOString(),
186
+ expiresAt: new Date(timestamp + this.#ttlMs).toISOString(),
187
+ redacted: reason !== null,
188
+ }
189
+
190
+ const next = new Map(this.#entries)
191
+ this.#sweep(next)
192
+ next.set(entry.id, entry)
193
+ this.#enforceMax(next)
194
+ this.#commit(next)
195
+ return summaryOf(entry)
196
+ }
197
+
198
+ /** Newest-first summaries, optionally filtered by kind. */
199
+ list(options = {}) {
200
+ const args = options ?? {}
201
+ this.#sweepAndCommit()
202
+ const kind = typeof args.kind === 'string' && args.kind.length > 0 ? args.kind : null
203
+ return [...this.#entries.values()]
204
+ .reverse()
205
+ .filter(entry => kind === null || entry.kind === kind)
206
+ .slice(0, requestedLimit(args.limit, this.#maxEntries))
207
+ .map(summaryOf)
208
+ }
209
+
210
+ /** Case-insensitive substring search over stored text (redacted text included). */
211
+ search(query, options = {}) {
212
+ const needle = typeof query === 'string' ? query.trim().toLowerCase() : ''
213
+ if (!needle) throw fail('SNIP_BAD_QUERY', 'snip: query must be a non-empty string')
214
+ this.#sweepAndCommit()
215
+ return [...this.#entries.values()]
216
+ .reverse()
217
+ .filter(entry => entry.text.toLowerCase().includes(needle))
218
+ .slice(0, requestedLimit(options?.limit, this.#maxEntries))
219
+ .map(summaryOf)
220
+ }
221
+
222
+ /** Full entry (including text) by id or `clipboard://` handle; null if absent. */
223
+ get(idOrHandle) {
224
+ const id = resolveId(idOrHandle)
225
+ this.#sweepAndCommit()
226
+ const entry = this.#entries.get(id)
227
+ if (!entry) return null
228
+ return {
229
+ ...summaryOf(entry),
230
+ text: entry.text,
231
+ sourceApp: entry.sourceApp,
232
+ sensitivity: entry.sensitivity,
233
+ }
234
+ }
235
+
236
+ /** Delete one entry by id or handle; true when it existed. */
237
+ forget(idOrHandle) {
238
+ const id = resolveId(idOrHandle)
239
+ const next = new Map(this.#entries)
240
+ const swept = this.#sweep(next)
241
+ const removed = next.delete(id)
242
+ if (removed || swept > 0) this.#commit(next)
243
+ return removed
244
+ }
245
+
246
+ /** Delete every entry; return the number removed. */
247
+ clear() {
248
+ const removed = this.#entries.size
249
+ if (removed > 0) this.#commit(new Map())
250
+ return removed
251
+ }
252
+
253
+ /** Sweep expired/overflowing entries; commit only when something changed. */
254
+ #sweepAndCommit() {
255
+ const next = new Map(this.#entries)
256
+ if (this.#sweep(next) === 0) return
257
+ this.#commit(next)
258
+ }
259
+
260
+ #sweep(entries = this.#entries) {
261
+ const now = this.#now()
262
+ let removed = 0
263
+ for (const [id, entry] of entries) {
264
+ if (Date.parse(entry.expiresAt) <= now) {
265
+ entries.delete(id)
266
+ removed += 1
267
+ }
268
+ }
269
+ return removed + this.#enforceMax(entries)
270
+ }
271
+
272
+ #enforceMax(entries = this.#entries) {
273
+ let removed = 0
274
+ while (entries.size > this.#maxEntries) {
275
+ entries.delete(entries.keys().next().value)
276
+ removed += 1
277
+ }
278
+ return removed
279
+ }
280
+
281
+ #load() {
282
+ if (!existsSync(this.#stateFile)) return
283
+ let parsed
284
+ try {
285
+ const raw = readFileSync(this.#stateFile, 'utf8').trim()
286
+ if (!raw) return
287
+ parsed = JSON.parse(raw)
288
+ } catch (error) {
289
+ throw fail('SNIP_STATE_INVALID', `snip: cannot read state file: ${error.message}`)
290
+ }
291
+ const entries = Array.isArray(parsed?.entries) ? parsed.entries : []
292
+ for (const raw of entries) {
293
+ if (!raw || typeof raw.id !== 'string' || typeof raw.text !== 'string') continue
294
+ const sensitivity = SENSITIVITIES.has(raw.sensitivity) ? raw.sensitivity : 'normal'
295
+ // Re-scan on load so a snapshot written with detection disabled is safe.
296
+ const reason = sensitivity === 'secret'
297
+ ? 'sensitivity'
298
+ : this.#excludeSecrets ? detectSecret(raw.text) : null
299
+ const text = reason ? `[redacted:${reason}]` : raw.text
300
+ this.#entries.set(raw.id, {
301
+ id: raw.id,
302
+ kind: KINDS.has(raw.kind) ? raw.kind : 'text',
303
+ text,
304
+ preview: previewOf(text),
305
+ sourceApp: safeSourceApp(raw.sourceApp),
306
+ sensitivity,
307
+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date(this.#now()).toISOString(),
308
+ expiresAt: typeof raw.expiresAt === 'string' ? raw.expiresAt : new Date(this.#now() + this.#ttlMs).toISOString(),
309
+ redacted: raw.redacted === true || reason !== null,
310
+ })
311
+ }
312
+ }
313
+
314
+ /** Write `next` first; only replace live state after the snapshot lands. */
315
+ #commit(next) {
316
+ this.#persist(next)
317
+ this.#entries = next
318
+ }
319
+
320
+ #persist(entries = this.#entries) {
321
+ if (!this.#stateFile) return
322
+ const payload = `${JSON.stringify({ version: 1, entries: [...entries.values()] }, null, 2)}\n`
323
+ const temp = `${this.#stateFile}.${process.pid}.${randomUUID()}.tmp`
324
+ try {
325
+ mkdirSync(dirname(this.#stateFile), { recursive: true, mode: 0o700 })
326
+ writeFileSync(temp, payload, { mode: 0o600 })
327
+ renameSync(temp, this.#stateFile)
328
+ } catch (error) {
329
+ try { rmSync(temp, { force: true }) } catch {}
330
+ throw fail('SNIP_STATE_WRITE_FAILED', `snip: cannot write state file: ${error.message}`)
331
+ }
332
+ }
333
+ }
334
+
335
+ const TOOL_OUTPUT = {
336
+ schema: { type: 'object', additionalProperties: true },
337
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
338
+ }
339
+
340
+ function tool(name, description, parameters, run) {
341
+ return {
342
+ name,
343
+ description,
344
+ parameters,
345
+ output: TOOL_OUTPUT,
346
+ async execute(args) {
347
+ return run(args ?? {})
348
+ },
349
+ }
350
+ }
351
+
352
+ /** Plain-object ToolDefinition list; deliberately no @deepseek-ai/dsh-tools import. */
353
+ export function makeTools(service) {
354
+ return [
355
+ tool(
356
+ 'snip_add',
357
+ 'Add a text clipping to the local Snip ledger and return a clipboard:// handle. Secret-looking text is redacted and not stored by default.',
358
+ {
359
+ type: 'object',
360
+ additionalProperties: false,
361
+ required: ['text'],
362
+ properties: {
363
+ text: { type: 'string', description: 'Text to record.' },
364
+ kind: { type: 'string', enum: [...KINDS] },
365
+ sourceApp: { type: 'string', description: 'Optional source application label.' },
366
+ sensitivity: { type: 'string', enum: [...SENSITIVITIES] },
367
+ },
368
+ },
369
+ args => service.add(args),
370
+ ),
371
+ tool(
372
+ 'snip_search',
373
+ 'Search the local Snip ledger (case-insensitive substring) and return matching handles and previews.',
374
+ {
375
+ type: 'object',
376
+ additionalProperties: false,
377
+ required: ['query'],
378
+ properties: {
379
+ query: { type: 'string', description: 'Text to look for.' },
380
+ limit: { type: 'integer', minimum: 1 },
381
+ },
382
+ },
383
+ args => ({ query: args.query, entries: service.search(args.query, { limit: args.limit }) }),
384
+ ),
385
+ tool(
386
+ 'snip_get',
387
+ 'Read one clipping by id or clipboard:// handle. Returned text becomes part of this conversation session log.',
388
+ {
389
+ type: 'object',
390
+ additionalProperties: false,
391
+ required: ['id'],
392
+ properties: { id: { type: 'string', description: 'Clipping id or clipboard:// handle.' } },
393
+ },
394
+ args => {
395
+ const entry = service.get(args.id)
396
+ if (!entry) throw fail('SNIP_NOT_FOUND', 'snip: clipping not found')
397
+ return entry
398
+ },
399
+ ),
400
+ tool(
401
+ 'snip_list',
402
+ 'List recent clippings newest first, optionally filtered by kind.',
403
+ {
404
+ type: 'object',
405
+ additionalProperties: false,
406
+ properties: {
407
+ kind: { type: 'string', enum: [...KINDS] },
408
+ limit: { type: 'integer', minimum: 1 },
409
+ },
410
+ },
411
+ args => ({ entries: service.list(args) }),
412
+ ),
413
+ tool(
414
+ 'snip_forget',
415
+ 'Delete one clipping by id or clipboard:// handle.',
416
+ {
417
+ type: 'object',
418
+ additionalProperties: false,
419
+ required: ['id'],
420
+ properties: { id: { type: 'string', description: 'Clipping id or clipboard:// handle.' } },
421
+ },
422
+ args => {
423
+ const removed = service.forget(args.id)
424
+ return { ok: removed, removed }
425
+ },
426
+ ),
427
+ tool(
428
+ 'snip_clear',
429
+ 'Delete every clipping in the local Snip ledger.',
430
+ { type: 'object', additionalProperties: false, properties: {} },
431
+ () => ({ removed: service.clear() }),
432
+ ),
433
+ ]
434
+ }
435
+
436
+ /** Mount `ctx.snip` and the snip_* agent tools. */
437
+ export function apply(ctx, config = {}) {
438
+ const service = new SnipService(config)
439
+ ctx.provide('snip', service)
440
+ if (ctx.tools && typeof ctx.tools.register === 'function') {
441
+ for (const definition of makeTools(service)) ctx.tools.register(definition)
442
+ }
443
+ return service
444
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-snip",
3
- "version": "0.0.1",
4
- "description": "Encrypted, searchable clipboard ledger for DeepSeek Harness with secret exclusion and agent handles.",
3
+ "version": "0.1.1",
4
+ "description": "Local-first, searchable clipboard ledger for DeepSeek Harness with secret exclusion and clipboard:// agent handles.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "exports": {
@@ -14,11 +14,16 @@
14
14
  "README.md",
15
15
  "CHANGELOG.md"
16
16
  ],
17
+ "scripts": {
18
+ "test": "node --test"
19
+ },
17
20
  "keywords": [
18
21
  "dsh",
19
22
  "dsh-plugin",
20
23
  "deepseek-harness",
21
24
  "agent-os",
25
+ "clipboard",
26
+ "clipboard-history",
22
27
  "snip"
23
28
  ],
24
29
  "license": "MIT",
@@ -34,15 +39,37 @@
34
39
  },
35
40
  "engines": {
36
41
  "node": "^22.19.0 || >=24.9.0",
37
- "dsh": ">=0.2.1-rc.2 <0.3.0 || >=0.2.2-0 <0.3.0"
42
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0"
38
43
  },
39
44
  "dsh": {
40
45
  "manifestVersion": 1,
41
46
  "bundle": {
42
47
  "patch": "./cordis.patch.yml"
48
+ },
49
+ "os": {
50
+ "service": "snip",
51
+ "provides": [
52
+ "snip"
53
+ ],
54
+ "capabilities": [
55
+ "clipboard",
56
+ "secret"
57
+ ],
58
+ "tools": [
59
+ "snip_add",
60
+ "snip_search",
61
+ "snip_get",
62
+ "snip_list",
63
+ "snip_forget",
64
+ "snip_clear"
65
+ ],
66
+ "ui": null,
67
+ "stability": "experimental",
68
+ "since": "0.1.0"
43
69
  }
44
70
  },
45
71
  "publishConfig": {
46
- "access": "public"
72
+ "access": "public",
73
+ "registry": "https://registry.npmjs.org/"
47
74
  }
48
75
  }