assistant-sandbox 0.0.0-stage → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # TypeScript SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```sh
4
+ npm install assistant-sandbox
5
+ ```
6
+
7
+ 首版 npm 发行包提供 Linux amd64 的 Node-API 模块。Windows amd64 仍在验收。需要 Node.js 22 或更新版本。
8
+
9
+ [示例](examples/shell.ts) 在同一个 Bash 中执行两次命令,输出 `hello from /tmp`。从 [GitHub Releases](https://github.com/Cosmic-Developers-Union/assistant-sandbox/releases) 下载客体镜像后运行示例。
10
+
11
+ ```sh
12
+ node sdk/typescript/examples/shell.ts ./assistant-sandbox-core-linux-amd64.bundle
13
+ ```
14
+
15
+ Windows amd64 可传入下载的 `assistant-sandbox-windows-amd64.exe` 读取内嵌镜像。从源码开发时,使用 `make sdk-packages` 构建本机 npm 包。
16
+
17
+ 社区使用适用 [PolyForm Noncommercial 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0)。商业使用需要与项目权利人另行签署商业授权协议。
package/dist/LICENSE ADDED
@@ -0,0 +1,131 @@
1
+ # PolyForm Noncommercial License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree
8
+ to them as both strict obligations and conditions to all
9
+ your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the
14
+ software to do everything you might do with the software
15
+ that would otherwise infringe the licensor's copyright
16
+ in it for any permitted purpose. However, you may
17
+ only distribute the software according to [Distribution
18
+ License](#distribution-license) and make changes or new works
19
+ based on the software according to [Changes and New Works
20
+ License](#changes-and-new-works-license).
21
+
22
+ ## Distribution License
23
+
24
+ The licensor grants you an additional copyright license
25
+ to distribute copies of the software. Your license
26
+ to distribute covers distributing the software with
27
+ changes and new works permitted by [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Notices
31
+
32
+ You must ensure that anyone who gets a copy of any part of
33
+ the software from you also gets a copy of these terms or the
34
+ URL for them above, as well as copies of any plain-text lines
35
+ beginning with `Required Notice:` that the licensor provided
36
+ with the software. For example:
37
+
38
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
39
+
40
+ ## Changes and New Works License
41
+
42
+ The licensor grants you an additional copyright license to
43
+ make changes and new works based on the software for any
44
+ permitted purpose.
45
+
46
+ ## Patent License
47
+
48
+ The licensor grants you a patent license for the software that
49
+ covers patent claims the licensor can license, or becomes able
50
+ to license, that you would infringe by using the software.
51
+
52
+ ## Noncommercial Purposes
53
+
54
+ Any noncommercial purpose is a permitted purpose.
55
+
56
+ ## Personal Uses
57
+
58
+ Personal use for research, experiment, and testing for
59
+ the benefit of public knowledge, personal study, private
60
+ entertainment, hobby projects, amateur pursuits, or religious
61
+ observance, without any anticipated commercial application,
62
+ is use for a permitted purpose.
63
+
64
+ ## Noncommercial Organizations
65
+
66
+ Use by any charitable organization, educational institution,
67
+ public research organization, public safety or health
68
+ organization, environmental protection organization,
69
+ or government institution is use for a permitted purpose
70
+ regardless of the source of funding or obligations resulting
71
+ from the funding.
72
+
73
+ ## Fair Use
74
+
75
+ You may have "fair use" rights for the software under the
76
+ law. These terms do not limit them.
77
+
78
+ ## No Other Rights
79
+
80
+ These terms do not allow you to sublicense or transfer any of
81
+ your licenses to anyone else, or prevent the licensor from
82
+ granting licenses to anyone else. These terms do not imply
83
+ any other licenses.
84
+
85
+ ## Patent Defense
86
+
87
+ If you make any written claim that the software infringes or
88
+ contributes to infringement of any patent, your patent license
89
+ for the software granted under these terms ends immediately. If
90
+ your company makes such a claim, your patent license ends
91
+ immediately for work on behalf of your company.
92
+
93
+ ## Violations
94
+
95
+ The first time you are notified in writing that you have
96
+ violated any of these terms, or done anything with the software
97
+ not covered by your licenses, your licenses can nonetheless
98
+ continue if you come into full compliance with these terms,
99
+ and take practical steps to correct past violations, within
100
+ 32 days of receiving notice. Otherwise, all your licenses
101
+ end immediately.
102
+
103
+ ## No Liability
104
+
105
+ ***As far as the law allows, the software comes as is, without
106
+ any warranty or condition, and the licensor will not be liable
107
+ to you for any damages arising out of these terms or the use
108
+ or nature of the software, under any kind of legal claim.***
109
+
110
+ ## Definitions
111
+
112
+ The **licensor** is the individual or entity offering these
113
+ terms, and the **software** is the software the licensor makes
114
+ available under these terms.
115
+
116
+ **You** refers to the individual or entity agreeing to these
117
+ terms.
118
+
119
+ **Your company** is any legal entity, sole proprietorship,
120
+ or other kind of organization that you work for, plus all
121
+ organizations that have control over, are under the control of,
122
+ or are under common control with that organization. **Control**
123
+ means ownership of substantially all the assets of an entity,
124
+ or the power to direct its management and policies by vote,
125
+ contract, or otherwise. Control can be direct or indirect.
126
+
127
+ **Your licenses** are all the licenses granted to you for the
128
+ software under these terms.
129
+
130
+ **Use** means anything you do with the software requiring one
131
+ of your licenses.
@@ -0,0 +1,26 @@
1
+ export declare const PROTOCOL_VERSION = 2;
2
+ export declare const MAX_RUNNING = 8;
3
+ export declare const MAX_SCRIPT = 65536;
4
+ export declare const MAX_FRAME = 8388608;
5
+ export declare const MAX_OUTPUT = 1048576;
6
+ export type Mode = "exec" | "command" | "script" | "terminal";
7
+ export type Shell = "bash" | "sh";
8
+ export interface Mount {
9
+ image: string;
10
+ target: string;
11
+ }
12
+ export interface Options {
13
+ allow_egress?: string[];
14
+ debug?: boolean;
15
+ directory?: string;
16
+ engine?: string;
17
+ memory_mib?: number;
18
+ mode?: Mode;
19
+ mounts?: Mount[];
20
+ publish?: string[];
21
+ read_only?: boolean;
22
+ script?: string;
23
+ shell?: Shell;
24
+ system?: string;
25
+ term?: string;
26
+ }
@@ -0,0 +1,6 @@
1
+ // Generated by tools/generate-sdk.py from the Rust protocol. DO NOT EDIT.
2
+ export const PROTOCOL_VERSION = 2;
3
+ export const MAX_RUNNING = 8;
4
+ export const MAX_SCRIPT = 65536;
5
+ export const MAX_FRAME = 8388608;
6
+ export const MAX_OUTPUT = 1048576;
package/dist/host.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import type { Options } from "./contract.ts";
2
+ import type { DesktopAction, Outcome } from "./runtime.ts";
3
+ export interface HostInfo {
4
+ id: string;
5
+ created_at: string;
6
+ shells?: number[];
7
+ }
8
+ export type HostEvent = {
9
+ sequence: number;
10
+ } & ({
11
+ type: "output";
12
+ stream: "stdout" | "stderr";
13
+ data: string;
14
+ } | {
15
+ type: "finished";
16
+ outcome: Outcome;
17
+ shell_closed?: boolean;
18
+ stdout_truncated: boolean;
19
+ stderr_truncated: boolean;
20
+ });
21
+ export declare class Host {
22
+ #private;
23
+ readonly url: string;
24
+ constructor(url: string, token: string);
25
+ list(): Promise<HostInfo[]>;
26
+ create(options?: Options): Promise<HostSandbox>;
27
+ attach(id: string): Promise<HostSandbox>;
28
+ /** @internal */
29
+ request(method: string, path: string, value?: unknown, signal?: AbortSignal): Promise<Response>;
30
+ /** @internal */
31
+ json<T>(method: string, path: string, value?: unknown): Promise<T>;
32
+ }
33
+ export declare class HostSandbox {
34
+ #private;
35
+ readonly id: string;
36
+ constructor(host: Host, id: string);
37
+ info(): Promise<HostInfo>;
38
+ destroy(): Promise<void>;
39
+ openShell(): Promise<number>;
40
+ closeShell(shell: number): Promise<void>;
41
+ run(script: string, options?: {
42
+ shell?: number;
43
+ timeout_ms?: number;
44
+ output_limit?: number;
45
+ }): Promise<number>;
46
+ events(run: number, after?: number, signal?: AbortSignal): AsyncGenerator<HostEvent>;
47
+ cancel(run: number): Promise<void>;
48
+ desktopURL(): Promise<string>;
49
+ desktopFrame(actions?: DesktopAction[]): Promise<Buffer>;
50
+ }
package/dist/host.js ADDED
@@ -0,0 +1,91 @@
1
+ export class Host {
2
+ url;
3
+ #token;
4
+ constructor(url, token) {
5
+ if (!/^http:\/\/127\.0\.0\.1:[0-9]{1,5}\/?$/.test(url) || !token) {
6
+ throw new Error("a local sandbox Host URL and token are required");
7
+ }
8
+ this.url = url.replace(/\/$/, "");
9
+ this.#token = token;
10
+ }
11
+ list() {
12
+ return this.json("GET", "/v1/sandboxes");
13
+ }
14
+ async create(options = {}) {
15
+ const { id } = await this.json("POST", "/v1/sandboxes", options);
16
+ return new HostSandbox(this, id);
17
+ }
18
+ async attach(id) {
19
+ const sandbox = new HostSandbox(this, id);
20
+ await sandbox.info();
21
+ return sandbox;
22
+ }
23
+ /** @internal */
24
+ async request(method, path, value, signal) {
25
+ const response = await fetch(this.url + path, {
26
+ method, signal, redirect: "error",
27
+ body: value === undefined ? undefined : JSON.stringify(value),
28
+ headers: { Authorization: `Bearer ${this.#token}`, "Content-Type": "application/json" },
29
+ });
30
+ if (!response.ok)
31
+ throw new Error(`sandbox Host returned ${response.status}: ${await response.text()}`);
32
+ return response;
33
+ }
34
+ /** @internal */
35
+ async json(method, path, value) {
36
+ const response = await this.request(method, path, value);
37
+ return response.status === 204 ? undefined : await response.json();
38
+ }
39
+ }
40
+ export class HostSandbox {
41
+ id;
42
+ #host;
43
+ #path;
44
+ constructor(host, id) {
45
+ if (!/^[0-9a-f]{32}$/.test(id))
46
+ throw new Error("invalid sandbox ID");
47
+ this.id = id;
48
+ this.#host = host;
49
+ this.#path = `/v1/sandboxes/${id}`;
50
+ }
51
+ info() { return this.#host.json("GET", this.#path); }
52
+ destroy() { return this.#host.json("DELETE", this.#path); }
53
+ async openShell() {
54
+ return (await this.#host.json("POST", this.#path + "/shells")).id;
55
+ }
56
+ closeShell(shell) { return this.#host.json("DELETE", this.#path + `/shells/${shell}`); }
57
+ async run(script, options = {}) {
58
+ const { shell, ...limits } = options;
59
+ const path = shell === undefined ? this.#path : this.#path + `/shells/${shell}`;
60
+ return (await this.#host.json("POST", path + "/runs", { script, ...limits })).id;
61
+ }
62
+ async *events(run, after = 0, signal) {
63
+ const response = await this.#host.request("GET", this.#path + `/runs/${run}/events?after=${after}`, undefined, signal);
64
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
65
+ let buffered = "";
66
+ try {
67
+ for (;;) {
68
+ const { value, done } = await reader.read();
69
+ if (done)
70
+ break;
71
+ const lines = (buffered + value).split("\n");
72
+ buffered = lines.pop() ?? "";
73
+ for (const line of lines)
74
+ yield JSON.parse(line);
75
+ }
76
+ }
77
+ finally {
78
+ await reader.cancel();
79
+ }
80
+ }
81
+ async cancel(run) {
82
+ await this.#host.request("POST", this.#path + `/runs/${run}/cancel`);
83
+ }
84
+ async desktopURL() {
85
+ return this.#host.url + (await this.#host.json("POST", this.#path + "/desktop/view")).url;
86
+ }
87
+ async desktopFrame(actions = []) {
88
+ const response = await this.#host.request("POST", this.#path + "/desktop/frames", actions);
89
+ return Buffer.from(await response.arrayBuffer());
90
+ }
91
+ }
@@ -0,0 +1,3 @@
1
+ export type { Mount, Options } from "./contract.ts";
2
+ export { Host, HostSandbox, type HostEvent, type HostInfo } from "./host.ts";
3
+ export { Desktop, Execution, Runtime, Sandbox, ShellSession, Sandbox as Session, type DesktopAction, type Event, type ExecOptions, type Outcome, type Point, type Completed, type Vnc, } from "./runtime.ts";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { Host, HostSandbox } from "./host.js";
2
+ export { Desktop, Execution, Runtime, Sandbox, ShellSession, Sandbox as Session, } from "./runtime.js";
Binary file
@@ -0,0 +1,130 @@
1
+ import { type Options } from "./contract.ts";
2
+ export interface ExecOptions {
3
+ timeout_ms?: number;
4
+ output_limit?: number;
5
+ }
6
+ export type Outcome = {
7
+ type: "exited";
8
+ code: number;
9
+ } | {
10
+ type: "cancelled" | "timed_out";
11
+ } | {
12
+ type: "failed";
13
+ message: string;
14
+ };
15
+ export type Event = {
16
+ type: "output";
17
+ stream: "stdout" | "stderr";
18
+ data: Buffer;
19
+ } | {
20
+ type: "finished";
21
+ outcome: Outcome;
22
+ stdout_truncated: boolean;
23
+ stderr_truncated: boolean;
24
+ shell_closed?: boolean;
25
+ };
26
+ interface NativeExecution {
27
+ readonly id: number;
28
+ next(): Promise<{
29
+ kind: "output";
30
+ stream: "stdout" | "stderr";
31
+ data: Buffer;
32
+ } | {
33
+ kind: "finished";
34
+ outcome: {
35
+ kind: Outcome["type"];
36
+ code?: number;
37
+ message?: string;
38
+ };
39
+ stdoutTruncated: boolean;
40
+ stderrTruncated: boolean;
41
+ shellClosed: boolean;
42
+ }>;
43
+ }
44
+ interface NativeShell {
45
+ readonly id: number;
46
+ run(script: string, timeout: number | undefined, limit: number): Promise<NativeExecution>;
47
+ interrupt(id: number): Promise<void>;
48
+ close(): Promise<void>;
49
+ }
50
+ interface NativeDesktop {
51
+ frame(actions: string): Promise<Buffer>;
52
+ openVnc(): Promise<Vnc>;
53
+ close(): void;
54
+ }
55
+ interface NativeSandbox {
56
+ exec(script: string, timeout: number | undefined, limit: number): Promise<NativeExecution>;
57
+ cancel(id: number): Promise<void>;
58
+ openShell(): Promise<NativeShell>;
59
+ desktop(): Promise<NativeDesktop>;
60
+ destroy(): Promise<void>;
61
+ }
62
+ export interface Completed {
63
+ code: number;
64
+ stdout: Buffer;
65
+ stderr: Buffer;
66
+ }
67
+ export interface Vnc {
68
+ read(timeoutMs?: number): Promise<Buffer>;
69
+ write(data: Buffer): Promise<void>;
70
+ close(): Promise<void>;
71
+ }
72
+ export declare class Execution {
73
+ #private;
74
+ /** @internal */
75
+ constructor(handle: NativeExecution);
76
+ get id(): number;
77
+ next(): Promise<Event>;
78
+ [Symbol.asyncIterator](): AsyncGenerator<Event>;
79
+ }
80
+ export declare class Runtime {
81
+ readonly bundle: string;
82
+ constructor(bundle: string);
83
+ open(options?: Options): Promise<Sandbox>;
84
+ create(options?: Options): Promise<Sandbox>;
85
+ run(script?: string, options?: Options, input?: Uint8Array): Promise<Completed>;
86
+ }
87
+ export declare class Sandbox {
88
+ #private;
89
+ /** @internal */
90
+ constructor(handle: NativeSandbox);
91
+ exec(script: string, options?: ExecOptions): Promise<Execution>;
92
+ openShell(): Promise<ShellSession>;
93
+ desktop(): Promise<Desktop>;
94
+ cancel(id: number): Promise<void>;
95
+ destroy(): Promise<void>;
96
+ close(): Promise<void>;
97
+ }
98
+ export declare class ShellSession {
99
+ #private;
100
+ /** @internal */
101
+ constructor(handle: NativeShell);
102
+ get id(): number;
103
+ run(script: string, options?: ExecOptions): Promise<Execution>;
104
+ interrupt(id: number): Promise<void>;
105
+ close(): Promise<void>;
106
+ }
107
+ export interface Point {
108
+ x: number;
109
+ y: number;
110
+ }
111
+ export interface DesktopAction {
112
+ type: string;
113
+ x?: number;
114
+ y?: number;
115
+ button?: string;
116
+ keys?: string[];
117
+ path?: Point[];
118
+ text?: string;
119
+ scroll_x?: number;
120
+ scroll_y?: number;
121
+ }
122
+ export declare class Desktop {
123
+ #private;
124
+ /** @internal */
125
+ constructor(handle: NativeDesktop);
126
+ frame(actions?: DesktopAction[]): Promise<Buffer>;
127
+ openVnc(): Promise<Vnc>;
128
+ close(): void;
129
+ }
130
+ export {};
@@ -0,0 +1,103 @@
1
+ import { createRequire } from "node:module";
2
+ import { resolve } from "node:path";
3
+ import { MAX_OUTPUT } from "./contract.js";
4
+ const require = createRequire(import.meta.url);
5
+ let binding;
6
+ function native() {
7
+ const target = `${process.platform}-${process.arch}`;
8
+ if (target !== "linux-x64" && target !== "win32-x64") {
9
+ throw new Error(`The Assistant Sandbox native runtime is unavailable on ${target}`);
10
+ }
11
+ return binding ??= require(`./native/${target}.node`);
12
+ }
13
+ function execOptions(options) {
14
+ const timeout = options.timeout_ms;
15
+ const limit = options.output_limit ?? (64 << 10);
16
+ if (!Number.isInteger(limit) || limit < 0 || limit > MAX_OUTPUT ||
17
+ (timeout !== undefined && (!Number.isInteger(timeout) || timeout <= 0 || timeout > 0xffffffff))) {
18
+ throw new RangeError("invalid timeout or output limit");
19
+ }
20
+ return [timeout, limit];
21
+ }
22
+ export class Execution {
23
+ #handle;
24
+ /** @internal */
25
+ constructor(handle) { this.#handle = handle; }
26
+ get id() { return this.#handle.id; }
27
+ async next() {
28
+ const event = await this.#handle.next();
29
+ if (event.kind === "output") {
30
+ return { type: "output", stream: event.stream, data: event.data };
31
+ }
32
+ const { kind, code, message } = event.outcome;
33
+ let outcome;
34
+ if (kind === "exited")
35
+ outcome = { type: kind, code: code };
36
+ else if (kind === "failed")
37
+ outcome = { type: kind, message: message };
38
+ else
39
+ outcome = { type: kind };
40
+ return {
41
+ type: "finished", outcome, stdout_truncated: event.stdoutTruncated,
42
+ stderr_truncated: event.stderrTruncated, shell_closed: event.shellClosed,
43
+ };
44
+ }
45
+ async *[Symbol.asyncIterator]() {
46
+ for (;;) {
47
+ const event = await this.next();
48
+ yield event;
49
+ if (event.type === "finished")
50
+ return;
51
+ }
52
+ }
53
+ }
54
+ export class Runtime {
55
+ bundle;
56
+ constructor(bundle) { this.bundle = resolve(bundle); }
57
+ open(options = {}) { return this.create(options); }
58
+ async create(options = {}) {
59
+ return new Sandbox(await native().create(this.bundle, JSON.stringify(options)));
60
+ }
61
+ async run(script, options = {}, input) {
62
+ const config = { ...options, mode: options.mode ?? "command", script: script ?? options.script };
63
+ return native().run(this.bundle, JSON.stringify(config), Buffer.from(input ?? []));
64
+ }
65
+ }
66
+ export class Sandbox {
67
+ #handle;
68
+ /** @internal */
69
+ constructor(handle) { this.#handle = handle; }
70
+ async exec(script, options = {}) {
71
+ return new Execution(await this.#handle.exec(script, ...execOptions(options)));
72
+ }
73
+ async openShell() {
74
+ return new ShellSession(await this.#handle.openShell());
75
+ }
76
+ async desktop() {
77
+ return new Desktop(await this.#handle.desktop());
78
+ }
79
+ cancel(id) { return this.#handle.cancel(id); }
80
+ destroy() { return this.#handle.destroy(); }
81
+ close() { return this.destroy(); }
82
+ }
83
+ export class ShellSession {
84
+ #handle;
85
+ /** @internal */
86
+ constructor(handle) { this.#handle = handle; }
87
+ get id() { return this.#handle.id; }
88
+ async run(script, options = {}) {
89
+ return new Execution(await this.#handle.run(script, ...execOptions(options)));
90
+ }
91
+ interrupt(id) { return this.#handle.interrupt(id); }
92
+ close() { return this.#handle.close(); }
93
+ }
94
+ export class Desktop {
95
+ #handle;
96
+ /** @internal */
97
+ constructor(handle) { this.#handle = handle; }
98
+ frame(actions = []) {
99
+ return this.#handle.frame(JSON.stringify(actions));
100
+ }
101
+ openVnc() { return this.#handle.openVnc(); }
102
+ close() { this.#handle.close(); }
103
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "assistant-sandbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.4",
4
+ "description": "Node.js SDK for the Assistant Sandbox Rust runtime",
5
+ "license": "PolyForm-Noncommercial-1.0.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Cosmic-Developers-Union/assistant-sandbox.git",
9
+ "directory": "sdk/typescript"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": ["dist"],
19
+ "engines": { "node": ">=22" },
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.json",
22
+ "test": "node --test tests/runtime.test.ts"
23
+ },
24
+ "devDependencies": { "@types/node": "^22.18.0", "typescript": "^5.9.2" }
25
+ }