@clarionstack/notesia 0.0.1 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,25 +10,10 @@ Local CLI for reading and updating Notesia desktop notes through the local app b
10
10
 
11
11
  ## Install
12
12
 
13
- ### Option 0: Install from npm
14
-
15
13
  ```bash
16
14
  npm install -g @clarionstack/notesia
17
15
  ```
18
16
 
19
- ### Option 1: Global install from local repo
20
-
21
- ```bash
22
- npm install -g ./packages/notesia-cli
23
- ```
24
-
25
- ### Option 2: Build distributable package and share it
26
-
27
- ```bash
28
- npm pack ./packages/notesia-cli
29
- npm install -g ./notesia-cli-0.0.1.tgz
30
- ```
31
-
32
17
  ## Commands
33
18
 
34
19
  ### Notes
@@ -44,9 +29,12 @@ npm install -g ./notesia-cli-0.0.1.tgz
44
29
 
45
30
  ### AI Knowledge Base (`kb`)
46
31
 
47
- - `notesia kb search --query "<text>" [--limit <n>] [--format text|json]`
32
+ - `notesia kb search --query "<text>" [--limit <n>] [--threshold <0-1>] [--format text|json]`
33
+ - `notesia kb ask --query "<text>" [--limit <n>] [--threshold <0-1>] [--conversation-id <uuid>] [--format text|json]`
48
34
  - `notesia kb folders [--format text|json]`
49
- - `notesia kb context --query "<text>" [--limit <n>]` *(always JSON)*
35
+ - `notesia kb context --query "<text>" [--limit <n>] [--threshold <0-1>]` *(always JSON)*
36
+
37
+ `kb ask` automatically reuses the same conversation in the same terminal session. Use `--conversation-id` only when you want to override/reset the session.
50
38
 
51
39
  ## Examples
52
40
 
@@ -73,9 +61,16 @@ notesia kb folders --json
73
61
  # Find relevant notes
74
62
  notesia kb search --query "project plan" --limit 10
75
63
 
64
+ # Ask KB directly
65
+ notesia kb ask --query "what did I change yesterday?"
66
+
76
67
  # Load full context for AI prompt (returns JSON with full content)
77
68
  notesia kb context --query "Q1 roadmap" --limit 5
78
69
 
70
+ # Continue a KB conversation across calls
71
+ notesia kb ask --query "what did I change yesterday?" --conversation-id 11111111-1111-4111-8111-111111111111
72
+ notesia kb ask --query "and what about folder sync?" --conversation-id 11111111-1111-4111-8111-111111111111
73
+
79
74
  # Create a tagged note
80
75
  echo "## Summary\n..." | notesia store --title "AI Summary" --tag ai --tag generated
81
76
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@clarionstack/notesia",
3
3
  "private": false,
4
- "version": "0.0.1",
4
+ "version": "0.0.4",
5
5
  "description": "Notesia desktop bridge CLI",
6
6
  "type": "module",
7
7
  "files": [
@@ -24,4 +24,4 @@
24
24
  "engines": {
25
25
  "node": ">=20"
26
26
  }
27
- }
27
+ }
package/src/commands.mjs CHANGED
@@ -1,4 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
2
5
  import { requestBridge as defaultRequestBridge } from './client.mjs';
3
6
  import {
4
7
  printListResult,
@@ -9,11 +12,96 @@ import {
9
12
  readInputContent as defaultReadInputContent,
10
13
  } from './io.mjs';
11
14
 
12
- const SUPPORTED_OPS = new Set(['get', 'list', 'store', 'update', 'append', 'sync', 'auth-status', 'kb-search', 'kb-folders', 'kb-context', 'trash']);
15
+ const SUPPORTED_OPS = new Set(['get', 'list', 'store', 'update', 'append', 'sync', 'auth-status', 'kb-search', 'kb-folders', 'kb-context', 'kb-ask', 'trash']);
13
16
  const OP_ALIASES = new Map([
14
17
  ['retrieve', 'get'],
15
18
  ['storage', 'store'],
16
19
  ]);
20
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
21
+ const KB_SESSION_TTL_MS = 24 * 60 * 60 * 1000;
22
+ const SAFE_SEGMENT = /[^a-zA-Z0-9_-]/g;
23
+
24
+ function toSafeSegment(value, fallback = 'user') {
25
+ const normalized = String(value || '').trim().replace(SAFE_SEGMENT, '_');
26
+ return normalized || fallback;
27
+ }
28
+
29
+ function getKbSessionStorePath({
30
+ tmpDir = os.tmpdir(),
31
+ user = os.userInfo().username,
32
+ } = {}) {
33
+ return path.join(tmpDir, `notesia-cli-kb-session-${toSafeSegment(user)}.json`);
34
+ }
35
+
36
+ function getTerminalSessionKey() {
37
+ return (
38
+ process.env.NOTESIA_CLI_SESSION_ID
39
+ || process.env.TERM_SESSION_ID
40
+ || process.env.WT_SESSION
41
+ || (process.env.TMUX_PANE ? `tmux:${process.env.TMUX_PANE}` : null)
42
+ || `ppid:${process.ppid || process.pid}`
43
+ );
44
+ }
45
+
46
+ async function loadKbSessionStore(sessionFilePath) {
47
+ try {
48
+ const raw = await fs.readFile(sessionFilePath, 'utf8');
49
+ const parsed = JSON.parse(raw);
50
+ return parsed && typeof parsed === 'object' ? parsed : {};
51
+ } catch {
52
+ return {};
53
+ }
54
+ }
55
+
56
+ async function saveKbSessionStore(sessionFilePath, store) {
57
+ await fs.writeFile(sessionFilePath, JSON.stringify(store, null, 2), 'utf8');
58
+ }
59
+
60
+ function pruneKbSessionStore(store, nowMs) {
61
+ const pruned = {};
62
+ for (const [key, value] of Object.entries(store || {})) {
63
+ if (!value || typeof value !== 'object') continue;
64
+ if (!UUID_REGEX.test(value.conversationId || '')) continue;
65
+ const updatedAt = Number(value.updatedAt || 0);
66
+ if (!Number.isFinite(updatedAt) || nowMs - updatedAt > KB_SESSION_TTL_MS) continue;
67
+ pruned[key] = {
68
+ conversationId: value.conversationId,
69
+ updatedAt,
70
+ };
71
+ }
72
+ return pruned;
73
+ }
74
+
75
+ export async function defaultResolveKbConversationId(explicitConversationId = null) {
76
+ const nowMs = Date.now();
77
+ const sessionFilePath = getKbSessionStorePath();
78
+ const sessionKey = getTerminalSessionKey();
79
+ const fallbackId = explicitConversationId || randomUUID();
80
+
81
+ try {
82
+ const loaded = await loadKbSessionStore(sessionFilePath);
83
+ const store = pruneKbSessionStore(loaded, nowMs);
84
+
85
+ if (explicitConversationId) {
86
+ store[sessionKey] = { conversationId: explicitConversationId, updatedAt: nowMs };
87
+ await saveKbSessionStore(sessionFilePath, store);
88
+ return explicitConversationId;
89
+ }
90
+
91
+ const existingId = store[sessionKey]?.conversationId;
92
+ if (UUID_REGEX.test(existingId || '')) {
93
+ store[sessionKey].updatedAt = nowMs;
94
+ await saveKbSessionStore(sessionFilePath, store);
95
+ return existingId;
96
+ }
97
+
98
+ store[sessionKey] = { conversationId: fallbackId, updatedAt: nowMs };
99
+ await saveKbSessionStore(sessionFilePath, store);
100
+ return fallbackId;
101
+ } catch {
102
+ return fallbackId;
103
+ }
104
+ }
17
105
 
18
106
  export class CliCommandError extends Error {
19
107
  constructor(code, message) {
@@ -51,11 +139,17 @@ export function parseArgs(argv = []) {
51
139
  if (!subcommand || subcommand === '--help' || subcommand === '-h') {
52
140
  return { op: 'help' };
53
141
  }
54
- const kbOps = { search: 'kb-search', folders: 'kb-folders', context: 'kb-context' };
142
+ const kbOps = { search: 'kb-search', folders: 'kb-folders', context: 'kb-context', ask: 'kb-ask' };
55
143
  if (!kbOps[subcommand]) {
56
144
  throw new CliCommandError('INVALID_OP', `Unsupported kb command: ${subcommand} `);
57
145
  }
58
146
  op = kbOps[subcommand];
147
+
148
+ // Support positional query arg for kb ask: `notesia kb ask "my question"`
149
+ if (op === 'kb-ask' && args.length > 0 && !args[0].startsWith('--')) {
150
+ // Stash the positional query; it will be picked up below as parsed.query
151
+ args.unshift('--query', args.shift());
152
+ }
59
153
  }
60
154
 
61
155
  if (!op || op === '--help' || op === '-h') {
@@ -74,8 +168,10 @@ export function parseArgs(argv = []) {
74
168
  folderId: null,
75
169
  content: undefined,
76
170
  limit: null,
171
+ threshold: null,
77
172
  withMeta: false,
78
173
  query: null,
174
+ conversationId: null,
79
175
  tags: [],
80
176
  };
81
177
 
@@ -136,6 +232,16 @@ export function parseArgs(argv = []) {
136
232
  continue;
137
233
  }
138
234
 
235
+ if (token === '--threshold') {
236
+ const threshold = Number(readFlagValue(args, i));
237
+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
238
+ throw new CliCommandError('INVALID_ARGS', '--threshold must be a number between 0 and 1');
239
+ }
240
+ parsed.threshold = threshold;
241
+ i += 1;
242
+ continue;
243
+ }
244
+
139
245
  if (token === '--format') {
140
246
  const format = readFlagValue(args, i);
141
247
  if (format !== 'text' && format !== 'json' && format !== 'table') {
@@ -162,6 +268,16 @@ export function parseArgs(argv = []) {
162
268
  continue;
163
269
  }
164
270
 
271
+ if (token === '--conversation-id') {
272
+ const value = readFlagValue(args, i);
273
+ if (!UUID_REGEX.test(value)) {
274
+ throw new CliCommandError('INVALID_ARGS', '--conversation-id must be a valid UUID');
275
+ }
276
+ parsed.conversationId = value;
277
+ i += 1;
278
+ continue;
279
+ }
280
+
165
281
  if (token === '--tag') {
166
282
  parsed.tags.push(readFlagValue(args, i));
167
283
  i += 1;
@@ -195,9 +311,10 @@ function usageText() {
195
311
  ' auth status [--format text|json]',
196
312
  '',
197
313
  'AI Knowledge Base:',
198
- ' kb search --query <text> [--limit <n>] [--format text|json]',
314
+ ' kb search --query <text> [--limit <n>] [--threshold <0-1>] [--format text|json]',
315
+ ' kb ask --query <text> [--limit <n>] [--threshold <0-1>] [--conversation-id <uuid>] [--format text|json]',
199
316
  ' kb folders [--format text|json]',
200
- ' kb context --query <text> [--limit <n>]',
317
+ ' kb context --query <text> [--limit <n>] [--threshold <0-1>]',
201
318
  '',
202
319
  'Pipe examples:',
203
320
  ' notesia get --id 12 > note.md',
@@ -205,6 +322,9 @@ function usageText() {
205
322
  ' cat patch.md | notesia update --id 12',
206
323
  ' echo "- bullet" | notesia append --id 12',
207
324
  '',
325
+ 'Note:',
326
+ ' kb ask reuses the same conversation automatically in the same terminal session.',
327
+ '',
208
328
  ].join('\n');
209
329
  }
210
330
 
@@ -287,7 +407,7 @@ function buildPayload(parsed, pipedContent) {
287
407
  if (!parsed.query) {
288
408
  throw new CliCommandError('MISSING_ARGS', '--query is required for kb search');
289
409
  }
290
- return { query: parsed.query, limit: parsed.limit ?? 20 };
410
+ return { query: parsed.query, limit: parsed.limit ?? 20, threshold: parsed.threshold ?? undefined };
291
411
  }
292
412
 
293
413
  if (parsed.op === 'kb-folders') {
@@ -298,7 +418,23 @@ function buildPayload(parsed, pipedContent) {
298
418
  if (!parsed.query) {
299
419
  throw new CliCommandError('MISSING_ARGS', '--query is required for kb context');
300
420
  }
301
- return { query: parsed.query, limit: parsed.limit ?? 5 };
421
+ return {
422
+ query: parsed.query,
423
+ limit: parsed.limit ?? 5,
424
+ threshold: parsed.threshold ?? undefined,
425
+ };
426
+ }
427
+
428
+ if (parsed.op === 'kb-ask') {
429
+ if (!parsed.query) {
430
+ throw new CliCommandError('MISSING_ARGS', '--query is required for kb ask');
431
+ }
432
+ return {
433
+ query: parsed.query,
434
+ limit: parsed.limit ?? 5,
435
+ threshold: parsed.threshold ?? undefined,
436
+ conversation_id: parsed.conversationId ?? undefined,
437
+ };
302
438
  }
303
439
 
304
440
  throw new CliCommandError('INVALID_OP', `Unsupported command: ${parsed.op} `);
@@ -308,6 +444,7 @@ export async function runCli(argv = [], {
308
444
  requestBridge = defaultRequestBridge,
309
445
  readInputContent = defaultReadInputContent,
310
446
  writeStdout = (chunk) => process.stdout.write(chunk),
447
+ resolveKbConversationId = defaultResolveKbConversationId,
311
448
  } = {}) {
312
449
  const parsed = parseArgs(argv);
313
450
 
@@ -320,6 +457,9 @@ export async function runCli(argv = [], {
320
457
  const pipedContent = needsPipedInput ? await readInputContent() : undefined;
321
458
 
322
459
  const payload = buildPayload(parsed, pipedContent);
460
+ if (parsed.op === 'kb-ask' && typeof resolveKbConversationId === 'function') {
461
+ payload.conversation_id = await resolveKbConversationId(payload.conversation_id ?? null);
462
+ }
323
463
  const request = {
324
464
  id: randomUUID(),
325
465
  op: parsed.op,
@@ -352,7 +492,7 @@ export async function runCli(argv = [], {
352
492
  format: parsed.format,
353
493
  writeStdout,
354
494
  });
355
- } else if (['kb-search', 'kb-folders', 'kb-context'].includes(parsed.op)) {
495
+ } else if (['kb-search', 'kb-folders', 'kb-context', 'kb-ask'].includes(parsed.op)) {
356
496
  printKbResult(parsed.op, response.data, { format: parsed.format, writeStdout });
357
497
  } else {
358
498
  printMutationResult(response.data, {
package/src/io.mjs CHANGED
@@ -163,6 +163,21 @@ export function printKbResult(op, result, {
163
163
  return;
164
164
  }
165
165
 
166
+ if (op === 'kb-ask') {
167
+ const answer = result?.answer || '';
168
+ const citations = Array.isArray(result?.citations) ? result.citations : [];
169
+ writeStdout(answer);
170
+ if (citations.length > 0) {
171
+ writeStdout('\n\nSources:\n');
172
+ for (const c of citations) {
173
+ writeStdout(` - [${c.noteId}] ${c.title}\n`);
174
+ }
175
+ } else {
176
+ writeStdout('\n');
177
+ }
178
+ return;
179
+ }
180
+
166
181
  if (op === 'kb-search') {
167
182
  const notes = Array.isArray(result?.notes) ? result.notes : [];
168
183
  if (notes.length === 0) {