@cmdop/sdk 1.1.0 → 3.0.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/LICENSE +21 -0
- package/README.md +14 -149
- package/dist/carriers/carrier.d.ts +40 -0
- package/dist/carriers/carrier.js +16 -0
- package/dist/carriers/http.d.ts +15 -0
- package/dist/carriers/http.js +114 -0
- package/dist/carriers/memory.d.ts +11 -0
- package/dist/carriers/memory.js +35 -0
- package/dist/carriers/ndjson.d.ts +16 -0
- package/dist/carriers/ndjson.js +31 -0
- package/dist/client.d.ts +113 -0
- package/dist/client.js +220 -0
- package/dist/generated/call.gen.d.ts +78 -0
- package/dist/generated/call.gen.js +5 -0
- package/dist/generated/tools.gen.d.ts +1046 -0
- package/dist/generated/tools.gen.js +34 -0
- package/dist/index.d.ts +8 -4245
- package/dist/index.js +8 -1113
- package/dist/screen.d.ts +19 -0
- package/dist/screen.js +16 -0
- package/dist/vendor.d.ts +52 -0
- package/dist/vendor.js +291 -0
- package/package.json +11 -42
- package/bin/cmdop-core-darwin-arm64 +0 -0
- package/bin/cmdop-core-darwin-x64 +0 -0
- package/bin/cmdop-core-linux-arm64 +0 -0
- package/bin/cmdop-core-linux-x64 +0 -0
- package/bin/cmdop-core-win32-x64.exe +0 -0
- package/dist/chunk-HVTWZ3OM.js +0 -63
- package/dist/chunk-HVTWZ3OM.js.map +0 -1
- package/dist/errors-4ITNIIVL.js +0 -3
- package/dist/errors-4ITNIIVL.js.map +0 -1
- package/dist/index.cjs +0 -1218
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -4245
- package/dist/index.js.map +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-2026 CMDOP
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,160 +1,25 @@
|
|
|
1
|
-
# @cmdop/sdk
|
|
1
|
+
# @cmdop/sdk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
Typed Node SDK for CMDOP — manage your machines, fleets, tunnels, and schedules,
|
|
6
|
-
stream a machine's AI agent, and drive the skills marketplace, all from typed
|
|
7
|
-
TypeScript.
|
|
8
|
-
|
|
9
|
-
📚 **Docs: [docs.cmdop.com](https://docs.cmdop.com)** · [SDK](https://cmdop.com/sdk) ·
|
|
10
|
-
[Bots](https://cmdop.com/bots) · [Connect](https://cmdop.com/connect)
|
|
11
|
-
|
|
12
|
-

|
|
13
|
-
|
|
14
|
-
- **One install, zero dependencies** — `npm i @cmdop/sdk` is everything. No
|
|
15
|
-
native build step, no `optionalDependencies`, nothing fetched on first run.
|
|
16
|
-
- **Works anywhere, offline-ready** — a single self-contained package runs the
|
|
17
|
-
same on macOS, Linux, and Windows, including air-gapped hosts.
|
|
18
|
-
- **Typed end to end** — full TypeScript types for every resource and response,
|
|
19
|
-
with one clean async streaming API for live agent output.
|
|
20
|
-
|
|
21
|
-
## Install
|
|
3
|
+
Your machines' tools from a program: the same tools agents use through MCP, typed.
|
|
22
4
|
|
|
23
5
|
```bash
|
|
24
|
-
npm
|
|
6
|
+
npm install @cmdop/sdk
|
|
25
7
|
```
|
|
26
8
|
|
|
27
|
-
ESM + CJS, Node ≥ 18.
|
|
28
|
-
|
|
29
|
-
## Quick start
|
|
30
|
-
|
|
31
9
|
```ts
|
|
32
|
-
import {
|
|
33
|
-
|
|
34
|
-
const c = new Client({ token: "..." }); // or Client.fromEnv()
|
|
10
|
+
import { connect } from "@cmdop/sdk";
|
|
35
11
|
|
|
36
|
-
const
|
|
37
|
-
|
|
12
|
+
const cmdop = connect(); // CMDOP_TOKEN, CMDOP_URL
|
|
13
|
+
const box = cmdop.machine("box");
|
|
14
|
+
console.log((await box.run("uptime")).stdout);
|
|
38
15
|
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
await c.close(); // release resources
|
|
16
|
+
const run = box.stream("make test");
|
|
17
|
+
for await (const piece of run) process.stdout.write(piece.data);
|
|
18
|
+
console.log((await run.result).exit_code);
|
|
43
19
|
```
|
|
44
20
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
The same surface as the relay, mirrored exactly by the Python SDK (camelCase
|
|
50
|
-
here, snake_case there):
|
|
51
|
-
|
|
52
|
-
| Namespace | Methods |
|
|
53
|
-
|---|---|
|
|
54
|
-
| `machines` | `list · get · update · disable · info · spend · ask · messages · clearMessages · activeSession` |
|
|
55
|
-
| `fleets` | `list · get · create · update · disable` |
|
|
56
|
-
| `fleets.members` | `list · add · setRole · remove` |
|
|
57
|
-
| `fleets.machines` | `list · attach · detach` |
|
|
58
|
-
| `tunnels` | `open · close · list · get · sessions` |
|
|
59
|
-
| `schedules` | `list · get · create · update · delete · trigger · runs` |
|
|
60
|
-
| `keys` | `list · issue · revoke` |
|
|
61
|
-
| `skills` | `list · get · my · install · star · versions · reviews · create · update · delete · publish · publishStatus · categories · tags` |
|
|
62
|
-
|
|
63
|
-
List endpoints also expose `iter(...)` (an async generator over every item,
|
|
64
|
-
following cursors) and `pages(...)` (an async generator over each page).
|
|
65
|
-
|
|
66
|
-
> **Two planes, one client.** `machines / fleets / tunnels / schedules / keys`
|
|
67
|
-
> use your relay token (`CMDOP_TOKEN`); the **`skills`** marketplace uses your
|
|
68
|
-
> platform API key (`CMDOP_API_KEY`). Set whichever you need — the client routes
|
|
69
|
-
> each call to the right plane for you.
|
|
70
|
-
|
|
71
|
-
## Streaming: `machines.ask()`
|
|
72
|
-
|
|
73
|
-
`ask()` returns an `AskStream` — an async iterable of typed frames with `pin()` /
|
|
74
|
-
`confirm()` / `collect()`:
|
|
75
|
-
|
|
76
|
-
```ts
|
|
77
|
-
const stream = c.machines.ask(machineId, "df -h", { sessionId: "s1" });
|
|
78
|
-
for await (const frame of stream) {
|
|
79
|
-
if (frame.type === "event") {
|
|
80
|
-
process.stdout.write(String((frame.payload as { delta?: string })?.delta ?? ""));
|
|
81
|
-
} else if (frame.type === "pin_required") { // machine asked for its connect PIN
|
|
82
|
-
await stream.pin(frame.challengeId, "1234");
|
|
83
|
-
} else if (frame.type === "confirm_required") { // a dangerous plan awaits approval
|
|
84
|
-
await stream.confirm(frame.token, true);
|
|
85
|
-
} else if (frame.type === "pin_denied") {
|
|
86
|
-
console.log("PIN rejected:", frame.reason);
|
|
87
|
-
} else if (frame.type === "done") {
|
|
88
|
-
console.log("\n->", frame.text);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// one-shot: drain to the final text
|
|
93
|
-
const text = await c.machines.ask(machineId, "uptime").collect();
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
**Connection PIN.** If a machine requires a PIN, pass it **upfront** — the SDK is
|
|
97
|
-
headless, so there's no prompt to answer:
|
|
98
|
-
|
|
99
|
-
```ts
|
|
100
|
-
const text = await c.machines.ask(machineId, "uptime", { pin: "1234" }).collect();
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
A wrong PIN throws `PinDeniedError`; an unverified one throws `PinTimeoutError`
|
|
104
|
-
(both extend `PermissionError`, non-retryable). The reactive `stream.pin(...)`
|
|
105
|
-
callback above is for interactive use (a human at a prompt). The relay never
|
|
106
|
-
stores the PIN — it forwards it once to the target, which verifies it locally.
|
|
107
|
-
|
|
108
|
-
Frame types: `event · done · error · confirm_required · pin_required ·
|
|
109
|
-
pin_denied`. An `error` outcome throws `AgentStreamError`.
|
|
110
|
-
|
|
111
|
-
## Environment variables
|
|
112
|
-
|
|
113
|
-
| Var | Meaning | Default |
|
|
114
|
-
|---|---|---|
|
|
115
|
-
| `CMDOP_TOKEN` | relay Bearer token (machines/fleets/…) | — (required for relay ops) |
|
|
116
|
-
| `CMDOP_BASE_URL` | relay REST root | `https://cloud.cmdop.com` |
|
|
117
|
-
| `CMDOP_API_KEY` | platform `UserAPIKey` (for `skills`) | — (required for skills) |
|
|
118
|
-
| `CMDOP_API_BASE_URL` | platform REST root | `https://api.cmdop.com` |
|
|
119
|
-
| `CMDOP_FLEET_ID` | default fleet for fleet-scoped ops | none |
|
|
120
|
-
| `CMDOP_TIMEOUT_MS` | per-call timeout | `30000` |
|
|
121
|
-
|
|
122
|
-
Precedence is always explicit option > env var > default. Pass a string to the
|
|
123
|
-
constructor (`new Client("token")`) as a shorthand for `{ token }`.
|
|
124
|
-
|
|
125
|
-
## Error handling
|
|
126
|
-
|
|
127
|
-
Every failure surfaces as a typed error carrying a stable `code` (all extend
|
|
128
|
-
`CmdopError`):
|
|
129
|
-
|
|
130
|
-
```ts
|
|
131
|
-
import {
|
|
132
|
-
AuthError, PermissionError, NotFoundError, ConflictError,
|
|
133
|
-
ValidationError, RateLimitError, ServerError, ConnectionError,
|
|
134
|
-
TimeoutError, UnavailableError, AgentStreamError, CmdopError,
|
|
135
|
-
} from "@cmdop/sdk";
|
|
136
|
-
|
|
137
|
-
try {
|
|
138
|
-
await c.machines.get("missing-id");
|
|
139
|
-
} catch (e) {
|
|
140
|
-
if (e instanceof NotFoundError) { /* ... */ }
|
|
141
|
-
else if (e instanceof CmdopError) {
|
|
142
|
-
if (e.retryable) { /* true on TimeoutError — safe to retry */ }
|
|
143
|
-
console.log(e.code, e.message);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
`ConnectionError` covers a lost connection mid-call (pending promises reject);
|
|
149
|
-
`TimeoutError` (a retryable subclass) is a deadline/handshake timeout;
|
|
150
|
-
`UnavailableError` means the relay is up but the target agent/machine is offline.
|
|
151
|
-
`AgentStreamError` is the streaming-`ask` error outcome.
|
|
152
|
-
|
|
153
|
-
## Links
|
|
21
|
+
Every tool is a typed method on a machine (`box.fs_read({ path })`, `box.task_start({ command })`, …), and
|
|
22
|
+
`cmdop.call(tool, args, { machine })` reaches any of them by name. A refused call throws `CmdopError` with its
|
|
23
|
+
`code`; `deadline` and `signal` bound and cancel any call.
|
|
154
24
|
|
|
155
|
-
|
|
156
|
-
- **SDK** → [cmdop.com/sdk](https://cmdop.com/sdk) · **Bots** →
|
|
157
|
-
[cmdop.com/bots](https://cmdop.com/bots) · **Connect** →
|
|
158
|
-
[cmdop.com/connect](https://cmdop.com/connect)
|
|
159
|
-
- [`@cmdop/sdk` on npm](https://www.npmjs.com/package/@cmdop/sdk) ·
|
|
160
|
-
[source](https://github.com/commandoperator/cmdop-sdk)
|
|
25
|
+
Docs: https://docs.cmdop.ai · License: MIT
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client-door seam (developer SDK plan, section 4): the one interface between the client and a channel. The client
|
|
3
|
+
* knows the call contract (`generated/call.gen.ts`) and nothing about the channel; an adapter moves the contract's
|
|
4
|
+
* shapes and nothing else. A carrier defines no semantics: codes, deadlines, cancel and the order of pieces come from
|
|
5
|
+
* the contract, and the shared vectors (`exports/sdk/vectors/carrier`) hold every adapter to it.
|
|
6
|
+
*/
|
|
7
|
+
import type { Answer, CallRequest, StreamLine } from "../generated/call.gen.ts";
|
|
8
|
+
export interface CallOptions {
|
|
9
|
+
/** Aborting it cancels the call: the adapter tells the door, the door tells the machine. */
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
/** One machine as the server lists it. Only the fields the client reads. */
|
|
13
|
+
export interface MachineRow {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
online: boolean;
|
|
17
|
+
os?: string;
|
|
18
|
+
last_seen?: number | null;
|
|
19
|
+
/** The machine's box key and its signature by the machine's id, for end-to-end calls. */
|
|
20
|
+
box_key?: string | null;
|
|
21
|
+
box_sig?: string | null;
|
|
22
|
+
tools?: string[];
|
|
23
|
+
}
|
|
24
|
+
export interface Carrier {
|
|
25
|
+
/** `"http"`, `"memory"`; later `"ws"`, `"grpc"`. */
|
|
26
|
+
readonly name: string;
|
|
27
|
+
/** One call, answered once. A refusal is an `Answer` with `error`, never a throw. */
|
|
28
|
+
call(req: CallRequest, o: CallOptions): Promise<Answer>;
|
|
29
|
+
/** One call, its pieces as they come, its answer as the last line. */
|
|
30
|
+
stream(req: CallRequest, o: CallOptions): AsyncIterable<StreamLine>;
|
|
31
|
+
/** The machines of the contour, a server-answered operation: `ok` is a `MachineRow[]`. */
|
|
32
|
+
machines(o: CallOptions): Promise<Answer>;
|
|
33
|
+
close(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
/** A carrier could not reach the door or read what came back: not a contract answer. */
|
|
36
|
+
export declare class CarrierError extends Error {
|
|
37
|
+
/** Written without parameter properties, so Node can run the sources with its own type stripping. */
|
|
38
|
+
readonly carrier: string;
|
|
39
|
+
constructor(carrier: string, message: string);
|
|
40
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client-door seam (developer SDK plan, section 4): the one interface between the client and a channel. The client
|
|
3
|
+
* knows the call contract (`generated/call.gen.ts`) and nothing about the channel; an adapter moves the contract's
|
|
4
|
+
* shapes and nothing else. A carrier defines no semantics: codes, deadlines, cancel and the order of pieces come from
|
|
5
|
+
* the contract, and the shared vectors (`exports/sdk/vectors/carrier`) hold every adapter to it.
|
|
6
|
+
*/
|
|
7
|
+
/** A carrier could not reach the door or read what came back: not a contract answer. */
|
|
8
|
+
export class CarrierError extends Error {
|
|
9
|
+
/** Written without parameter properties, so Node can run the sources with its own type stripping. */
|
|
10
|
+
carrier;
|
|
11
|
+
constructor(carrier, message) {
|
|
12
|
+
super(`${carrier}: ${message}`);
|
|
13
|
+
this.name = "CarrierError";
|
|
14
|
+
this.carrier = carrier;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP + NDJSON, the first carrier: `POST /api/v1/call`, `POST /api/v1/call/stream` (one JSON value per line, the
|
|
3
|
+
* answer last) and `GET /api/v1/machines` on the contour's address. Every answer of these routes is shaped like the
|
|
4
|
+
* contract's `Answer`, refusals included, so the HTTP status is never needed to read one. Cancel is closing the
|
|
5
|
+
* request: the server sends the machine the contract's cancel. `gen.ts` checks these paths against `openapi.json`.
|
|
6
|
+
*/
|
|
7
|
+
import { type Carrier } from "./carrier.ts";
|
|
8
|
+
export interface HttpOptions {
|
|
9
|
+
/** The contour's base URL, `https://<address>.cmdop.dev`, or a local server's. */
|
|
10
|
+
url: string;
|
|
11
|
+
token: string;
|
|
12
|
+
/** For tests and other runtimes; the global `fetch` by default. */
|
|
13
|
+
fetch?: typeof fetch;
|
|
14
|
+
}
|
|
15
|
+
export declare function httpCarrier(opts: HttpOptions): Carrier;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP + NDJSON, the first carrier: `POST /api/v1/call`, `POST /api/v1/call/stream` (one JSON value per line, the
|
|
3
|
+
* answer last) and `GET /api/v1/machines` on the contour's address. Every answer of these routes is shaped like the
|
|
4
|
+
* contract's `Answer`, refusals included, so the HTTP status is never needed to read one. Cancel is closing the
|
|
5
|
+
* request: the server sends the machine the contract's cancel. `gen.ts` checks these paths against `openapi.json`.
|
|
6
|
+
*/
|
|
7
|
+
import { CarrierError } from "./carrier.js";
|
|
8
|
+
import { readNdjson } from "./ndjson.js";
|
|
9
|
+
function isAnswer(v) {
|
|
10
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && ("ok" in v || "error" in v || "sealed" in v);
|
|
11
|
+
}
|
|
12
|
+
function isRow(v) {
|
|
13
|
+
const r = v;
|
|
14
|
+
return typeof r === "object" && r !== null && typeof r.id === "string" && typeof r.name === "string" && typeof r.online === "boolean";
|
|
15
|
+
}
|
|
16
|
+
export function httpCarrier(opts) {
|
|
17
|
+
const base = opts.url.replace(/\/+$/, "");
|
|
18
|
+
const doFetch = opts.fetch ?? fetch;
|
|
19
|
+
const headers = {
|
|
20
|
+
authorization: `Bearer ${opts.token}`,
|
|
21
|
+
"content-type": "application/json",
|
|
22
|
+
// The server takes writes under /api only with this header (a browser form cannot send it).
|
|
23
|
+
"x-cmdop": "1",
|
|
24
|
+
};
|
|
25
|
+
const fail = (m) => new CarrierError("http", m);
|
|
26
|
+
async function request(method, path, body, o) {
|
|
27
|
+
try {
|
|
28
|
+
return await doFetch(`${base}${path}`, {
|
|
29
|
+
method,
|
|
30
|
+
headers,
|
|
31
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
32
|
+
...(o.signal ? { signal: o.signal } : {}),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
if (o.signal?.aborted)
|
|
37
|
+
throw o.signal.reason ?? e;
|
|
38
|
+
throw fail(`could not reach ${base}: ${String(e)}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function answerOf(res) {
|
|
42
|
+
let body;
|
|
43
|
+
try {
|
|
44
|
+
body = await res.json();
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw fail(`server answered ${res.status} without JSON`);
|
|
48
|
+
}
|
|
49
|
+
if (!isAnswer(body))
|
|
50
|
+
throw fail(`server answered ${res.status} without a call answer`);
|
|
51
|
+
return body;
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
name: "http",
|
|
55
|
+
async call(req, o) {
|
|
56
|
+
return answerOf(await request("POST", "/api/v1/call", req, o));
|
|
57
|
+
},
|
|
58
|
+
async *stream(req, o) {
|
|
59
|
+
const res = await request("POST", "/api/v1/call/stream", req, o);
|
|
60
|
+
// A refusal before the call was sent comes as one JSON answer, not a stream.
|
|
61
|
+
if (!res.ok || !res.body) {
|
|
62
|
+
yield await answerOf(res);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const lines = [];
|
|
66
|
+
let wake;
|
|
67
|
+
let done = false;
|
|
68
|
+
let failed;
|
|
69
|
+
void readNdjson(res.body, (l) => {
|
|
70
|
+
lines.push(l);
|
|
71
|
+
wake?.();
|
|
72
|
+
})
|
|
73
|
+
.catch((e) => {
|
|
74
|
+
failed = e;
|
|
75
|
+
})
|
|
76
|
+
.finally(() => {
|
|
77
|
+
done = true;
|
|
78
|
+
wake?.();
|
|
79
|
+
});
|
|
80
|
+
for (;;) {
|
|
81
|
+
const next = lines.shift();
|
|
82
|
+
if (next !== undefined) {
|
|
83
|
+
yield next;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (done)
|
|
87
|
+
break;
|
|
88
|
+
await new Promise((r) => (wake = r));
|
|
89
|
+
wake = undefined;
|
|
90
|
+
}
|
|
91
|
+
if (failed !== undefined) {
|
|
92
|
+
if (o.signal?.aborted)
|
|
93
|
+
throw o.signal.reason ?? failed;
|
|
94
|
+
throw fail(`the stream broke: ${String(failed)}`);
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
async machines(o) {
|
|
98
|
+
const res = await request("GET", "/api/v1/machines", undefined, o);
|
|
99
|
+
let body;
|
|
100
|
+
try {
|
|
101
|
+
body = await res.json();
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw fail(`server answered ${res.status} without JSON for the machine list`);
|
|
105
|
+
}
|
|
106
|
+
if (isAnswer(body))
|
|
107
|
+
return body;
|
|
108
|
+
if (!res.ok || !Array.isArray(body) || !body.every(isRow))
|
|
109
|
+
throw fail(`server answered ${res.status} without a machine list`);
|
|
110
|
+
return { ok: body };
|
|
111
|
+
},
|
|
112
|
+
async close() { },
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The in-memory carrier: the contract with no channel at all, for tests and the conformance suite. `serve` plays the
|
|
3
|
+
* door: it gets each request and the caller's signal, and yields what the door would (pieces, then the answer).
|
|
4
|
+
*/
|
|
5
|
+
import type { CallRequest, StreamLine } from "../generated/call.gen.ts";
|
|
6
|
+
import { type Carrier, type MachineRow } from "./carrier.ts";
|
|
7
|
+
export interface MemoryDoor {
|
|
8
|
+
serve(req: CallRequest, signal: AbortSignal | undefined): AsyncIterable<StreamLine>;
|
|
9
|
+
machines?: MachineRow[];
|
|
10
|
+
}
|
|
11
|
+
export declare function memoryCarrier(door: MemoryDoor): Carrier;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The in-memory carrier: the contract with no channel at all, for tests and the conformance suite. `serve` plays the
|
|
3
|
+
* door: it gets each request and the caller's signal, and yields what the door would (pieces, then the answer).
|
|
4
|
+
*/
|
|
5
|
+
import { CarrierError } from "./carrier.js";
|
|
6
|
+
const isAnswer = (l) => "ok" in l || "error" in l || "sealed" in l;
|
|
7
|
+
export function memoryCarrier(door) {
|
|
8
|
+
return {
|
|
9
|
+
name: "memory",
|
|
10
|
+
async call(req, o) {
|
|
11
|
+
let last;
|
|
12
|
+
for await (const l of this.stream(req, o))
|
|
13
|
+
if (isAnswer(l))
|
|
14
|
+
last = l;
|
|
15
|
+
if (!last)
|
|
16
|
+
throw new CarrierError("memory", "the door gave no answer");
|
|
17
|
+
return last;
|
|
18
|
+
},
|
|
19
|
+
async *stream(req, o) {
|
|
20
|
+
try {
|
|
21
|
+
yield* door.serve(req, o.signal);
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
// The caller's own abort stays theirs; anything else is the channel breaking.
|
|
25
|
+
if (o.signal?.aborted)
|
|
26
|
+
throw e;
|
|
27
|
+
throw new CarrierError("memory", `the door broke: ${String(e)}`);
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
async machines() {
|
|
31
|
+
return { ok: door.machines ?? [] };
|
|
32
|
+
},
|
|
33
|
+
async close() { },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The small streaming boundary used by `/api/v1/call/stream`.
|
|
3
|
+
*
|
|
4
|
+
* The endpoint deliberately stays outside ordinary JSON code generation: its
|
|
5
|
+
* response is a sequence of JSON values, not one JSON document. Keeping the
|
|
6
|
+
* framing here gives the SDK one place to handle split UTF-8 chunks, blank
|
|
7
|
+
* lines and a final line without a trailing newline.
|
|
8
|
+
*/
|
|
9
|
+
export type NdjsonLine<TChunk, TAnswer> = {
|
|
10
|
+
chunk: TChunk;
|
|
11
|
+
seq: number;
|
|
12
|
+
} | {
|
|
13
|
+
sealed_chunk: string;
|
|
14
|
+
seq: number;
|
|
15
|
+
} | TAnswer;
|
|
16
|
+
export declare function readNdjson<T>(body: ReadableStream<Uint8Array>, onLine: (line: T) => void | Promise<void>): Promise<void>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The small streaming boundary used by `/api/v1/call/stream`.
|
|
3
|
+
*
|
|
4
|
+
* The endpoint deliberately stays outside ordinary JSON code generation: its
|
|
5
|
+
* response is a sequence of JSON values, not one JSON document. Keeping the
|
|
6
|
+
* framing here gives the SDK one place to handle split UTF-8 chunks, blank
|
|
7
|
+
* lines and a final line without a trailing newline.
|
|
8
|
+
*/
|
|
9
|
+
export async function readNdjson(body, onLine) {
|
|
10
|
+
const reader = body.getReader();
|
|
11
|
+
const decoder = new TextDecoder();
|
|
12
|
+
let rest = "";
|
|
13
|
+
const emit = async (line) => {
|
|
14
|
+
const text = line.trim();
|
|
15
|
+
if (text)
|
|
16
|
+
await onLine(JSON.parse(text));
|
|
17
|
+
};
|
|
18
|
+
for (;;) {
|
|
19
|
+
const { done, value } = await reader.read();
|
|
20
|
+
if (done)
|
|
21
|
+
break;
|
|
22
|
+
rest += decoder.decode(value, { stream: true });
|
|
23
|
+
let newline;
|
|
24
|
+
while ((newline = rest.indexOf("\n")) >= 0) {
|
|
25
|
+
await emit(rest.slice(0, newline));
|
|
26
|
+
rest = rest.slice(newline + 1);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
rest += decoder.decode();
|
|
30
|
+
await emit(rest);
|
|
31
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cmdop client (developer SDK plan, section 4): your machines' tools from a program.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* const cmdop = connect(); // CMDOP_TOKEN and CMDOP_URL
|
|
6
|
+
* const box = cmdop.machine("box");
|
|
7
|
+
* const { exit_code, stdout } = await box.run("uptime");
|
|
8
|
+
* const run = box.stream("make test");
|
|
9
|
+
* for await (const piece of run) process.stdout.write(piece.data);
|
|
10
|
+
* const done = await run.result;
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Every tool, its arguments and result, the error codes and the call shapes are generated from the Rust workspace
|
|
14
|
+
* (`generated/`). This file speaks only the call contract; which channel carries it is the carrier's business
|
|
15
|
+
* (`carriers/`), and nothing here knows it.
|
|
16
|
+
*
|
|
17
|
+
* End-to-end calls come through a `Sealer` (`connect({ e2e })`): this file holds no key and reads no sealed text.
|
|
18
|
+
*/
|
|
19
|
+
import type { Answer, CallRequest, ErrorCode, OutputChunk } from "./generated/call.gen.ts";
|
|
20
|
+
import { type ExecRunArgs, type ExecRunOut, type ScreenCaptureArgs, type ToolMap, type ToolName } from "./generated/tools.gen.ts";
|
|
21
|
+
import { type Carrier, type MachineRow } from "./carriers/carrier.ts";
|
|
22
|
+
import { type Screenshot } from "./screen.ts";
|
|
23
|
+
/**
|
|
24
|
+
* End-to-end calls: `connect({ e2e })` takes a sealer. It turns each call into the request to send and opens what
|
|
25
|
+
* comes back for it; the client sends what it is given and never reads the sealed text itself.
|
|
26
|
+
*/
|
|
27
|
+
export interface Sealer {
|
|
28
|
+
/** The request to send for one call, and how to open what comes back for it. `machines` lists the contour's machines. */
|
|
29
|
+
seal(call: CallRequest, machines: () => Promise<MachineRow[]>): Promise<{
|
|
30
|
+
req: CallRequest;
|
|
31
|
+
open: Opener;
|
|
32
|
+
}>;
|
|
33
|
+
/** This client's public key, for `cmdop pair <key>` on each machine. */
|
|
34
|
+
publicKey(): Promise<string>;
|
|
35
|
+
}
|
|
36
|
+
/** Opens what comes back for one sealed call. Anything not sealed for it throws `CmdopError` (`not_sealed`). */
|
|
37
|
+
export interface Opener {
|
|
38
|
+
answer(sealed: string): Promise<Answer>;
|
|
39
|
+
piece(seq: number, sealed: string): Promise<OutputChunk>;
|
|
40
|
+
}
|
|
41
|
+
export interface ConnectOptions {
|
|
42
|
+
/** An agent token (held to its grant) or an owner token. Default: `CMDOP_TOKEN`. Keep it out of source and logs. */
|
|
43
|
+
token?: string;
|
|
44
|
+
/** The contour's address in full, `https://<address>.cmdop.dev` or a local server. Default: `CMDOP_URL`. */
|
|
45
|
+
url?: string;
|
|
46
|
+
/** The contour's address alone, for example `m7xg5cgy`, instead of `url`. */
|
|
47
|
+
contour?: string;
|
|
48
|
+
/** `"auto"` (default, or `CMDOP_CARRIER`), `"http"`, or a carrier of your own (tests: `memoryCarrier`). */
|
|
49
|
+
carrier?: "auto" | "http" | Carrier;
|
|
50
|
+
/** Seal every call end to end with this sealer. */
|
|
51
|
+
e2e?: Sealer;
|
|
52
|
+
/** For the HTTP carrier in tests and other runtimes; the global `fetch` by default. */
|
|
53
|
+
fetch?: typeof fetch;
|
|
54
|
+
}
|
|
55
|
+
export interface CallOpts {
|
|
56
|
+
/** Machine id or unique name; left out when exactly one machine is online. */
|
|
57
|
+
machine?: string;
|
|
58
|
+
/** How long to wait, in milliseconds. The call keeps the shorter of this and the tool's own time. */
|
|
59
|
+
deadline?: number;
|
|
60
|
+
/** Aborting it cancels the call; the answer is then `cancelled`. */
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
}
|
|
63
|
+
/** Why a call returned no result. Decide by `code`, never by `message`. */
|
|
64
|
+
export declare class CmdopError extends Error {
|
|
65
|
+
readonly code: ErrorCode | "not_sealable" | "not_sealed" | "key_changed";
|
|
66
|
+
/**
|
|
67
|
+
* Machine-readable facts that come with some codes. `permission_missing` carries
|
|
68
|
+
* `{ permission, state, requires_human, machine, human_action, retry }`: a person must act on that machine, do not
|
|
69
|
+
* retry until they have.
|
|
70
|
+
*/
|
|
71
|
+
readonly details?: Record<string, unknown>;
|
|
72
|
+
constructor(code: CmdopError["code"], message: string, details?: Record<string, unknown>);
|
|
73
|
+
}
|
|
74
|
+
/** One piece of a running command's output, with its place in the call. */
|
|
75
|
+
export type Piece = OutputChunk & {
|
|
76
|
+
seq: number;
|
|
77
|
+
};
|
|
78
|
+
/** A call running with its output followed: iterate for the pieces, then `await run.result`. */
|
|
79
|
+
export interface Run<T = ExecRunOut> extends AsyncIterable<Piece> {
|
|
80
|
+
/** The call's result, the same as the one-shot call returns. Awaiting it without iterating skips the pieces. */
|
|
81
|
+
readonly result: Promise<T>;
|
|
82
|
+
}
|
|
83
|
+
type ToolMethods = {
|
|
84
|
+
[N in ToolName]: (args: ToolMap[N]["args"], opts?: Omit<CallOpts, "machine">) => Promise<ToolMap[N]["out"]>;
|
|
85
|
+
};
|
|
86
|
+
/** One machine: every tool as a method (`box.fs_read({ path })`) and three short forms. */
|
|
87
|
+
export type Machine = ToolMethods & {
|
|
88
|
+
/** `exec_run` with a shell command line. */
|
|
89
|
+
run(command: string, args?: Omit<ExecRunArgs, "command" | "argv">, opts?: Omit<CallOpts, "machine">): Promise<ExecRunOut>;
|
|
90
|
+
/** `exec_run` with its output as it comes. Breaking out of the loop or aborting `signal` stops the command. */
|
|
91
|
+
stream(command: string, args?: Omit<ExecRunArgs, "command" | "argv">, opts?: Omit<CallOpts, "machine">): Run;
|
|
92
|
+
/** `screen_capture` with the picture decoded. Needs the `screen` grant and `screen` in the machine's ceiling. */
|
|
93
|
+
screenshot(args?: ScreenCaptureArgs, opts?: Omit<CallOpts, "machine">): Promise<Screenshot>;
|
|
94
|
+
};
|
|
95
|
+
export interface Client {
|
|
96
|
+
/** Which carrier is in use (`"http"`, …): what `auto` picked. */
|
|
97
|
+
readonly carrier: string;
|
|
98
|
+
/** The machines of the contour: name, id, online, os, tools. */
|
|
99
|
+
machines(opts?: Pick<CallOpts, "signal">): Promise<MachineRow[]>;
|
|
100
|
+
/** One machine; no name: the one online machine (the server decides). */
|
|
101
|
+
machine(name?: string): Machine;
|
|
102
|
+
/** Runs any tool by name. */
|
|
103
|
+
call<N extends ToolName>(tool: N, args: ToolMap[N]["args"], opts?: CallOpts): Promise<ToolMap[N]["out"]>;
|
|
104
|
+
/** Runs any tool by name as a streamed call: its pieces as they come (only `exec_run` sends any), then its result. */
|
|
105
|
+
stream<N extends ToolName>(tool: N, args: ToolMap[N]["args"], opts?: CallOpts): Run<ToolMap[N]["out"]>;
|
|
106
|
+
/** With `e2e`: this client's public key, for `cmdop pair <key>` on each machine. */
|
|
107
|
+
publicKey(): Promise<string>;
|
|
108
|
+
close(): Promise<void>;
|
|
109
|
+
}
|
|
110
|
+
/** `url` as given, else `https://<contour>.cmdop.dev`; `CMDOP_URL` when neither is given. */
|
|
111
|
+
export declare function urlOf(opts: Pick<ConnectOptions, "url" | "contour">): string;
|
|
112
|
+
export declare function connect(opts?: ConnectOptions): Client;
|
|
113
|
+
export {};
|