@yasad/cli 0.0.0-stage → 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.
- package/README.md +24 -2
- package/bin/yasad.mjs +279 -0
- package/lib/check.mjs +184 -0
- package/lib/key.mjs +56 -0
- package/lib/mcp.mjs +270 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# yasad
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Yasad command line for AI assistants and agents. It makes private assistant keys, connects them over MCP and checks apps. No dependencies. Requires Node 24.
|
|
4
|
+
|
|
5
|
+
**Building an app?** You don't need this CLI. In Yasad, open **Apps → your app → Create API key**, put the two lines it shows (`YASAD_API_URL`, `YASAD_API_KEY`) in your server's `.env`, and `npm install @yasad/client`.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx @yasad/cli init https://YOUR-API-ORIGIN # private key in ~/.yasad + @yasad/client
|
|
9
|
+
npx @yasad/cli mcp add claude # or: codex, vscode, json (Cursor and others)
|
|
10
|
+
npx @yasad/cli check # fails if the app brings its own database
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
| Command | What it does |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| `yasad init <API_ORIGIN> [ENV_FILE]` | Makes a key and writes it to `ENV_FILE` (default `~/.yasad/workspace.env` in a 0700 folder; the file is never overwritten and is mode 0600 on Linux and macOS). Installs `@yasad/client` when a `package.json` exists. |
|
|
16
|
+
| `yasad key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]` | Makes a key only. Prints the key fingerprint for the owner to add under Settings → Add a key by hand, or the owner review link when given a workspace connect link. |
|
|
17
|
+
| `yasad mcp [--env FILE]` | Runs the read-only stdio MCP server in-process. It reads only `YASAD_*` (or legacy `FRESH_*`) settings from the file, and an explicit file wins over inherited settings. Set `YASAD_MCP_ALLOW_WRITES=1` (the legacy `FRESH_MCP_ALLOW_WRITES=1` also works) to allow writes the key permits. |
|
|
18
|
+
| `yasad mcp add <claude\|codex\|vscode\|json> [--env FILE] [--name NAME]` | Registers the server with Claude Code or Codex, or prints config for VS Code (`.vscode/mcp.json`) and other clients (`mcpServers`). Registrations pin this exact CLI version. If the client isn't installed, or on Windows, it prints a safely quoted command and exits 2 without registering anything. |
|
|
19
|
+
| `yasad check [DIR]` | Fails when an app stores business data outside Yasad, including business records kept in Redis without an expiry. Redis used as a cache or for coordination is listed for review, not failed. |
|
|
20
|
+
|
|
21
|
+
Use `--env FILE` with `npx` rather than exporting `YASAD_API_KEY`: `npx` starts a child process, and Node's `NODE_DEBUG=child_process` would print any exported key. On Windows, `mcp add claude|codex` prints the configuration to add instead of a command line, because cmd and PowerShell quote differently.
|
|
22
|
+
|
|
23
|
+
Key files must live outside every git repository. The CLI refuses any path with a `.git` in an ancestor folder (including nested repositories, symlinks and `..` paths) or inside `GIT_WORK_TREE`/`GIT_DIR`, rather than relying on `.gitignore`. It never edits files in your project.
|
|
24
|
+
|
|
25
|
+
Registration sends only the key's SHA-256 fingerprint; the key itself is sent only to its own API origin, over HTTPS (plain HTTP only for local development addresses). New key files use `YASAD_API_URL`/`YASAD_API_KEY` and `ysk_` keys. The MCP server, key maker and checker are byte-identical to the `/agent/mcp.mjs`, `/agent/key.mjs` and `/agent/check.mjs` downloads, so either route behaves the same.
|
package/bin/yasad.mjs
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Yasad command line. New first-party code. Node 24, no dependencies.
|
|
3
|
+
// lib/mcp.mjs, lib/key.mjs and lib/check.mjs are byte-identical copies of the hosted
|
|
4
|
+
// /agent/* downloads (tests enforce this), so `npx @yasad/cli` and the downloads behave the same.
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { createInterface } from 'node:readline';
|
|
9
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
10
|
+
import { parseEnv } from 'node:util';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { createBridge, createProtocol, origin as apiOrigin } from '../lib/mcp.mjs';
|
|
13
|
+
|
|
14
|
+
const lib = fileURLToPath(new URL('../lib/', import.meta.url));
|
|
15
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
16
|
+
// Outside any project directory, so a key cannot be committed with application code.
|
|
17
|
+
const DEFAULT_ENV = join(homedir(), '.yasad', 'workspace.env');
|
|
18
|
+
const windows = process.platform === 'win32';
|
|
19
|
+
const [command, ...args] = process.argv.slice(2);
|
|
20
|
+
// Node itself honours --env-file and --env-file-if-exists anywhere on the command line, before this
|
|
21
|
+
// script runs, and would
|
|
22
|
+
// apply NODE_OPTIONS from the file. This CLI therefore uses --env and refuses --env-file.
|
|
23
|
+
if (args.some((arg) => /^--env-file(-if-exists)?(=|$)/.test(arg))) {
|
|
24
|
+
console.error('Use --env FILE. Node loads --env-file itself before yasad runs, including any NODE_OPTIONS in it.');
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const help = `yasad ${version}
|
|
29
|
+
|
|
30
|
+
Usage
|
|
31
|
+
npx @yasad/cli init <API_ORIGIN> [ENV_FILE] Make a private key outside your repository, install @yasad/client
|
|
32
|
+
npx @yasad/cli key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]
|
|
33
|
+
Make a private key; prints the code (or review link) to approve
|
|
34
|
+
npx @yasad/cli mcp [--env FILE] Run the MCP server over stdio (read-only unless allowed)
|
|
35
|
+
npx @yasad/cli mcp add <claude|codex|vscode|json> [--env FILE] [--name NAME]
|
|
36
|
+
Connect an AI client to your workspace
|
|
37
|
+
npx @yasad/cli check [DIR] Static policy lint: flags app code that brings its own database
|
|
38
|
+
npx @yasad/cli doctor [--env FILE] Check a key: which workspace, app and role it reaches (never prints the key)
|
|
39
|
+
|
|
40
|
+
ENV_FILE defaults to ${DEFAULT_ENV} and must be outside any git repository. Registration sends only the key's fingerprint;
|
|
41
|
+
the key itself is sent only to its own API origin. Find API_ORIGIN on the dashboard's Connect page.
|
|
42
|
+
|
|
43
|
+
Building an app? You don't need this CLI: create a key on the app's page in Yasad (Apps → your app → API keys)
|
|
44
|
+
and put YASAD_API_URL and YASAD_API_KEY in the app's server .env.`;
|
|
45
|
+
|
|
46
|
+
function fail(message, code = 1) {
|
|
47
|
+
console.error(message);
|
|
48
|
+
process.exit(code);
|
|
49
|
+
}
|
|
50
|
+
function option(name, fallback) {
|
|
51
|
+
const index = args.indexOf(name);
|
|
52
|
+
if (index === -1) return fallback;
|
|
53
|
+
const value = args[index + 1];
|
|
54
|
+
if (!value || value.startsWith('--')) fail(`${name} needs a value.`);
|
|
55
|
+
args.splice(index, 2);
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
/** Quote one argument for a POSIX shell: nothing inside single quotes is expanded. */
|
|
59
|
+
const sh = (value) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${String(value).replaceAll("'", `'\\''`)}'`);
|
|
60
|
+
const shell = (parts) => parts.map(sh).join(' ');
|
|
61
|
+
function run(script, scriptArgs) {
|
|
62
|
+
const result = spawnSync(process.execPath, [join(lib, script), ...scriptArgs], { stdio: 'inherit' });
|
|
63
|
+
if (result.status !== 0) process.exit(result.status ?? 1);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Read only the Yasad settings from an env file. Everything else in it is ignored, never exported. */
|
|
67
|
+
function readSettings(file) {
|
|
68
|
+
if (!existsSync(file)) fail(`No env file at ${file}. Run \`npx @yasad/cli key\` first.`);
|
|
69
|
+
// Node's own dotenv parser, so quoted and multi-line values are read exactly as Node would. Windows
|
|
70
|
+
// editors sometimes save .env as UTF-16 (PowerShell 5 `>`) or with a UTF-8 byte-order mark; read
|
|
71
|
+
// those too, and warn, because `node --env-file` silently misreads them.
|
|
72
|
+
const raw = readFileSync(file);
|
|
73
|
+
let text;
|
|
74
|
+
if (raw[0] === 0xff && raw[1] === 0xfe) text = raw.subarray(2).toString('utf16le');
|
|
75
|
+
else if (raw[0] === 0xfe && raw[1] === 0xff) text = Buffer.from(raw.subarray(2)).swap16().toString('utf16le');
|
|
76
|
+
else text = raw.toString('utf8').replace(/^\uFEFF/, '');
|
|
77
|
+
if (text !== raw.toString('utf8'))
|
|
78
|
+
console.error(`Warning: ${file} is saved as UTF-16 or with a byte-order mark. \`node --env-file\` cannot read it reliably; save it as UTF-8 (in VS Code: "Save with Encoding" → UTF-8; in PowerShell: Set-Content -Encoding ascii).`);
|
|
79
|
+
const parsed = parseEnv(text), values = {};
|
|
80
|
+
for (const family of ['YASAD', 'FRESH']) for (const name of ['API_URL', 'API_KEY', 'MCP_ALLOW_WRITES']) {
|
|
81
|
+
if (Object.hasOwn(parsed, `${family}_${name}`)) values[`${family}_${name}`] = parsed[`${family}_${name}`];
|
|
82
|
+
}
|
|
83
|
+
return values;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Choose one settings family. The key and its origin always come from the same family, so a key is
|
|
87
|
+
* never sent to an origin configured for another key. YASAD_* wins over the legacy FRESH_* names.
|
|
88
|
+
*/
|
|
89
|
+
function credentials(source) {
|
|
90
|
+
const set = (name) => (source[name] === undefined || source[name] === '' ? undefined : source[name]);
|
|
91
|
+
const family = set('YASAD_API_KEY') ? 'YASAD' : set('FRESH_API_KEY') ? 'FRESH' : null;
|
|
92
|
+
if (!family) return null;
|
|
93
|
+
return {
|
|
94
|
+
// Never a guessed address: a key without its URL is refused, as in the SDK.
|
|
95
|
+
baseUrl: set(`${family}_API_URL`),
|
|
96
|
+
apiKey: set(`${family}_API_KEY`),
|
|
97
|
+
// The write opt-in is not a credential, so either spelling works with any key file.
|
|
98
|
+
allowWrites: (set('YASAD_MCP_ALLOW_WRITES') ?? set('FRESH_MCP_ALLOW_WRITES')) === '1',
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The real location of a key file. The parent is resolved by the operating system from the path as
|
|
104
|
+
* given (a symlink followed by `..` goes where the OS goes, not where string normalization goes), and
|
|
105
|
+
* this one canonical path is used for the repository check, the key writer and the MCP server.
|
|
106
|
+
*/
|
|
107
|
+
function canonical(file) {
|
|
108
|
+
const parent = dirname(file);
|
|
109
|
+
// Without an existing folder the OS cannot resolve symlinks and `..` for us, so refuse to guess.
|
|
110
|
+
if (!existsSync(parent)) fail(`The folder for ${file} does not exist. Create it first (outside any git repository).`);
|
|
111
|
+
return join(realpathSync.native(parent), basename(file));
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Keys never live inside a git repository. Rather than trusting .gitignore (which nested repositories,
|
|
115
|
+
* alternate indexes and pathspec rules can all defeat), refuse any path with a `.git` entry in any
|
|
116
|
+
* ancestor directory, or inside an explicitly configured GIT_WORK_TREE.
|
|
117
|
+
*/
|
|
118
|
+
function outsideRepositories(target) {
|
|
119
|
+
for (let dir = dirname(target); ; dir = dirname(dir)) {
|
|
120
|
+
if (existsSync(join(dir, '.git'))) fail(`${target} is inside the git repository at ${dir}. Keys must live outside repositories; the default is ${DEFAULT_ENV}.`);
|
|
121
|
+
if (dirname(dir) === dir) break;
|
|
122
|
+
}
|
|
123
|
+
// With GIT_DIR or GIT_WORK_TREE set, git's work tree can be anywhere (including core.worktree), so
|
|
124
|
+
// a directory check cannot be trusted. Refuse instead of guessing.
|
|
125
|
+
for (const name of ['GIT_DIR', 'GIT_WORK_TREE']) {
|
|
126
|
+
if (process.env[name]) fail(`${name} is set, so yasad cannot tell which folders git tracks. Unset it and run again.`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** Resolve the key path; the default directory is created privately on first use. */
|
|
130
|
+
function keyPath(file) {
|
|
131
|
+
if (file === DEFAULT_ENV) mkdirSync(dirname(DEFAULT_ENV), { recursive: true, mode: 0o700 });
|
|
132
|
+
const target = canonical(file);
|
|
133
|
+
outsideRepositories(target);
|
|
134
|
+
return target;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The stdio MCP server, run in this process so the key is never placed in a child environment. */
|
|
138
|
+
async function serve(settings) {
|
|
139
|
+
if (!settings) fail('No YASAD_API_KEY found. Pass --env FILE or set YASAD_API_URL and YASAD_API_KEY.');
|
|
140
|
+
if (!settings.baseUrl) fail('The API URL is not set next to the key. Add YASAD_API_URL (or FRESH_API_URL for a FRESH_API_KEY) to the env file.');
|
|
141
|
+
const handle = createProtocol(createBridge(settings));
|
|
142
|
+
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
143
|
+
for await (const line of input) {
|
|
144
|
+
if (!line.trim()) continue;
|
|
145
|
+
let response;
|
|
146
|
+
try {
|
|
147
|
+
if (Buffer.byteLength(line) > 65536) throw new Error('oversized');
|
|
148
|
+
response = await handle(JSON.parse(line));
|
|
149
|
+
} catch {
|
|
150
|
+
response = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid JSON message' } };
|
|
151
|
+
}
|
|
152
|
+
if (response) process.stdout.write(JSON.stringify(response) + '\n');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
switch (command) {
|
|
157
|
+
case undefined:
|
|
158
|
+
case 'help':
|
|
159
|
+
case '--help':
|
|
160
|
+
case '-h':
|
|
161
|
+
console.log(help);
|
|
162
|
+
break;
|
|
163
|
+
case '--version':
|
|
164
|
+
case '-v':
|
|
165
|
+
console.log(version);
|
|
166
|
+
break;
|
|
167
|
+
case 'key': {
|
|
168
|
+
const [origin, file = DEFAULT_ENV, ...rest] = args;
|
|
169
|
+
if (!origin) fail('Usage: npx @yasad/cli key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]');
|
|
170
|
+
const target = keyPath(file);
|
|
171
|
+
run('key.mjs', [origin, target, ...rest]);
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
case 'init': {
|
|
175
|
+
const [origin, file = DEFAULT_ENV] = args;
|
|
176
|
+
if (!origin) fail('Usage: npx @yasad/cli init <API_ORIGIN> [ENV_FILE]');
|
|
177
|
+
const target = keyPath(file);
|
|
178
|
+
run('key.mjs', [origin, target]);
|
|
179
|
+
const sdk = `@yasad/client@^${version.split('.').slice(0, 2).join('.')}.0`;
|
|
180
|
+
if (existsSync('package.json')) {
|
|
181
|
+
// Fixed arguments only, so the Windows shell needed for npm.cmd sees no user input.
|
|
182
|
+
const installed = spawnSync(windows ? 'npm.cmd' : 'npm', ['install', sdk], { stdio: 'inherit', shell: windows });
|
|
183
|
+
if (installed.status !== 0) fail(`npm install ${sdk} failed. Install it yourself, then continue.`);
|
|
184
|
+
} else {
|
|
185
|
+
console.log(`No package.json here. Install the SDK in your app with: npm install ${sdk}`);
|
|
186
|
+
}
|
|
187
|
+
console.log(`\nNext: the workspace owner approves the fingerprint above in Yasad. Then load the key in your server with\n new Yasad({ envFile: ${JSON.stringify(target)} })`);
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
case 'mcp': {
|
|
191
|
+
if (args[0] === 'add') {
|
|
192
|
+
args.shift();
|
|
193
|
+
const client = args.shift();
|
|
194
|
+
// Same OS-resolved path rules as `key`, so the file it created is the file registered.
|
|
195
|
+
const file = canonical(option('--env', DEFAULT_ENV)), name = option('--name', 'yasad');
|
|
196
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) fail('--name may use letters, digits, - and _.');
|
|
197
|
+
if (!existsSync(file)) fail(`No env file at ${file}. Run \`npx @yasad/cli key\` first.`);
|
|
198
|
+
// Pin the exact CLI version so the client never runs a different release than you approved.
|
|
199
|
+
const server = ['npx', '-y', `@yasad/cli@${version}`, 'mcp', '--env', file];
|
|
200
|
+
if (client === 'claude' || client === 'codex') {
|
|
201
|
+
const add = client === 'claude' ? ['mcp', 'add', '--transport', 'stdio', '--scope', 'local', name, '--', ...server] : ['mcp', 'add', name, '--', ...server];
|
|
202
|
+
// Windows agent CLIs are .cmd shims that need a shell, and cmd/PowerShell quote differently,
|
|
203
|
+
// so on Windows print configuration instead of a command line.
|
|
204
|
+
if (windows) {
|
|
205
|
+
// JSON strings are valid TOML basic strings, so paths are escaped correctly for both formats.
|
|
206
|
+
const config = client === 'codex'
|
|
207
|
+
? `Add this to ~/.codex/config.toml:\n[mcp_servers.${name}]\ncommand = ${JSON.stringify(server[0])}\nargs = [${server.slice(1).map((part) => JSON.stringify(part)).join(', ')}]`
|
|
208
|
+
: `Add this to Claude Code's MCP settings (.mcp.json):\n${JSON.stringify({ mcpServers: { [name]: { command: server[0], args: server.slice(1) } } }, null, 2)}`;
|
|
209
|
+
console.log(`Nothing was registered. ${config}`);
|
|
210
|
+
process.exit(2);
|
|
211
|
+
}
|
|
212
|
+
const found = spawnSync(client, ['--version'], { stdio: 'ignore' }).status === 0;
|
|
213
|
+
if (!found) {
|
|
214
|
+
console.log(`${client} was not run (not installed here). Nothing was registered. Run in a POSIX shell:\n ${shell([client, ...add])}`);
|
|
215
|
+
process.exit(2);
|
|
216
|
+
}
|
|
217
|
+
const result = spawnSync(client, add, { stdio: 'inherit' });
|
|
218
|
+
process.exit(result.status ?? 1);
|
|
219
|
+
}
|
|
220
|
+
if (client === 'vscode') {
|
|
221
|
+
console.log(JSON.stringify({ servers: { [name]: { type: 'stdio', command: server[0], args: server.slice(1) } } }, null, 2));
|
|
222
|
+
console.log('\nAdd this to .vscode/mcp.json.');
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
if (client === 'json') {
|
|
226
|
+
console.log(JSON.stringify({ mcpServers: { [name]: { command: server[0], args: server.slice(1) } } }, null, 2));
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
fail('Usage: npx @yasad/cli mcp add <claude|codex|vscode|json> [--env FILE] [--name NAME]');
|
|
230
|
+
}
|
|
231
|
+
const file = option('--env', undefined);
|
|
232
|
+
// An explicitly chosen file wins over inherited settings; it is never merged with them.
|
|
233
|
+
await serve(credentials(file ? readSettings(canonical(file)) : process.env));
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
case 'doctor': {
|
|
237
|
+
// Reads settings the way the SDK does (YASAD_* first, legacy FRESH_* only as a pair) and makes one
|
|
238
|
+
// read-only request. It prints where the settings came from and a short key hint, never the key.
|
|
239
|
+
const file = option('--env');
|
|
240
|
+
const source = file ? readSettings(resolve(file)) : process.env;
|
|
241
|
+
const from = file ? resolve(file) : 'this shell\'s environment';
|
|
242
|
+
const value = (name) => (source[name] === undefined || source[name] === '' ? undefined : source[name]);
|
|
243
|
+
const family = value('YASAD_API_KEY') ? 'YASAD' : value('FRESH_API_KEY') ? 'FRESH' : null;
|
|
244
|
+
if (!family)
|
|
245
|
+
fail(`No YASAD_API_KEY in ${from}.\nCreate a key in Yasad (Apps → your app → Create API key) and put YASAD_API_URL and YASAD_API_KEY in your server .env.\nThen run: npx @yasad/cli doctor --env .env`, 2);
|
|
246
|
+
const url = value(`${family}_API_URL`);
|
|
247
|
+
if (!url) fail(`${family}_API_URL is not set in ${from}. Copy it from the same place as the key.`, 2);
|
|
248
|
+
let base;
|
|
249
|
+
try {
|
|
250
|
+
base = apiOrigin(url);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
fail(`${family}_API_URL is not usable: ${error.message}.`, 2);
|
|
253
|
+
}
|
|
254
|
+
const key = value(`${family}_API_KEY`);
|
|
255
|
+
console.log(`Settings: ${from} (${family}_* names)\nAPI: ${base}\nKey: ${key.slice(0, 4)}…${key.slice(-4)}`);
|
|
256
|
+
let response;
|
|
257
|
+
try {
|
|
258
|
+
response = await fetch(base + '/v1/capabilities', { headers: { authorization: 'Bearer ' + key }, redirect: 'error', signal: AbortSignal.timeout(15000) });
|
|
259
|
+
} catch (error) {
|
|
260
|
+
fail(`Could not reach ${base}: ${error.cause?.code ?? error.message}. Check the address and your network.`, 2);
|
|
261
|
+
}
|
|
262
|
+
const text = await response.text();
|
|
263
|
+
let body;
|
|
264
|
+
try {
|
|
265
|
+
body = JSON.parse(text);
|
|
266
|
+
} catch {
|
|
267
|
+
fail(`${base} answered HTTP ${response.status} without JSON. Is ${family}_API_URL your Yasad API address rather than the website?`, 2);
|
|
268
|
+
}
|
|
269
|
+
if (!response.ok) fail(`Not connected: HTTP ${response.status} ${body.error ?? ''}: ${body.message ?? ''}\n${body.details?.recovery ?? ''}`.trim(), 2);
|
|
270
|
+
const caller = body.context?.caller;
|
|
271
|
+
console.log(`Workspace: ${body.context?.workspaceName ?? '?'} (${body.workspaceId})\nCaller: ${caller ? caller.name + ' (' + caller.kind + ')' : 'a key not assigned to an app'}\nRole: ${body.role}\nCan call: ${body.operations?.length ?? 0} operations\nMode: ${body.context?.environment ?? 'unknown'}\n\nConnected.${family === 'FRESH' ? ' Rename FRESH_API_URL/FRESH_API_KEY to YASAD_API_URL/YASAD_API_KEY when convenient.' : ''}`);
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
case 'check':
|
|
275
|
+
run('check.mjs', args);
|
|
276
|
+
break;
|
|
277
|
+
default:
|
|
278
|
+
fail(`Unknown command: ${command}\n\n${help}`);
|
|
279
|
+
}
|
package/lib/check.mjs
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Yasad data check: a static policy lint. Run in an app repository: `node check.mjs [project-directory]`.
|
|
3
|
+
// Fails when the app's code brings its own database or data file instead of storing data in Yasad, or
|
|
4
|
+
// keeps business records in Redis without an expiry; lists caches and browser storage for review. Pattern matching cannot prove that records persist
|
|
5
|
+
// in Yasad or that access is authorized; test the app's real flows for that.
|
|
6
|
+
// Node 24, no dependencies, reads files only. New first-party code.
|
|
7
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
8
|
+
import { join, relative, extname } from 'node:path';
|
|
9
|
+
import { pathToFileURL } from 'node:url';
|
|
10
|
+
|
|
11
|
+
/** Packages whose purpose is a separate datastore or an ORM for one. */
|
|
12
|
+
export const databasePackages = [
|
|
13
|
+
'better-sqlite3', 'sqlite', 'sqlite3', '@libsql/client', 'sql.js',
|
|
14
|
+
'pg', 'postgres', '@neondatabase/serverless', '@vercel/postgres', 'pg-promise', 'slonik',
|
|
15
|
+
'mysql', 'mysql2', 'mariadb', 'mssql', 'tedious', 'oracledb',
|
|
16
|
+
'mongodb', 'mongoose',
|
|
17
|
+
'prisma', '@prisma/client', 'drizzle-orm', 'knex', 'kysely', 'typeorm', 'sequelize', 'objection',
|
|
18
|
+
'@mikro-orm/core', 'lowdb', 'nedb', '@seald-io/nedb', 'level', 'classic-level', 'lmdb', 'pouchdb',
|
|
19
|
+
'@supabase/supabase-js', 'firebase', 'firebase-admin', '@google-cloud/firestore', '@aws-sdk/client-dynamodb',
|
|
20
|
+
'dexie', 'idb', 'localforage',
|
|
21
|
+
];
|
|
22
|
+
/**
|
|
23
|
+
* Caches and key-value stores. Allowed for caching and temporary coordination (Nik, 2026-12-02), so a
|
|
24
|
+
* dependency is listed for review, not failed. What fails is using one as a business database: a
|
|
25
|
+
* write of a business record with no expiry (see kvWrite below).
|
|
26
|
+
*/
|
|
27
|
+
export const cachePackages = ['memcached', 'lru-cache', 'keyv', 'redis', 'ioredis', '@upstash/redis', '@vercel/kv'];
|
|
28
|
+
const kvClients = ['redis', 'ioredis', '@upstash/redis', '@vercel/kv', 'memcached', 'keyv'];
|
|
29
|
+
const kvImport = new RegExp(`(?:from\\s+|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:${kvClients.map((p) => p.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|')})(?:/[^'"]*)?['"]`);
|
|
30
|
+
/** Redis-only write commands (any receiver name), and generic set/append on a client-like receiver. */
|
|
31
|
+
const kvCommand = /\.\s*(?:setnx|mset|msetnx|hset|hmset|hsetnx|lpush|rpush|sadd|zadd|xadd|json\.set|jsonSet|hSet|hSetNX|lPush|rPush|sAdd|zAdd|xAdd|mSet)\s*\(/;
|
|
32
|
+
const kvWrite = /\b(?:\w*(?:redis|Redis|kv|KV|cache|Cache|upstash|Upstash)\w*|client|multi|pipeline|tx|r|db|store|conn)\s*(?:\(\s*\))?\s*\.\s*(?:set|append)\s*\(/;
|
|
33
|
+
/** The key a write names: its string prefix (`'order:'`), or the variable it uses. */
|
|
34
|
+
const writtenKey = (text) => /\.\s*\w+(?:\.\w+)?\s*\(\s*(?:[`'"]([^`'"$]+)|([A-Za-z_$][\w$.]*))/.exec(text)?.slice(1).find(Boolean);
|
|
35
|
+
/** An expiry given with the write or set right after it. */
|
|
36
|
+
const kvExpiry = /\b(?:EX|PX|EXAT|PXAT)\b|\b(?:ex|px|exat|pxat|ttl|expiresIn|expirationTtl)\s*:|\b(?:setex|psetex|setEx|pSetEx|expire|pexpire|expireat|pexpireat|expireAt)\s*\(|\bKEEPTTL\b/;
|
|
37
|
+
/** A key or value that names a business record. */
|
|
38
|
+
const businessKey = /(?<![a-z])(?:customers?|orders?|bookings?|reservations?|payments?|invoices?|appointments?|leads?|contacts?|guests?|patients?|products?|inventory|menus?|receipts?)(?![a-z])/i;
|
|
39
|
+
const kvPersist = /\.persist\s*\(/;
|
|
40
|
+
const code = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx', '.py', '.rb', '.go']);
|
|
41
|
+
const skip = new Set(['node_modules', '.git', '.next', 'dist', 'build', 'out', 'coverage', '.turbo', '.vercel']);
|
|
42
|
+
const dataFile = /\.(sqlite3?|db|db3|mdb)$|^schema\.prisma$|^drizzle\.config\.[cm]?[jt]s$|^knexfile\.[cm]?[jt]s$/i;
|
|
43
|
+
/** Append-only record logs (JSON Lines) kept in a data folder. Static .json content such as translations is fine. */
|
|
44
|
+
const dataFolder = /(^|[\\/])(data|db|database|storage|store)[\\/]/i;
|
|
45
|
+
const recordFile = /\.(jsonl|ndjson)$/i;
|
|
46
|
+
/** A write call, in JavaScript or Python. */
|
|
47
|
+
const writeCall = /\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream|json\.dump)\s*\(/;
|
|
48
|
+
/** A data file name in a string literal (often kept in a variable or split across lines). */
|
|
49
|
+
const namedDataFile = /['"`][^'"`\n]*\.(?:json|jsonl|ndjson|csv)['"`]/;
|
|
50
|
+
/** Well-known configuration and build files are not business records. */
|
|
51
|
+
const configFile = /['"`][^'"`\n]*(?:package|package-lock|tsconfig|jsconfig|manifest|vercel|components|composer|app|\.?eslintrc|\.?prettierrc)\.json['"`]/;
|
|
52
|
+
/** A line that only reads a file, such as a build script loading translations. */
|
|
53
|
+
const readCall = /\b(?:readFile|readFileSync|import|require|fetch)\s*\(/;
|
|
54
|
+
const escaped = databasePackages.map((p) => p.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|');
|
|
55
|
+
const sourcePatterns = [
|
|
56
|
+
[new RegExp(`(?:from\\s+|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:node:sqlite|${escaped})(?:/[^'"]*)?['"]`), 'imports a database client'],
|
|
57
|
+
[/\bnew\s+DatabaseSync\s*\(|\bsqlite3\.connect\s*\(|\bcreate_engine\s*\(/, 'opens a database'],
|
|
58
|
+
[/\bCREATE\s+TABLE\b/i, 'defines its own tables'],
|
|
59
|
+
[/\bindexedDB\.open\s*\(/, 'stores records in the browser'],
|
|
60
|
+
// Review only: preferences and drafts are fine, customer or order records are not.
|
|
61
|
+
[/\b(?:localStorage|sessionStorage)\.setItem\s*\(/, 'review: saves data in browser storage', 'warning'],
|
|
62
|
+
[new RegExp(`(?:from\\s+|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:${cachePackages.map((p) => p.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|')})(?:/[^'"]*)?['"]`), 'review: uses a cache or key-value store (allowed only for caching and temporary coordination)', 'warning'],
|
|
63
|
+
[/\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream)\s*\([^)]*\.(?:json|jsonl|ndjson|csv)\b/, 'saves data to a file'],
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
async function* walk(dir, root) {
|
|
67
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
68
|
+
if (entry.name.startsWith('.') && entry.name !== '.env.example' && entry.isDirectory()) continue;
|
|
69
|
+
if (skip.has(entry.name)) continue;
|
|
70
|
+
const path = join(dir, entry.name);
|
|
71
|
+
if (entry.isDirectory()) yield* walk(path, root);
|
|
72
|
+
else if (entry.isFile()) yield path;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Failures only. Use reviewProject for the full list including review-only warnings. */
|
|
77
|
+
export async function checkProject(root) {
|
|
78
|
+
return (await reviewProject(root)).filter((f) => f.severity !== 'warning');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** @returns {Promise<{file:string,line:number,problem:string,detail:string,severity?:'warning'}[]>} */
|
|
82
|
+
export async function reviewProject(root) {
|
|
83
|
+
const findings = [];
|
|
84
|
+
const paths = [];
|
|
85
|
+
for await (const path of walk(root, root)) paths.push(path);
|
|
86
|
+
// A project that depends on or imports a key-value client has every code file checked for writes,
|
|
87
|
+
// because the client is usually created in one module and used from others.
|
|
88
|
+
let kvProject = false;
|
|
89
|
+
for (const path of paths) {
|
|
90
|
+
const name = path.split(/[\\/]/).pop();
|
|
91
|
+
if (name === 'package.json') {
|
|
92
|
+
try {
|
|
93
|
+
const pkg = JSON.parse(await readFile(path, 'utf8'));
|
|
94
|
+
kvProject ||= ['dependencies', 'devDependencies', 'optionalDependencies'].some((f) => Object.keys(pkg[f] ?? {}).some((d) => kvClients.includes(d)));
|
|
95
|
+
} catch {}
|
|
96
|
+
} else if (!kvProject && code.has(extname(name)) && (await stat(path)).size <= 1_000_000 && kvImport.test(await readFile(path, 'utf8'))) kvProject = true;
|
|
97
|
+
}
|
|
98
|
+
for (const path of paths) {
|
|
99
|
+
const file = relative(root, path) || path;
|
|
100
|
+
const name = path.split(/[\\/]/).pop();
|
|
101
|
+
if (dataFile.test(name)) {
|
|
102
|
+
findings.push({ file, line: 0, problem: 'keeps a separate database or schema file', detail: name });
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (recordFile.test(name) && dataFolder.test(file)) {
|
|
106
|
+
findings.push({ file, line: 0, problem: 'keeps records in a data file', detail: name });
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (name === 'package.json') {
|
|
110
|
+
let pkg;
|
|
111
|
+
try {
|
|
112
|
+
pkg = JSON.parse(await readFile(path, 'utf8'));
|
|
113
|
+
} catch {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
for (const field of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'])
|
|
117
|
+
for (const dep of Object.keys(pkg[field] ?? {}))
|
|
118
|
+
if (databasePackages.includes(dep))
|
|
119
|
+
findings.push({ file, line: 0, problem: 'depends on a database package', detail: dep });
|
|
120
|
+
else if (cachePackages.includes(dep))
|
|
121
|
+
findings.push({ file, line: 0, problem: 'review: depends on a cache or key-value store (allowed only for caching and temporary coordination)', detail: dep, severity: 'warning' });
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (!code.has(extname(name)) || (await stat(path)).size > 1_000_000) continue;
|
|
125
|
+
const lines = (await readFile(path, 'utf8')).split('\n');
|
|
126
|
+
// A data file named in this file outside a read (often in a variable, or across lines) and written here.
|
|
127
|
+
const namesData = lines.some((text) => namedDataFile.test(text) && !configFile.test(text) && !readCall.test(text));
|
|
128
|
+
lines.forEach((text, i) => {
|
|
129
|
+
let flagged = false;
|
|
130
|
+
for (const [pattern, problem, severity] of sourcePatterns)
|
|
131
|
+
if (pattern.test(text)) {
|
|
132
|
+
findings.push({ file, line: i + 1, problem, detail: text.trim().slice(0, 120), ...(severity && { severity }) });
|
|
133
|
+
flagged ||= problem === 'saves data to a file';
|
|
134
|
+
}
|
|
135
|
+
if (!flagged && namesData && writeCall.test(text))
|
|
136
|
+
findings.push({ file, line: i + 1, problem: 'saves data to a file', detail: text.trim().slice(0, 120) });
|
|
137
|
+
});
|
|
138
|
+
// Key-value writes, in projects that use a key-value client (Map.set and the like are ignored
|
|
139
|
+
// unless the receiver looks like a client).
|
|
140
|
+
if (kvProject)
|
|
141
|
+
lines.forEach((text, i) => {
|
|
142
|
+
const detail = text.trim().slice(0, 120);
|
|
143
|
+
if (kvPersist.test(text)) {
|
|
144
|
+
findings.push({ file, line: i + 1, problem: 'removes the expiry from a key-value entry (Redis is a cache, not a database)', detail });
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (!kvCommand.test(text) && !kvWrite.test(text)) return;
|
|
148
|
+
// An expiry in the write itself, or an expire call for the same key within the next three lines.
|
|
149
|
+
const key = writtenKey(text);
|
|
150
|
+
const expires = kvExpiry.test(text) || (key && lines.slice(i + 1, i + 4).some((next) => kvExpiry.test(next) && next.includes(key)));
|
|
151
|
+
if (expires) return;
|
|
152
|
+
if (businessKey.test(text))
|
|
153
|
+
findings.push({ file, line: i + 1, problem: 'stores business records in a key-value store with no expiry (keep them in Yasad; cache copies must expire)', detail });
|
|
154
|
+
else
|
|
155
|
+
findings.push({ file, line: i + 1, problem: 'review: key-value write without an expiry (caches must expire and be rebuildable from Yasad)', detail, severity: 'warning' });
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return findings;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
162
|
+
const root = process.argv[2] ?? '.';
|
|
163
|
+
const all = await reviewProject(root);
|
|
164
|
+
const failures = all.filter((f) => f.severity !== 'warning'), warnings = all.filter((f) => f.severity === 'warning');
|
|
165
|
+
const show = (list) => list.forEach((f) => console.log(` ${f.file}${f.line ? ':' + f.line : ''} ${f.problem}: ${f.detail}`));
|
|
166
|
+
if (!failures.length) {
|
|
167
|
+
console.log('Yasad data check (static policy lint) passed: no separate database or data file found in the code.');
|
|
168
|
+
} else {
|
|
169
|
+
console.log('Yasad data check (static policy lint) failed. This app stores data outside its Yasad workspace:\n');
|
|
170
|
+
show(failures);
|
|
171
|
+
console.log(
|
|
172
|
+
'\nMove this data into Yasad. Use native records where they fit and create a custom collection',
|
|
173
|
+
'\n(createCollection, then createRecord) for everything else. If your credential cannot write,',
|
|
174
|
+
'\nask the owner to approve an operator credential. Then remove the database code and run this check again.',
|
|
175
|
+
);
|
|
176
|
+
process.exitCode = 1;
|
|
177
|
+
}
|
|
178
|
+
if (warnings.length) {
|
|
179
|
+
console.log('\nReview these (allowed for caches, temporary coordination, preferences and drafts; never for business records):');
|
|
180
|
+
show(warnings);
|
|
181
|
+
}
|
|
182
|
+
console.log('\nThis lint reads code only. It does not prove that records persist in Yasad or that access is authorized:');
|
|
183
|
+
console.log('test the real flows (create, read back after a restart, and a denied request).');
|
|
184
|
+
}
|
package/lib/key.mjs
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Run on the application server. Only the digest goes into the dashboard.
|
|
2
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
3
|
+
import { writeFile } from 'node:fs/promises';
|
|
4
|
+
import { isIP } from 'node:net';
|
|
5
|
+
const [origin, file] = process.argv.slice(2);
|
|
6
|
+
// The same transport rule as the SDK and MCP bridge: HTTPS, or plain HTTP only for loopback and
|
|
7
|
+
// private-network development addresses, so a key is never written beside a plaintext public origin.
|
|
8
|
+
function local(host) {
|
|
9
|
+
return host === 'localhost' || host === '[::1]' ||
|
|
10
|
+
(isIP(host) === 4 && /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)/.test(host));
|
|
11
|
+
}
|
|
12
|
+
const parsed = origin && URL.canParse(origin) ? new URL(origin) : null;
|
|
13
|
+
if (
|
|
14
|
+
!parsed ||
|
|
15
|
+
!file ||
|
|
16
|
+
parsed.origin !== origin ||
|
|
17
|
+
!(parsed.protocol === 'https:' || (parsed.protocol === 'http:' && local(parsed.hostname)))
|
|
18
|
+
) {
|
|
19
|
+
console.error('Usage: node key.mjs API_ORIGIN PRIVATE_ENV_FILE\nAPI_ORIGIN is a bare https:// origin (plain http only for local development).');
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
22
|
+
// The optional link carries only a digest and a requested role. The owner approves in Yasad.
|
|
23
|
+
const [approval, kind = 'assistant', name = 'My assistant', role = 'reader', type = 'Other', caller = ''] =
|
|
24
|
+
process.argv.slice(4);
|
|
25
|
+
const url = approval ? new URL(approval) : null;
|
|
26
|
+
if (url) {
|
|
27
|
+
if (
|
|
28
|
+
!['http:', 'https:'].includes(url.protocol) ||
|
|
29
|
+
url.username ||
|
|
30
|
+
url.password ||
|
|
31
|
+
!/^\/w\/[a-f0-9-]{36}\/connect$/.test(url.pathname)
|
|
32
|
+
)
|
|
33
|
+
throw Error('Use the workspace connection address supplied by the owner.');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const key = 'ysk_' + randomBytes(32).toString('hex');
|
|
37
|
+
const digest = createHash('sha256').update(key).digest('hex');
|
|
38
|
+
await writeFile(file, 'YASAD_API_URL=' + origin + '\nYASAD_API_KEY=' + key + '\n', {
|
|
39
|
+
mode: 0o600,
|
|
40
|
+
flag: 'wx',
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
if (url) {
|
|
44
|
+
url.search = '';
|
|
45
|
+
url.hash = new URLSearchParams({
|
|
46
|
+
kind,
|
|
47
|
+
name,
|
|
48
|
+
role,
|
|
49
|
+
type,
|
|
50
|
+
caller,
|
|
51
|
+
digest,
|
|
52
|
+
}).toString();
|
|
53
|
+
console.log('Give this review link to the workspace owner:\n' + url.href);
|
|
54
|
+
} else {
|
|
55
|
+
console.log('Give this key fingerprint to the workspace owner. They add it in Yasad under Settings → Add a key by hand.\n' + digest);
|
|
56
|
+
}
|
package/lib/mcp.mjs
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Local stdio MCP adapter. It only consumes the published HTTP contract.
|
|
2
|
+
// No database access, source imports, external dependencies or automatic retries.
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { isIP } from 'node:net';
|
|
6
|
+
// Kept identical to agent/data-policy.mjs (tested). This file is downloaded and run on its own.
|
|
7
|
+
export const dataPolicy =
|
|
8
|
+
'Yasad is the system of record for apps built on this workspace. Store every business record and every piece of durable app state in Yasad: native records (customers, resources, reservations, orders, payments) and custom collections for everything else, such as settings, menus, capacity, notes, statuses and outboxes. Never create or connect another database or data file: no SQLite, PostgreSQL, MySQL, MongoDB, Prisma, Drizzle, Knex, TypeORM or JSON/CSV files used as storage. Redis or a similar key-value store is optional and allowed only as a cache or for temporary coordination (rate limits, locks, short-lived sessions, job signals that carry Yasad IDs): write to Yasad first, give every key an expiry, re-read cached records from Yasad, and make sure the app still works if Redis is emptied. Never keep the only copy of a customer, order, booking, payment or other business record in Redis. If your credential cannot write, ask the owner to approve an operator credential instead of storing data elsewhere. Only secrets (in a private env file) and rebuildable caches may live outside Yasad. Run /agent/check.mjs on the project before you finish.';
|
|
9
|
+
const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
10
|
+
const readOnlyPost = new Map([
|
|
11
|
+
['availability', '/v1/availability'],
|
|
12
|
+
['getCollection', '/v1/collections/schema'],
|
|
13
|
+
['pageBusinessRecords','/v1/records/page'],
|
|
14
|
+
['queryRecords', '/v1/data/query'],
|
|
15
|
+
['summarizeRecords','/v1/data/summary'],
|
|
16
|
+
]);
|
|
17
|
+
// Keep both the published operation ID and its path pinned for a read-only POST.
|
|
18
|
+
// The standalone adapter also supplies this classification to the REST server.
|
|
19
|
+
export const isReadOperation = (method, path, id) =>
|
|
20
|
+
method === 'GET' || method === 'HEAD' ||
|
|
21
|
+
(method === 'POST' && typeof path === 'string' && readOnlyPost.get(id) === path);
|
|
22
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
23
|
+
const isObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
24
|
+
export function origin(raw) {
|
|
25
|
+
const u = new URL(raw);
|
|
26
|
+
if (u.username || u.password || u.search || u.hash || u.pathname !== '/')
|
|
27
|
+
throw new Error('Use a Yasad API origin with no path or credentials');
|
|
28
|
+
const h = u.hostname;
|
|
29
|
+
const local =
|
|
30
|
+
h === 'localhost' ||
|
|
31
|
+
h === '[::1]' ||
|
|
32
|
+
(isIP(h) === 4 &&
|
|
33
|
+
(/^127\./.test(h) ||
|
|
34
|
+
/^10\./.test(h) ||
|
|
35
|
+
/^192\.168\./.test(h) ||
|
|
36
|
+
/^172\.(1[6-9]|2[0-9]|3[01])\./.test(h)));
|
|
37
|
+
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local))
|
|
38
|
+
throw new Error('HTTPS required outside trusted local development');
|
|
39
|
+
return u.origin;
|
|
40
|
+
}
|
|
41
|
+
async function jsonLimited(response) {
|
|
42
|
+
if (!response.body) throw new Error('Empty API response');
|
|
43
|
+
const reader = response.body.getReader();
|
|
44
|
+
let size = 0;
|
|
45
|
+
const chunks = [];
|
|
46
|
+
try {
|
|
47
|
+
for (;;) {
|
|
48
|
+
const { done, value } = await reader.read();
|
|
49
|
+
if (done) break;
|
|
50
|
+
size += value.length;
|
|
51
|
+
if (size > 2_000_000) {
|
|
52
|
+
await reader.cancel();
|
|
53
|
+
throw new Error('API response exceeds local adapter limit');
|
|
54
|
+
}
|
|
55
|
+
chunks.push(Buffer.from(value));
|
|
56
|
+
}
|
|
57
|
+
} finally {
|
|
58
|
+
reader.releaseLock();
|
|
59
|
+
}
|
|
60
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
61
|
+
}
|
|
62
|
+
function toolFailure(code, message, details = {outcome: 'rejected', retryable: false, recovery: 'Review the request and current access.'}) {
|
|
63
|
+
return Object.assign(new Error(message), {safeResult: {error: code, message, ...details}});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function createBridge({ baseUrl, apiKey, allowWrites = false, fetchImpl = fetch }) {
|
|
67
|
+
if (typeof apiKey !== 'string' || !apiKey.trim()) throw new Error('YASAD_API_KEY is required');
|
|
68
|
+
const base = origin(baseUrl);
|
|
69
|
+
async function request(path, method = 'GET', body) {
|
|
70
|
+
const response = await fetchImpl(base + path, {
|
|
71
|
+
method,
|
|
72
|
+
redirect: 'error',
|
|
73
|
+
signal: AbortSignal.timeout(15000),
|
|
74
|
+
headers: {
|
|
75
|
+
authorization: 'Bearer ' + apiKey,
|
|
76
|
+
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
77
|
+
},
|
|
78
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
79
|
+
});
|
|
80
|
+
const data = await jsonLimited(response);
|
|
81
|
+
return { status: response.status, ok: response.ok, data };
|
|
82
|
+
}
|
|
83
|
+
async function discover() {
|
|
84
|
+
const unavailable = () => toolFailure('DISCOVERY_UNAVAILABLE',
|
|
85
|
+
'Yasad could not list the available tools. The requested operation did not start.',
|
|
86
|
+
{outcome: 'rejected', retryable: true, recovery: 'Retry discovery before using the tool.'});
|
|
87
|
+
let caps, contract;
|
|
88
|
+
try {
|
|
89
|
+
[caps, contract] = await Promise.all([request('/v1/capabilities'), request('/openapi.json')]);
|
|
90
|
+
} catch {
|
|
91
|
+
throw unavailable();
|
|
92
|
+
}
|
|
93
|
+
if (caps.status === 401 || caps.status === 403)
|
|
94
|
+
throw toolFailure(caps.status === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN',
|
|
95
|
+
'Workspace discovery was denied. Review this connection before trying again.');
|
|
96
|
+
if (!caps.ok || !contract.ok || !Array.isArray(caps.data?.operations)) throw unavailable();
|
|
97
|
+
const permitted = new Set(caps.data.operations);
|
|
98
|
+
const list = [];
|
|
99
|
+
const routes = new Map();
|
|
100
|
+
for (const [path, methods] of Object.entries(contract.data.paths ?? {})) {
|
|
101
|
+
if (!/^\/v1(?:\/(?:[a-z][a-z-]*|\{id\}))+$/.test(path)) continue;
|
|
102
|
+
for (const [verb, op] of Object.entries(methods)) {
|
|
103
|
+
const name = op.operationId,
|
|
104
|
+
method = verb.toUpperCase(),
|
|
105
|
+
route = [method, path];
|
|
106
|
+
if (
|
|
107
|
+
!['GET', 'POST', 'PATCH', 'DELETE'].includes(method) ||
|
|
108
|
+
typeof name !== 'string' ||
|
|
109
|
+
routes.has(name)
|
|
110
|
+
)
|
|
111
|
+
continue;
|
|
112
|
+
const read = isReadOperation(method, path, name);
|
|
113
|
+
if (!permitted.has(name) || (!allowWrites && !read)) continue;
|
|
114
|
+
|
|
115
|
+
const properties = {},
|
|
116
|
+
required = [];
|
|
117
|
+
if (path.includes('{id}')) {
|
|
118
|
+
properties.id = { type: 'string', pattern: uuid.source };
|
|
119
|
+
required.push('id');
|
|
120
|
+
}
|
|
121
|
+
const body = op.requestBody?.content?.['application/json']?.schema;
|
|
122
|
+
if (body) {
|
|
123
|
+
properties.body = body;
|
|
124
|
+
required.push('body');
|
|
125
|
+
}
|
|
126
|
+
if (method !== 'GET' && !body) continue;
|
|
127
|
+
routes.set(name, route);
|
|
128
|
+
list.push({
|
|
129
|
+
name,
|
|
130
|
+
description:
|
|
131
|
+
op.summary +
|
|
132
|
+
(read
|
|
133
|
+
? ''
|
|
134
|
+
: ' Requires an explicitly supplied stable requestId for retries. No automatic retry.'),
|
|
135
|
+
inputSchema: { type: 'object', properties, required, additionalProperties: false },
|
|
136
|
+
annotations: { readOnlyHint: read },
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return { list, routes };
|
|
141
|
+
}
|
|
142
|
+
async function call(name, args = {}) {
|
|
143
|
+
const { list: available, routes } = await discover();
|
|
144
|
+
const tool = available.find((t) => t.name === name);
|
|
145
|
+
if (!tool) throw toolFailure('OPERATION_UNAVAILABLE','This tool is outside the current connection or write configuration. Review permitted tools before requesting access.');
|
|
146
|
+
if (
|
|
147
|
+
!isObject(args) ||
|
|
148
|
+
Object.keys(args).some((k) => !Object.hasOwn(tool.inputSchema.properties, k)) ||
|
|
149
|
+
tool.inputSchema.required.some((k) => !Object.hasOwn(args, k))
|
|
150
|
+
)
|
|
151
|
+
throw toolFailure('INVALID_INPUT','Invalid tool arguments. Correct the request before submitting it.');
|
|
152
|
+
const [method, template] = routes.get(name);
|
|
153
|
+
let path = template;
|
|
154
|
+
if (template.includes('{id}')) {
|
|
155
|
+
if (typeof args.id !== 'string' || !uuid.test(args.id)) throw toolFailure('INVALID_INPUT','Invalid record UUID. Correct the request before submitting it.');
|
|
156
|
+
path = template.replace('{id}', args.id);
|
|
157
|
+
}
|
|
158
|
+
if (Object.hasOwn(args, 'body') && !isObject(args.body)) throw toolFailure('INVALID_INPUT','Expected body object. Correct the request before submitting it.');
|
|
159
|
+
const read = tool.annotations.readOnlyHint;
|
|
160
|
+
if (!read && !uuid.test(args.body?.requestId ?? ''))
|
|
161
|
+
throw toolFailure('INVALID_INPUT','Explicit lowercase UUID requestId required. Correct the request before submitting it.');
|
|
162
|
+
if (args.body && Buffer.byteLength(JSON.stringify(args.body)) > 32768)
|
|
163
|
+
throw toolFailure('INVALID_INPUT','Request body too large. Correct the request before submitting it.');
|
|
164
|
+
let result;
|
|
165
|
+
try {
|
|
166
|
+
result = await request(path, method, args.body);
|
|
167
|
+
} catch {
|
|
168
|
+
if (read) throw toolFailure('READ_UNAVAILABLE', 'The response could not be read.',
|
|
169
|
+
{outcome: 'read_failed', retryable: true, recovery: 'Try loading this information again.'});
|
|
170
|
+
throw toolFailure('OUTCOME_UNCONFIRMED', 'The outcome of this change could not be confirmed.',
|
|
171
|
+
{outcome: 'unconfirmed', retryable: false, requestId: args.body.requestId,
|
|
172
|
+
recovery: 'Check the original receipt before repeating this change. Keep the same request ID.'});
|
|
173
|
+
}
|
|
174
|
+
if (name === 'getCapabilities' && result.ok) {
|
|
175
|
+
result.data.mcpTools = available.map((t) => t.name);
|
|
176
|
+
result.data.mcpWritesEnabled = allowWrites;
|
|
177
|
+
}
|
|
178
|
+
return { content: [{ type: 'text', text: JSON.stringify(result.data) }], isError: !result.ok };
|
|
179
|
+
}
|
|
180
|
+
return { tools: async () => (await discover()).list, call };
|
|
181
|
+
}
|
|
182
|
+
export function createProtocol(bridge, {stateless = false} = {}) {
|
|
183
|
+
let initialized = stateless;
|
|
184
|
+
return async function handle(message) {
|
|
185
|
+
if (!isObject(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string')
|
|
186
|
+
return { jsonrpc: '2.0', id: message?.id ?? null, error: { code: -32600, message: 'Invalid request' } };
|
|
187
|
+
const { id, method, params } = message;
|
|
188
|
+
if (!Object.hasOwn(message, 'id')) return undefined;
|
|
189
|
+
const success = (result) => ({ jsonrpc: '2.0', id, result });
|
|
190
|
+
const error = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
|
|
191
|
+
if (method === 'initialize') {
|
|
192
|
+
initialized = true;
|
|
193
|
+
const requested = params?.protocolVersion;
|
|
194
|
+
return success({
|
|
195
|
+
protocolVersion: versions.includes(requested) ? requested : versions[0],
|
|
196
|
+
capabilities: { tools: {}, resources: {} },
|
|
197
|
+
serverInfo: { name: stateless ? 'yasad-http' : 'fresh-infra-local', version: '0.1.0' },
|
|
198
|
+
instructions:
|
|
199
|
+
dataPolicy +
|
|
200
|
+
' Read yasad://workspace/context or call getCapabilities to check your workspace, grant and guide links. tools/list reflects your key and local write setting. Persist a requestId before every mutation. Replay the original body and ID after an uncertain outcome.',
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
if (method === 'ping') return success({});
|
|
204
|
+
if (!initialized) return error(-32002, 'Initialize first');
|
|
205
|
+
try {
|
|
206
|
+
if (method === 'resources/list' || method === 'resources/read') {
|
|
207
|
+
const available = await bridge.tools();
|
|
208
|
+
const resources = [
|
|
209
|
+
{uri:'yasad://workspace/context',name:'Workspace and permissions',operation:'getCapabilities'},
|
|
210
|
+
{uri:'yasad://workspace/collections',name:'Business record collections',operation:'listCollections'},
|
|
211
|
+
].filter(r=>available.some(t=>t.name===r.operation));
|
|
212
|
+
if (method==='resources/list') return success({resources:resources.map(({uri,name})=>({uri,name,mimeType:'application/json'}))});
|
|
213
|
+
const entry=resources.find(r=>r.uri===params?.uri);
|
|
214
|
+
if (!entry) return error(-32602,'Resource unavailable for this caller');
|
|
215
|
+
const response=await bridge.call(entry.operation,{});
|
|
216
|
+
if (response.isError) return error(-32002,'Workspace unavailable for this caller');
|
|
217
|
+
return success({contents:[{uri:entry.uri,mimeType:'application/json',text:response.content[0].text}]});
|
|
218
|
+
}
|
|
219
|
+
if (method === 'tools/list') return success({ tools: await bridge.tools() });
|
|
220
|
+
if (method === 'tools/call') {
|
|
221
|
+
try {
|
|
222
|
+
return success(await bridge.call(params?.name, params?.arguments ?? {}));
|
|
223
|
+
} catch (error) {
|
|
224
|
+
const result = error.safeResult ?? {error: 'OUTCOME_UNCONFIRMED',
|
|
225
|
+
message: 'Yasad could not confirm the tool response.', outcome: 'unconfirmed', retryable: false,
|
|
226
|
+
recovery: 'Check the original receipt before repeating any change. Keep the same request ID.'};
|
|
227
|
+
return success({isError:true,content:[{type:'text',text:JSON.stringify(result)}]});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return error(-32601, 'Method not found');
|
|
231
|
+
} catch {
|
|
232
|
+
return error(-32000, 'Fresh API unavailable or discovery failed');
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
class CredentialPairError extends Error {}
|
|
237
|
+
|
|
238
|
+
export function standaloneBridge(env, fetchImpl = fetch) {
|
|
239
|
+
const family = env.YASAD_API_KEY !== undefined ? 'YASAD' : 'FRESH';
|
|
240
|
+
const apiKey = env[family + '_API_KEY'];
|
|
241
|
+
const baseUrl = env[family + '_API_URL'];
|
|
242
|
+
if (!apiKey?.trim() || !baseUrl?.trim())
|
|
243
|
+
throw new CredentialPairError('Set ' + family + '_API_KEY and ' + family + '_API_URL together before starting MCP.');
|
|
244
|
+
return createBridge({ baseUrl, apiKey, allowWrites: env[family + '_MCP_ALLOW_WRITES'] === '1', fetchImpl });
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (!process.env.YASAD_BUNDLED && process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
248
|
+
try {
|
|
249
|
+
const bridge = standaloneBridge(process.env);
|
|
250
|
+
const handle = createProtocol(bridge);
|
|
251
|
+
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
252
|
+
for await (const line of input) {
|
|
253
|
+
if (!line.trim()) continue;
|
|
254
|
+
let response;
|
|
255
|
+
try {
|
|
256
|
+
if (Buffer.byteLength(line) > 65536) throw new Error('oversized');
|
|
257
|
+
response = await handle(JSON.parse(line));
|
|
258
|
+
} catch {
|
|
259
|
+
response = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid JSON message' } };
|
|
260
|
+
}
|
|
261
|
+
if (response) process.stdout.write(JSON.stringify(response) + '\n');
|
|
262
|
+
}
|
|
263
|
+
} catch (error) {
|
|
264
|
+
const message = error instanceof CredentialPairError
|
|
265
|
+
? error.message
|
|
266
|
+
: 'Fresh MCP startup failed; check server environment.';
|
|
267
|
+
process.stderr.write(message + '\n');
|
|
268
|
+
process.exitCode = 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yasad/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Yasad command line for AI assistants: make an assistant key, connect over MCP, check a key (doctor) and lint an app.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"yasadInfra": {
|
|
8
|
+
"layer": "integration",
|
|
9
|
+
"provides": "cli"
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=24"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"yasad",
|
|
16
|
+
"cli",
|
|
17
|
+
"mcp"
|
|
18
|
+
],
|
|
19
|
+
"bin": {
|
|
20
|
+
"yasad": "bin/yasad.mjs"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"bin",
|
|
24
|
+
"lib",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "node --check bin/yasad.mjs && node --check lib/mcp.mjs && node --check lib/key.mjs && node --check lib/check.mjs"
|
|
29
|
+
},
|
|
30
|
+
"sideEffects": true,
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
}
|
|
34
|
+
}
|