@clarionstack/notesia 0.0.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.
- package/README.md +90 -0
- package/bin/notesia.mjs +8 -0
- package/package.json +27 -0
- package/src/client.mjs +153 -0
- package/src/commands.mjs +365 -0
- package/src/io.mjs +208 -0
package/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Notesia CLI
|
|
2
|
+
|
|
3
|
+
Local CLI for reading and updating Notesia desktop notes through the local app bridge.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Node.js 20+
|
|
8
|
+
- Notesia desktop app running (macOS/Linux)
|
|
9
|
+
- Logged into Notesia in the desktop app
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
### Option 0: Install from npm
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install -g @clarionstack/notesia
|
|
17
|
+
```
|
|
18
|
+
|
|
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
|
+
## Commands
|
|
33
|
+
|
|
34
|
+
### Notes
|
|
35
|
+
|
|
36
|
+
- `notesia get --id <id>|--supabase-id <uuid>|--title "<title>" [--json] [--with-meta]`
|
|
37
|
+
- `notesia list [--limit <count>] [--format table|json]`
|
|
38
|
+
- `notesia store --title "<title>" [--tag <tag>]... [--folder-id <id>] [--content <text>]`
|
|
39
|
+
- `notesia update --id <id>|... [--content <text>] [--title "<new title>"]`
|
|
40
|
+
- `notesia append --id <id>|... [--content <text>]`
|
|
41
|
+
- `notesia trash --id <id>|...`
|
|
42
|
+
- `notesia sync`
|
|
43
|
+
- `notesia auth status [--format text|json]`
|
|
44
|
+
|
|
45
|
+
### AI Knowledge Base (`kb`)
|
|
46
|
+
|
|
47
|
+
- `notesia kb search --query "<text>" [--limit <n>] [--format text|json]`
|
|
48
|
+
- `notesia kb folders [--format text|json]`
|
|
49
|
+
- `notesia kb context --query "<text>" [--limit <n>]` *(always JSON)*
|
|
50
|
+
|
|
51
|
+
## Examples
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
notesia get --id 42 > note.md
|
|
55
|
+
notesia get --id 42 --with-meta # prepends YAML frontmatter
|
|
56
|
+
notesia list --format json > notes.json
|
|
57
|
+
cat patch.md | notesia update --id 42
|
|
58
|
+
echo "- new item" | notesia append --id 42
|
|
59
|
+
notesia trash --id 42
|
|
60
|
+
notesia sync
|
|
61
|
+
notesia auth status
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## AI Agent Quick Start
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Check auth
|
|
68
|
+
notesia auth status --json
|
|
69
|
+
|
|
70
|
+
# Discover knowledge structure
|
|
71
|
+
notesia kb folders --json
|
|
72
|
+
|
|
73
|
+
# Find relevant notes
|
|
74
|
+
notesia kb search --query "project plan" --limit 10
|
|
75
|
+
|
|
76
|
+
# Load full context for AI prompt (returns JSON with full content)
|
|
77
|
+
notesia kb context --query "Q1 roadmap" --limit 5
|
|
78
|
+
|
|
79
|
+
# Create a tagged note
|
|
80
|
+
echo "## Summary\n..." | notesia store --title "AI Summary" --tag ai --tag generated
|
|
81
|
+
|
|
82
|
+
# Get a note with frontmatter for context injection
|
|
83
|
+
notesia get --id 42 --with-meta
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Security Notes
|
|
87
|
+
|
|
88
|
+
- **Secure notes** (encrypted vault notes) are **never** exposed through the CLI
|
|
89
|
+
- The bridge token is stored in `$TMPDIR/notesia-cli-<user>.json` (mode 600)
|
|
90
|
+
- Content via `--content` or stdin is limited to **512 KB**
|
package/bin/notesia.mjs
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@clarionstack/notesia",
|
|
3
|
+
"private": false,
|
|
4
|
+
"version": "0.0.1",
|
|
5
|
+
"description": "Notesia desktop bridge CLI",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"files": [
|
|
8
|
+
"bin",
|
|
9
|
+
"src",
|
|
10
|
+
"README.md"
|
|
11
|
+
],
|
|
12
|
+
"bin": {
|
|
13
|
+
"notesia": "bin/notesia.mjs"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test test/*.test.mjs"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"notesia",
|
|
20
|
+
"cli",
|
|
21
|
+
"knowledge-base",
|
|
22
|
+
"desktop"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/client.mjs
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const SAFE_SEGMENT = /[^a-zA-Z0-9_-]/g;
|
|
8
|
+
|
|
9
|
+
export class BridgeClientError extends Error {
|
|
10
|
+
constructor(code, message, details = {}) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.details = details;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const toSafeSegment = (value, fallback = 'user') => {
|
|
18
|
+
const normalized = String(value || '').trim().replace(SAFE_SEGMENT, '_');
|
|
19
|
+
return normalized || fallback;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export function getDefaultBridgeInfoPath({
|
|
23
|
+
platform = process.platform,
|
|
24
|
+
user = os.userInfo().username,
|
|
25
|
+
tmpDir = os.tmpdir(),
|
|
26
|
+
} = {}) {
|
|
27
|
+
const safeUser = toSafeSegment(user, 'user');
|
|
28
|
+
return path.join(tmpDir, `notesia-cli-${safeUser}.json`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function loadBridgeInfo({
|
|
32
|
+
bridgeInfoPath = getDefaultBridgeInfoPath(),
|
|
33
|
+
} = {}) {
|
|
34
|
+
let raw;
|
|
35
|
+
try {
|
|
36
|
+
raw = await fs.readFile(bridgeInfoPath, 'utf8');
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (error?.code === 'ENOENT') {
|
|
39
|
+
throw new BridgeClientError(
|
|
40
|
+
'NOTESIA_APP_NOT_RUNNING',
|
|
41
|
+
'Notesia desktop app bridge was not found. Start Notesia and try again.',
|
|
42
|
+
{ bridgeInfoPath }
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let parsed;
|
|
49
|
+
try {
|
|
50
|
+
parsed = JSON.parse(raw);
|
|
51
|
+
} catch {
|
|
52
|
+
throw new BridgeClientError(
|
|
53
|
+
'INVALID_BRIDGE_INFO',
|
|
54
|
+
'Bridge info file is invalid JSON',
|
|
55
|
+
{ bridgeInfoPath }
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (!parsed?.socketPath || !parsed?.token) {
|
|
60
|
+
throw new BridgeClientError(
|
|
61
|
+
'INVALID_BRIDGE_INFO',
|
|
62
|
+
'Bridge info file is missing required fields',
|
|
63
|
+
{ bridgeInfoPath }
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return parsed;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function requestBridge(request, {
|
|
71
|
+
timeoutMs = 15000,
|
|
72
|
+
bridgeInfoPath,
|
|
73
|
+
} = {}) {
|
|
74
|
+
if (!request || typeof request !== 'object' || !request.op) {
|
|
75
|
+
throw new BridgeClientError('INVALID_REQUEST', 'Bridge request requires an operation');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const bridgeInfo = await loadBridgeInfo({ bridgeInfoPath });
|
|
79
|
+
const payload = {
|
|
80
|
+
id: request.id || randomUUID(),
|
|
81
|
+
token: bridgeInfo.token,
|
|
82
|
+
op: request.op,
|
|
83
|
+
payload: request.payload || {},
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
const client = net.createConnection(bridgeInfo.socketPath);
|
|
88
|
+
let buffer = '';
|
|
89
|
+
let settled = false;
|
|
90
|
+
|
|
91
|
+
const finish = (fn) => (value) => {
|
|
92
|
+
if (settled) return;
|
|
93
|
+
settled = true;
|
|
94
|
+
clearTimeout(timeout);
|
|
95
|
+
client.destroy();
|
|
96
|
+
fn(value);
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const doneResolve = finish(resolve);
|
|
100
|
+
const doneReject = finish(reject);
|
|
101
|
+
|
|
102
|
+
const timeout = setTimeout(() => {
|
|
103
|
+
doneReject(
|
|
104
|
+
new BridgeClientError(
|
|
105
|
+
'BRIDGE_TIMEOUT',
|
|
106
|
+
`Timed out waiting for Notesia bridge response after ${timeoutMs}ms`
|
|
107
|
+
)
|
|
108
|
+
);
|
|
109
|
+
}, timeoutMs);
|
|
110
|
+
|
|
111
|
+
client.on('connect', () => {
|
|
112
|
+
client.write(`${JSON.stringify(payload)}\n`);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
client.on('data', (chunk) => {
|
|
116
|
+
buffer += chunk.toString('utf8');
|
|
117
|
+
const lineBreak = buffer.indexOf('\n');
|
|
118
|
+
if (lineBreak === -1) return;
|
|
119
|
+
|
|
120
|
+
const line = buffer.slice(0, lineBreak).trim();
|
|
121
|
+
if (!line) {
|
|
122
|
+
doneReject(new BridgeClientError('INVALID_RESPONSE', 'Bridge returned an empty response'));
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
const parsed = JSON.parse(line);
|
|
128
|
+
doneResolve(parsed);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
doneReject(
|
|
131
|
+
new BridgeClientError(
|
|
132
|
+
'INVALID_RESPONSE',
|
|
133
|
+
`Bridge returned invalid JSON: ${error.message}`
|
|
134
|
+
)
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
client.on('error', (error) => {
|
|
140
|
+
if (error?.code === 'ENOENT' || error?.code === 'ECONNREFUSED') {
|
|
141
|
+
doneReject(
|
|
142
|
+
new BridgeClientError(
|
|
143
|
+
'NOTESIA_APP_NOT_RUNNING',
|
|
144
|
+
'Unable to connect to Notesia bridge. Ensure the desktop app is running.',
|
|
145
|
+
{ socketPath: bridgeInfo.socketPath }
|
|
146
|
+
)
|
|
147
|
+
);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
doneReject(error);
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
}
|
package/src/commands.mjs
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { requestBridge as defaultRequestBridge } from './client.mjs';
|
|
3
|
+
import {
|
|
4
|
+
printListResult,
|
|
5
|
+
printRetrieveResult,
|
|
6
|
+
printMutationResult,
|
|
7
|
+
printAuthStatusResult,
|
|
8
|
+
printKbResult,
|
|
9
|
+
readInputContent as defaultReadInputContent,
|
|
10
|
+
} from './io.mjs';
|
|
11
|
+
|
|
12
|
+
const SUPPORTED_OPS = new Set(['get', 'list', 'store', 'update', 'append', 'sync', 'auth-status', 'kb-search', 'kb-folders', 'kb-context', 'trash']);
|
|
13
|
+
const OP_ALIASES = new Map([
|
|
14
|
+
['retrieve', 'get'],
|
|
15
|
+
['storage', 'store'],
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
export class CliCommandError extends Error {
|
|
19
|
+
constructor(code, message) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.code = code;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readFlagValue(args, index) {
|
|
26
|
+
const value = args[index + 1];
|
|
27
|
+
if (value === undefined || value.startsWith('--')) {
|
|
28
|
+
throw new CliCommandError('INVALID_ARGS', `Flag ${args[index]} requires a value`);
|
|
29
|
+
}
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function parseArgs(argv = []) {
|
|
34
|
+
const args = [...argv];
|
|
35
|
+
const rawOp = args.shift();
|
|
36
|
+
let op = OP_ALIASES.get(rawOp) || rawOp;
|
|
37
|
+
|
|
38
|
+
if (rawOp === 'auth') {
|
|
39
|
+
const subcommand = args.shift();
|
|
40
|
+
if (!subcommand || subcommand === '--help' || subcommand === '-h') {
|
|
41
|
+
return { op: 'help' };
|
|
42
|
+
}
|
|
43
|
+
if (subcommand !== 'status') {
|
|
44
|
+
throw new CliCommandError('INVALID_OP', `Unsupported auth command: ${subcommand} `);
|
|
45
|
+
}
|
|
46
|
+
op = 'auth-status';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (rawOp === 'kb') {
|
|
50
|
+
const subcommand = args.shift();
|
|
51
|
+
if (!subcommand || subcommand === '--help' || subcommand === '-h') {
|
|
52
|
+
return { op: 'help' };
|
|
53
|
+
}
|
|
54
|
+
const kbOps = { search: 'kb-search', folders: 'kb-folders', context: 'kb-context' };
|
|
55
|
+
if (!kbOps[subcommand]) {
|
|
56
|
+
throw new CliCommandError('INVALID_OP', `Unsupported kb command: ${subcommand} `);
|
|
57
|
+
}
|
|
58
|
+
op = kbOps[subcommand];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (!op || op === '--help' || op === '-h') {
|
|
62
|
+
return { op: 'help' };
|
|
63
|
+
}
|
|
64
|
+
if (!SUPPORTED_OPS.has(op)) {
|
|
65
|
+
throw new CliCommandError('INVALID_OP', `Unsupported command: ${op} `);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const parsed = {
|
|
69
|
+
op,
|
|
70
|
+
format: 'text',
|
|
71
|
+
id: null,
|
|
72
|
+
supabaseId: null,
|
|
73
|
+
title: null,
|
|
74
|
+
folderId: null,
|
|
75
|
+
content: undefined,
|
|
76
|
+
limit: null,
|
|
77
|
+
withMeta: false,
|
|
78
|
+
query: null,
|
|
79
|
+
tags: [],
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
83
|
+
const token = args[i];
|
|
84
|
+
|
|
85
|
+
if (token === '--help' || token === '-h') {
|
|
86
|
+
return { op: 'help' };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (token === '--id') {
|
|
90
|
+
const value = Number(readFlagValue(args, i));
|
|
91
|
+
if (!Number.isFinite(value)) {
|
|
92
|
+
throw new CliCommandError('INVALID_ARGS', '--id must be a number');
|
|
93
|
+
}
|
|
94
|
+
parsed.id = value;
|
|
95
|
+
i += 1;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (token === '--supabase-id') {
|
|
100
|
+
parsed.supabaseId = readFlagValue(args, i);
|
|
101
|
+
i += 1;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (token === '--title') {
|
|
106
|
+
parsed.title = readFlagValue(args, i);
|
|
107
|
+
i += 1;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (token === '--folder-id') {
|
|
112
|
+
parsed.folderId = Number(readFlagValue(args, i));
|
|
113
|
+
if (!Number.isFinite(parsed.folderId)) {
|
|
114
|
+
throw new CliCommandError('INVALID_ARGS', '--folder-id must be a number');
|
|
115
|
+
}
|
|
116
|
+
i += 1;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (token === '--content') {
|
|
121
|
+
parsed.content = readFlagValue(args, i);
|
|
122
|
+
if (Buffer.byteLength(parsed.content, 'utf8') > 512 * 1024) {
|
|
123
|
+
throw new CliCommandError('CONTENT_TOO_LARGE', '--content exceeds 512 KB limit');
|
|
124
|
+
}
|
|
125
|
+
i += 1;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (token === '--limit') {
|
|
130
|
+
const limit = Number(readFlagValue(args, i));
|
|
131
|
+
if (!Number.isFinite(limit) || limit <= 0) {
|
|
132
|
+
throw new CliCommandError('INVALID_ARGS', '--limit must be a positive number');
|
|
133
|
+
}
|
|
134
|
+
parsed.limit = Math.floor(limit);
|
|
135
|
+
i += 1;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (token === '--format') {
|
|
140
|
+
const format = readFlagValue(args, i);
|
|
141
|
+
if (format !== 'text' && format !== 'json' && format !== 'table') {
|
|
142
|
+
throw new CliCommandError('INVALID_ARGS', '--format must be text, table, or json');
|
|
143
|
+
}
|
|
144
|
+
parsed.format = format;
|
|
145
|
+
i += 1;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (token === '--json') {
|
|
150
|
+
parsed.format = 'json';
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (token === '--with-meta') {
|
|
155
|
+
parsed.withMeta = true;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (token === '--query') {
|
|
160
|
+
parsed.query = readFlagValue(args, i);
|
|
161
|
+
i += 1;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (token === '--tag') {
|
|
166
|
+
parsed.tags.push(readFlagValue(args, i));
|
|
167
|
+
i += 1;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
throw new CliCommandError('INVALID_ARGS', `Unknown argument: ${token} `);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const selector = {};
|
|
175
|
+
if (parsed.id !== null) selector.id = parsed.id;
|
|
176
|
+
if (parsed.supabaseId) selector.supabase_id = parsed.supabaseId;
|
|
177
|
+
if (parsed.title && op === 'get') selector.title = parsed.title;
|
|
178
|
+
if (Object.keys(selector).length > 0) parsed.selector = selector;
|
|
179
|
+
|
|
180
|
+
return parsed;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function usageText() {
|
|
184
|
+
return [
|
|
185
|
+
'notesia <command> [options]',
|
|
186
|
+
'',
|
|
187
|
+
'Commands:',
|
|
188
|
+
' get --id <id>|--supabase-id <uuid>|--title <title> [--json] [--with-meta]',
|
|
189
|
+
' list [--limit <count>] [--format table|json]',
|
|
190
|
+
' store [--title <title>] [--tag <tag>]... [--folder-id <id>] [--content <text>]',
|
|
191
|
+
' update --id <id>|--supabase-id <uuid>|--title <title> [--content <text>] [--title <new>]',
|
|
192
|
+
' append --id <id>|--supabase-id <uuid>|--title <title> [--content <text>]',
|
|
193
|
+
' trash --id <id>|--supabase-id <uuid>|--title <title>',
|
|
194
|
+
' sync',
|
|
195
|
+
' auth status [--format text|json]',
|
|
196
|
+
'',
|
|
197
|
+
'AI Knowledge Base:',
|
|
198
|
+
' kb search --query <text> [--limit <n>] [--format text|json]',
|
|
199
|
+
' kb folders [--format text|json]',
|
|
200
|
+
' kb context --query <text> [--limit <n>]',
|
|
201
|
+
'',
|
|
202
|
+
'Pipe examples:',
|
|
203
|
+
' notesia get --id 12 > note.md',
|
|
204
|
+
' notesia list --json > notes.json',
|
|
205
|
+
' cat patch.md | notesia update --id 12',
|
|
206
|
+
' echo "- bullet" | notesia append --id 12',
|
|
207
|
+
'',
|
|
208
|
+
].join('\n');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function requireSelector(parsed) {
|
|
212
|
+
if (!parsed.selector) {
|
|
213
|
+
throw new CliCommandError(
|
|
214
|
+
'SELECTOR_REQUIRED',
|
|
215
|
+
'Selector is required (--id, --supabase-id, or --title)'
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
return parsed.selector;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function buildPayload(parsed, pipedContent) {
|
|
222
|
+
if (parsed.op === 'get') {
|
|
223
|
+
return {
|
|
224
|
+
selector: requireSelector(parsed),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (parsed.op === 'list') {
|
|
229
|
+
return {
|
|
230
|
+
limit: parsed.limit ?? 100,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (parsed.op === 'sync') {
|
|
235
|
+
return {};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (parsed.op === 'auth-status') {
|
|
239
|
+
return {};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (parsed.op === 'store') {
|
|
243
|
+
return {
|
|
244
|
+
title: parsed.title || undefined,
|
|
245
|
+
folder_id: parsed.folderId ?? null,
|
|
246
|
+
content: parsed.content ?? pipedContent ?? '',
|
|
247
|
+
tags: parsed.tags,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (parsed.op === 'update') {
|
|
252
|
+
const content = parsed.content ?? pipedContent;
|
|
253
|
+
const hasContent = content !== undefined;
|
|
254
|
+
const hasTitle = Boolean(parsed.title);
|
|
255
|
+
if (!hasContent && !hasTitle) {
|
|
256
|
+
throw new CliCommandError(
|
|
257
|
+
'MISSING_CONTENT',
|
|
258
|
+
'Update requires --content or --title (or piped stdin)'
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
selector: requireSelector(parsed),
|
|
263
|
+
content,
|
|
264
|
+
title: parsed.title || undefined,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (parsed.op === 'append') {
|
|
269
|
+
const content = parsed.content ?? pipedContent;
|
|
270
|
+
if (content === undefined || content === '') {
|
|
271
|
+
throw new CliCommandError(
|
|
272
|
+
'MISSING_CONTENT',
|
|
273
|
+
'Append requires non-empty --content or piped stdin'
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
return {
|
|
277
|
+
selector: requireSelector(parsed),
|
|
278
|
+
content,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (parsed.op === 'trash') {
|
|
283
|
+
return { selector: requireSelector(parsed) };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (parsed.op === 'kb-search') {
|
|
287
|
+
if (!parsed.query) {
|
|
288
|
+
throw new CliCommandError('MISSING_ARGS', '--query is required for kb search');
|
|
289
|
+
}
|
|
290
|
+
return { query: parsed.query, limit: parsed.limit ?? 20 };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (parsed.op === 'kb-folders') {
|
|
294
|
+
return {};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (parsed.op === 'kb-context') {
|
|
298
|
+
if (!parsed.query) {
|
|
299
|
+
throw new CliCommandError('MISSING_ARGS', '--query is required for kb context');
|
|
300
|
+
}
|
|
301
|
+
return { query: parsed.query, limit: parsed.limit ?? 5 };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
throw new CliCommandError('INVALID_OP', `Unsupported command: ${parsed.op} `);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export async function runCli(argv = [], {
|
|
308
|
+
requestBridge = defaultRequestBridge,
|
|
309
|
+
readInputContent = defaultReadInputContent,
|
|
310
|
+
writeStdout = (chunk) => process.stdout.write(chunk),
|
|
311
|
+
} = {}) {
|
|
312
|
+
const parsed = parseArgs(argv);
|
|
313
|
+
|
|
314
|
+
if (parsed.op === 'help') {
|
|
315
|
+
writeStdout(usageText());
|
|
316
|
+
return { ok: true, help: true };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const needsPipedInput = ['store', 'update', 'append'].includes(parsed.op) && parsed.content === undefined;
|
|
320
|
+
const pipedContent = needsPipedInput ? await readInputContent() : undefined;
|
|
321
|
+
|
|
322
|
+
const payload = buildPayload(parsed, pipedContent);
|
|
323
|
+
const request = {
|
|
324
|
+
id: randomUUID(),
|
|
325
|
+
op: parsed.op,
|
|
326
|
+
payload,
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const response = await requestBridge(request);
|
|
330
|
+
if (!response || typeof response !== 'object') {
|
|
331
|
+
throw new CliCommandError('INVALID_RESPONSE', 'Bridge returned an invalid response');
|
|
332
|
+
}
|
|
333
|
+
if (response.ok === false) {
|
|
334
|
+
const code = response.error?.code || 'BRIDGE_ERROR';
|
|
335
|
+
const message = response.error?.message || 'Bridge request failed';
|
|
336
|
+
throw new CliCommandError(code, message);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (parsed.op === 'get') {
|
|
340
|
+
printRetrieveResult(response.data, {
|
|
341
|
+
format: parsed.format,
|
|
342
|
+
withMeta: parsed.withMeta,
|
|
343
|
+
writeStdout,
|
|
344
|
+
});
|
|
345
|
+
} else if (parsed.op === 'list') {
|
|
346
|
+
printListResult(response.data, {
|
|
347
|
+
format: parsed.format === 'text' ? 'table' : parsed.format,
|
|
348
|
+
writeStdout,
|
|
349
|
+
});
|
|
350
|
+
} else if (parsed.op === 'auth-status') {
|
|
351
|
+
printAuthStatusResult(response.data, {
|
|
352
|
+
format: parsed.format,
|
|
353
|
+
writeStdout,
|
|
354
|
+
});
|
|
355
|
+
} else if (['kb-search', 'kb-folders', 'kb-context'].includes(parsed.op)) {
|
|
356
|
+
printKbResult(parsed.op, response.data, { format: parsed.format, writeStdout });
|
|
357
|
+
} else {
|
|
358
|
+
printMutationResult(response.data, {
|
|
359
|
+
format: parsed.format,
|
|
360
|
+
writeStdout,
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return response;
|
|
365
|
+
}
|
package/src/io.mjs
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
function defaultWriteStdout(chunk) {
|
|
2
|
+
process.stdout.write(chunk);
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
async function defaultReadStdin() {
|
|
6
|
+
if (process.stdin.isTTY) {
|
|
7
|
+
return '';
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
return new Promise((resolve, reject) => {
|
|
11
|
+
let value = '';
|
|
12
|
+
process.stdin.setEncoding('utf8');
|
|
13
|
+
process.stdin.on('data', (chunk) => {
|
|
14
|
+
value += chunk;
|
|
15
|
+
});
|
|
16
|
+
process.stdin.on('end', () => resolve(value));
|
|
17
|
+
process.stdin.on('error', reject);
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function readInputContent(readStdin = defaultReadStdin) {
|
|
22
|
+
return readStdin();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function printRetrieveResult(result, {
|
|
26
|
+
format = 'text',
|
|
27
|
+
withMeta = false,
|
|
28
|
+
writeStdout = defaultWriteStdout,
|
|
29
|
+
} = {}) {
|
|
30
|
+
if (format === 'json') {
|
|
31
|
+
writeStdout(`${JSON.stringify(result ?? {}, null, 2)}\n`);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (withMeta && result) {
|
|
35
|
+
const tags = Array.isArray(result.tags) ? result.tags.join(', ') : '';
|
|
36
|
+
const lines = [
|
|
37
|
+
'---',
|
|
38
|
+
`title: "${(result.title || '').replace(/"/g, '\\"')}"`,
|
|
39
|
+
`id: ${result.id ?? ''}`,
|
|
40
|
+
`updated_at: ${result.updated_at || ''}`,
|
|
41
|
+
];
|
|
42
|
+
if (tags) lines.push(`tags: [${tags}]`);
|
|
43
|
+
if (result.folder_id != null) lines.push(`folder_id: ${result.folder_id}`);
|
|
44
|
+
lines.push('---', '');
|
|
45
|
+
writeStdout(lines.join('\n'));
|
|
46
|
+
}
|
|
47
|
+
writeStdout(String(result?.content ?? ''));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function printMutationResult(result, {
|
|
51
|
+
format = 'text',
|
|
52
|
+
writeStdout = defaultWriteStdout,
|
|
53
|
+
} = {}) {
|
|
54
|
+
if (format === 'json') {
|
|
55
|
+
writeStdout(`${JSON.stringify(result ?? { ok: true }, null, 2)}\n`);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
writeStdout('ok\n');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function formatCell(value) {
|
|
62
|
+
if (value === null || value === undefined) return '';
|
|
63
|
+
return String(value).replace(/\s+/g, ' ').trim();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function truncate(text, maxLength) {
|
|
67
|
+
if (text.length <= maxLength) return text;
|
|
68
|
+
if (maxLength <= 1) return text.slice(0, maxLength);
|
|
69
|
+
return `${text.slice(0, maxLength - 1)}…`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function buildListTable(notes = []) {
|
|
73
|
+
const headers = ['ID', 'TITLE', 'UPDATED_AT', 'SECURE', 'FOLDER_ID'];
|
|
74
|
+
const rows = notes.map((note) => [
|
|
75
|
+
formatCell(note.id),
|
|
76
|
+
truncate(formatCell(note.title), 50),
|
|
77
|
+
formatCell(note.updated_at),
|
|
78
|
+
note.is_secure ? 'yes' : 'no',
|
|
79
|
+
formatCell(note.folder_id),
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
const widths = headers.map((header, idx) => {
|
|
83
|
+
const rowMax = rows.reduce((max, row) => Math.max(max, row[idx].length), 0);
|
|
84
|
+
return Math.max(header.length, rowMax);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const renderRow = (cells) => (
|
|
88
|
+
cells
|
|
89
|
+
.map((cell, idx) => cell.padEnd(widths[idx], ' '))
|
|
90
|
+
.join(' ')
|
|
91
|
+
.trimEnd()
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
const output = [
|
|
95
|
+
renderRow(headers),
|
|
96
|
+
widths.map((width) => '-'.repeat(width)).join(' '),
|
|
97
|
+
...rows.map(renderRow),
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
return `${output.join('\n')}\n`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function printListResult(result, {
|
|
104
|
+
format = 'table',
|
|
105
|
+
writeStdout = defaultWriteStdout,
|
|
106
|
+
} = {}) {
|
|
107
|
+
if (format === 'json') {
|
|
108
|
+
writeStdout(`${JSON.stringify(result ?? { notes: [], total: 0 }, null, 2)}\n`);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const notes = Array.isArray(result?.notes) ? result.notes : [];
|
|
113
|
+
if (notes.length === 0) {
|
|
114
|
+
writeStdout('No notes found.\n');
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
writeStdout(buildListTable(notes));
|
|
119
|
+
if (typeof result?.total === 'number') {
|
|
120
|
+
writeStdout(`Total: ${result.total}\n`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function printAuthStatusResult(result, {
|
|
125
|
+
format = 'text',
|
|
126
|
+
writeStdout = defaultWriteStdout,
|
|
127
|
+
} = {}) {
|
|
128
|
+
const authenticated = Boolean(result?.authenticated);
|
|
129
|
+
const payload = {
|
|
130
|
+
authenticated,
|
|
131
|
+
status: result?.status || (authenticated ? 'authenticated' : 'unauthenticated'),
|
|
132
|
+
user_id: result?.user_id || null,
|
|
133
|
+
email: result?.email || null,
|
|
134
|
+
provider: result?.provider || null,
|
|
135
|
+
source: result?.source || 'local-app',
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
if (format === 'json') {
|
|
139
|
+
writeStdout(`${JSON.stringify(payload, null, 2)}\n`);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const lines = [
|
|
144
|
+
`Authenticated: ${payload.authenticated ? 'yes' : 'no'}`,
|
|
145
|
+
`Status: ${payload.status}`,
|
|
146
|
+
`User ID: ${payload.user_id || 'none'}`,
|
|
147
|
+
];
|
|
148
|
+
|
|
149
|
+
if (payload.email) lines.push(`Email: ${payload.email}`);
|
|
150
|
+
if (payload.provider) lines.push(`Provider: ${payload.provider}`);
|
|
151
|
+
lines.push(`Source: ${payload.source}`);
|
|
152
|
+
|
|
153
|
+
writeStdout(`${lines.join('\n')}\n`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function printKbResult(op, result, {
|
|
157
|
+
format = 'text',
|
|
158
|
+
writeStdout = defaultWriteStdout,
|
|
159
|
+
} = {}) {
|
|
160
|
+
// kb-context always returns JSON (full note content)
|
|
161
|
+
if (format === 'json' || op === 'kb-context') {
|
|
162
|
+
writeStdout(`${JSON.stringify(result ?? {}, null, 2)}\n`);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (op === 'kb-search') {
|
|
167
|
+
const notes = Array.isArray(result?.notes) ? result.notes : [];
|
|
168
|
+
if (notes.length === 0) {
|
|
169
|
+
writeStdout('No results found.\n');
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const headers = ['ID', 'SCORE', 'TITLE', 'UPDATED_AT'];
|
|
173
|
+
const rows = notes.map((n) => [
|
|
174
|
+
formatCell(n.id),
|
|
175
|
+
formatCell(n.score),
|
|
176
|
+
truncate(formatCell(n.title), 50),
|
|
177
|
+
formatCell(n.updated_at),
|
|
178
|
+
]);
|
|
179
|
+
const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
180
|
+
const renderRow = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();
|
|
181
|
+
const tableLines = [renderRow(headers), widths.map((w) => '-'.repeat(w)).join(' '), ...rows.map(renderRow)];
|
|
182
|
+
writeStdout(`${tableLines.join('\n')}\n`);
|
|
183
|
+
if (result?.total != null) writeStdout(`\nFound: ${result.total}\n`);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (op === 'kb-folders') {
|
|
188
|
+
const folders = Array.isArray(result?.folders) ? result.folders : [];
|
|
189
|
+
if (folders.length === 0) {
|
|
190
|
+
writeStdout('No folders found.\n');
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const headers = ['ID', 'NAME', 'NOTES'];
|
|
194
|
+
const rows = folders.map((f) => [
|
|
195
|
+
formatCell(f.id ?? '-'),
|
|
196
|
+
truncate(formatCell(f.name), 40),
|
|
197
|
+
formatCell(f.note_count),
|
|
198
|
+
]);
|
|
199
|
+
const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
200
|
+
const renderRow = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();
|
|
201
|
+
const tableLines = [renderRow(headers), widths.map((w) => '-'.repeat(w)).join(' '), ...rows.map(renderRow)];
|
|
202
|
+
writeStdout(`${tableLines.join('\n')}\n`);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Fallback for unknown kb ops
|
|
207
|
+
writeStdout(`${JSON.stringify(result ?? {}, null, 2)}\n`);
|
|
208
|
+
}
|