@sudosapient/client 0.0.0-stage → 0.2.0
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 +47 -2
- package/config.js +49 -0
- package/index.js +128 -0
- package/package.json +26 -3
package/README.md
CHANGED
|
@@ -1,3 +1,48 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sudosapient/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The small fetch client that [`@sudosapient/cli`](../cli) and [`@sudosapient/mcp`](../mcp) use to talk
|
|
4
|
+
to a Sudo Sapient workspace's public API (`/api/v1`), plus the config file they share. It has no
|
|
5
|
+
dependencies and runs on any `fetch` (Node 22 or later). It is a library, not a command; you get it
|
|
6
|
+
with the CLI or the MCP server, or on its own:
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @sudosapient/client
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
import { createClient, ApiError } from '@sudosapient/client';
|
|
14
|
+
|
|
15
|
+
const api = createClient({ url: 'https://sudo.example.com', key: process.env.SUDO_API_KEY, client: 'My script' });
|
|
16
|
+
try {
|
|
17
|
+
const me = await api.get('/me');
|
|
18
|
+
const mine = await api.all('/tasks', { assignee: 'me', status: 'open' });
|
|
19
|
+
await api.post('/tasks', { project: 'WEB', title: 'Fix login bug' });
|
|
20
|
+
await api.upload('/files', { task: 'WEB-212', name: 'trace.txt' }, new TextEncoder().encode('…'), 'text/plain');
|
|
21
|
+
} catch (e) {
|
|
22
|
+
if (e instanceof ApiError) console.error(e.status, e.code, e.message);
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- `createClient({ url, key, client, fetch, retry, onRetry })`: `get`, `post`, `patch`, `put`, `del`,
|
|
27
|
+
`request`, `all` (every page of a list endpoint), `upload(path, query, bytes, type)` (raw bytes as
|
|
28
|
+
the body, for `POST /files`) and `download(path)` (`{ bytes, type, name }`). `client` labels your changes in Activity ("Ada via My
|
|
29
|
+
script"). Errors are `ApiError` with `status`, `code` and `field` (and `retryAfter`, in seconds, on
|
|
30
|
+
a `429`).
|
|
31
|
+
- Rate limits are waited out: a `429` with `Retry-After` is sent again after that many seconds, up
|
|
32
|
+
to `retry.retries` times (default 3), as long as each wait is at most `retry.maxDelay` ms (default
|
|
33
|
+
60 000) and the waits for one request add up to at most `retry.maxTotal` ms (default 120 000);
|
|
34
|
+
otherwise the `429` is thrown straight away. A `Retry-After` of 0 still waits a second. The server refuses such a request before handling
|
|
35
|
+
it, so this is safe for writes too. `onRetry({ attempt, delay, method, path })` is called before
|
|
36
|
+
each wait; `retry: { retries: 0 }` turns it off.
|
|
37
|
+
- `plainHttpRemote(url)`: true when the URL would send the key unencrypted to another machine.
|
|
38
|
+
- `@sudosapient/client/config`: `loadConfig`, `saveConfig`, `clearConfig` and `configPath` for
|
|
39
|
+
`$XDG_CONFIG_HOME/sudo-sapient/config.json`, the file `sudo-cli login` writes (readable only by
|
|
40
|
+
you; `SUDO_URL` and `SUDO_API_KEY` override it).
|
|
41
|
+
|
|
42
|
+
Endpoints, fields and errors are in the workspace's API reference (`/api/docs`) and in
|
|
43
|
+
[docs/api.md](../../docs/api.md).
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
UNLICENSED, all rights reserved. The package is public on npm so anyone can install and use it, but
|
|
48
|
+
no license to copy, modify or redistribute the code is granted.
|
package/config.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/* Where the CLI keeps the workspace URL and API key, shared with the MCP server:
|
|
2
|
+
$XDG_CONFIG_HOME/sudo-sapient/config.json (default ~/.config), readable only by its owner.
|
|
3
|
+
SUDO_URL and SUDO_API_KEY override it. `insecure`: the person allowed plain http to the saved URL
|
|
4
|
+
(`login --insecure`); it doesn't carry over to a SUDO_URL. */
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
export const configPath = (env = process.env) => path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'sudo-sapient', 'config.json');
|
|
11
|
+
|
|
12
|
+
export function loadConfig(env = process.env) {
|
|
13
|
+
let file = {};
|
|
14
|
+
try {
|
|
15
|
+
file = JSON.parse(fs.readFileSync(configPath(env), 'utf8'));
|
|
16
|
+
} catch {
|
|
17
|
+
/* not logged in yet */
|
|
18
|
+
}
|
|
19
|
+
return { url: env.SUDO_URL || file.url || '', key: env.SUDO_API_KEY || file.key || '', insecure: !env.SUDO_URL && !!file.insecure };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/* The key is never readable by anyone else, not even for a moment: the directory is made (or made
|
|
23
|
+
again) owner-only, and the file is written to a new temporary file created 0600, then renamed over
|
|
24
|
+
the old one, so it is never a file that had wider permissions, and a crash can't leave half of it. */
|
|
25
|
+
export function saveConfig(cfg, env = process.env) {
|
|
26
|
+
const file = configPath(env);
|
|
27
|
+
const dir = path.dirname(file);
|
|
28
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
29
|
+
fs.chmodSync(dir, 0o700);
|
|
30
|
+
const tmp = path.join(dir, `.config.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
|
|
31
|
+
const fd = fs.openSync(tmp, 'wx', 0o600);
|
|
32
|
+
try {
|
|
33
|
+
fs.writeFileSync(fd, JSON.stringify(cfg, null, 2) + '\n');
|
|
34
|
+
fs.fsyncSync(fd);
|
|
35
|
+
} finally {
|
|
36
|
+
fs.closeSync(fd);
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
fs.renameSync(tmp, file);
|
|
40
|
+
} catch (e) {
|
|
41
|
+
fs.rmSync(tmp, { force: true });
|
|
42
|
+
throw e;
|
|
43
|
+
}
|
|
44
|
+
return file;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function clearConfig(env = process.env) {
|
|
48
|
+
fs.rmSync(configPath(env), { force: true });
|
|
49
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/* A minimal client for the Sudo Sapient public API (/api/v1), shared by the CLI and the MCP server.
|
|
2
|
+
No dependencies: it runs on any fetch (Node 22+, or an in-process `app.request`). */
|
|
3
|
+
|
|
4
|
+
export class ApiError extends Error {
|
|
5
|
+
constructor(status, body, retryAfter = null) {
|
|
6
|
+
super(body?.error || (status ? `Request failed (${status})` : 'Couldn’t reach Sudo Sapient. Check the URL and your connection.'));
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.code = body?.code || (status ? 'http_' + status : 'offline');
|
|
9
|
+
this.field = body?.field || null;
|
|
10
|
+
this.retryAfter = retryAfter;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/* Rate limits (429). The API refuses a request over the limit before handling it (middleware.js
|
|
15
|
+
`bearer`), so nothing of it was applied and retrying is safe for every method, writes included.
|
|
16
|
+
The client waits as long as Retry-After says (at least a second), up to `retries` times, never
|
|
17
|
+
longer than `maxDelay` at once nor `maxTotal` in all for one request: a wait past either is
|
|
18
|
+
reported instead (an ApiError with `retryAfter`, in seconds). A 429 without Retry-After (e.g.
|
|
19
|
+
"too many invites this hour") isn't retried. */
|
|
20
|
+
export const RETRY = { retries: 3, maxDelay: 60_000, maxTotal: 120_000 };
|
|
21
|
+
const MIN_WAIT = 1000;
|
|
22
|
+
|
|
23
|
+
/* Milliseconds to wait from a Retry-After header (seconds, or an HTTP date), or null. */
|
|
24
|
+
export function retryAfterMs(value, now = Date.now()) {
|
|
25
|
+
const v = String(value ?? '').trim();
|
|
26
|
+
if (!v) return null;
|
|
27
|
+
if (/^\d+$/.test(v)) return Number(v) * 1000;
|
|
28
|
+
const at = Date.parse(v);
|
|
29
|
+
return Number.isFinite(at) ? Math.max(0, at - now) : null;
|
|
30
|
+
}
|
|
31
|
+
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
32
|
+
|
|
33
|
+
/* `url`: the workspace's base URL (https://sudo.example.com). `client`: a label for activity, e.g.
|
|
34
|
+
"CLI" or "Claude", shown as "Ada via Claude". `retry`: { retries, maxDelay, maxTotal } for rate limits (see
|
|
35
|
+
RETRY; `{ retries: 0 }` turns retrying off). `onRetry({ attempt, delay, method, path })` is called
|
|
36
|
+
before each wait, e.g. to tell someone at a terminal why it paused. */
|
|
37
|
+
export function createClient({ url, key, client = 'API', fetch: doFetch = globalThis.fetch, retry = {}, onRetry, sleep = wait }) {
|
|
38
|
+
const base = String(url || '').replace(/\/+$/, '') + '/api/v1';
|
|
39
|
+
const { retries, maxDelay, maxTotal } = { ...RETRY, ...retry };
|
|
40
|
+
/* `raw`: { body, type } sent as is instead of JSON (a file upload). `binary`: answer with the bytes
|
|
41
|
+
({ bytes, type, name }) instead of parsed JSON (a file download). */
|
|
42
|
+
async function request(method, path, { query, body, idempotencyKey, raw, binary = false } = {}) {
|
|
43
|
+
const qs = query ? new URLSearchParams(Object.entries(query).filter(([, v]) => v != null && v !== '')).toString() : '';
|
|
44
|
+
const init = {
|
|
45
|
+
method,
|
|
46
|
+
headers: {
|
|
47
|
+
authorization: `Bearer ${key}`,
|
|
48
|
+
// URI-encoded: header values must be Latin-1, and client names needn't be.
|
|
49
|
+
'x-sudo-client': encodeURIComponent(client),
|
|
50
|
+
accept: 'application/json',
|
|
51
|
+
...(raw ? { 'content-type': raw.type || 'application/octet-stream' } : body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
52
|
+
...(idempotencyKey ? { 'idempotency-key': idempotencyKey } : {}),
|
|
53
|
+
},
|
|
54
|
+
body: raw ? raw.body : body !== undefined ? JSON.stringify(body) : undefined,
|
|
55
|
+
};
|
|
56
|
+
let waited = 0;
|
|
57
|
+
for (let attempt = 1; ; attempt++) {
|
|
58
|
+
let res;
|
|
59
|
+
try {
|
|
60
|
+
res = await doFetch(base + path + (qs ? `?${qs}` : ''), init);
|
|
61
|
+
} catch {
|
|
62
|
+
throw new ApiError(0, null);
|
|
63
|
+
}
|
|
64
|
+
if (res.ok && binary) return { bytes: new Uint8Array(await res.arrayBuffer()), type: res.headers.get('content-type') || '', name: fileName(res) };
|
|
65
|
+
const data = (res.headers.get('content-type') || '').includes('json') ? await res.json().catch(() => null) : null;
|
|
66
|
+
if (res.ok) return data;
|
|
67
|
+
const header = res.status === 429 ? retryAfterMs(res.headers.get('retry-after')) : null;
|
|
68
|
+
// "Retry-After: 0" still waits a moment, so a client can't spin against the limit.
|
|
69
|
+
const after = header == null ? null : Math.max(header, MIN_WAIT);
|
|
70
|
+
if (after == null || after > maxDelay || waited + after > maxTotal || attempt > retries)
|
|
71
|
+
throw new ApiError(res.status, data, header == null ? null : Math.ceil(header / 1000));
|
|
72
|
+
// A little jitter, so clients that were refused together don't all come back in the same instant.
|
|
73
|
+
const delay = after + Math.floor(Math.random() * 250);
|
|
74
|
+
waited += delay;
|
|
75
|
+
onRetry?.({ attempt, delay, method, path });
|
|
76
|
+
await sleep(delay);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
request,
|
|
81
|
+
get: (path, query) => request('GET', path, { query }),
|
|
82
|
+
post: (path, body = {}, opts) => request('POST', path, { body, ...opts }),
|
|
83
|
+
patch: (path, body, opts) => request('PATCH', path, { body, ...opts }),
|
|
84
|
+
put: (path, body = {}, opts) => request('PUT', path, { body, ...opts }),
|
|
85
|
+
del: (path, opts) => request('DELETE', path, opts),
|
|
86
|
+
/* POST raw bytes, e.g. upload('/files', { project: 'WEB', name: 'spec.pdf' }, bytes, 'application/pdf'). */
|
|
87
|
+
upload: (path, query, bytes, type, opts) => request('POST', path, { query, raw: { body: bytes, type }, ...opts }),
|
|
88
|
+
/* GET bytes: { bytes, type, name }. */
|
|
89
|
+
download: (path, query) => request('GET', path, { query, binary: true }),
|
|
90
|
+
/* Every page of a list endpoint, up to `max` items. */
|
|
91
|
+
async all(path, query = {}, max = 500) {
|
|
92
|
+
const out = [];
|
|
93
|
+
let cursor;
|
|
94
|
+
do {
|
|
95
|
+
const page = await request('GET', path, { query: { ...query, limit: 100, cursor } });
|
|
96
|
+
out.push(...page.data);
|
|
97
|
+
cursor = page.nextCursor;
|
|
98
|
+
} while (cursor && out.length < max);
|
|
99
|
+
return out.slice(0, max);
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/* The file name a download was sent with (Content-Disposition: filename*=UTF-8''…). */
|
|
105
|
+
function fileName(res) {
|
|
106
|
+
const m = /filename\*=UTF-8''([^;]+)/i.exec(res.headers.get('content-disposition') || '');
|
|
107
|
+
try {
|
|
108
|
+
return m ? decodeURIComponent(m[1]) : null;
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/* Path segment for a task or project reference (an id or key). */
|
|
115
|
+
export const seg = ref => encodeURIComponent(String(ref).trim());
|
|
116
|
+
|
|
117
|
+
/* True when `url` would send the key in the clear to another machine: plain http to anything but
|
|
118
|
+
this one (localhost, 127.x, ::1). */
|
|
119
|
+
export function plainHttpRemote(url) {
|
|
120
|
+
let u;
|
|
121
|
+
try {
|
|
122
|
+
u = new URL(url);
|
|
123
|
+
} catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
const host = u.hostname.replace(/^\[|\]$/g, '');
|
|
127
|
+
return u.protocol === 'http:' && !(host === 'localhost' || host.endsWith('.localhost') || host === '::1' || /^127\./.test(host));
|
|
128
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sudosapient/client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Minimal fetch client for the Sudo Sapient public API (/api/v1), plus the shared CLI/MCP config.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/sudosapient-labs/project-tracker.git",
|
|
8
|
+
"directory": "packages/client"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/sudosapient-labs/project-tracker/tree/prod/packages/client#readme",
|
|
11
|
+
"bugs": "https://github.com/sudosapient-labs/project-tracker/issues",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": "./index.js",
|
|
15
|
+
"./config": "./config.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"index.js",
|
|
19
|
+
"config.js",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=22"
|
|
24
|
+
},
|
|
25
|
+
"license": "UNLICENSED",
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
}
|
|
6
29
|
}
|