@celestoai/sdk 0.1.3 → 0.1.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
@@ -28,12 +28,21 @@ files or folders your app can use.
28
28
  npm install @celestoai/sdk
29
29
  ```
30
30
 
31
- Set your API key before running SDK examples:
31
+ Sign in once with the Celesto CLI:
32
32
 
33
33
  ```bash
34
- export CELESTO_API_KEY="your-api-key"
34
+ pip install celesto
35
+ celesto auth login
35
36
  ```
36
37
 
38
+ The `Computer` API checks an explicitly passed `token` or `apiKey` first, then `CELESTO_API_KEY` in the shell, the current project's `.env`, and credentials saved by `celesto auth login`. You can use a local `.env` instead of the CLI:
39
+
40
+ ```bash .env
41
+ CELESTO_API_KEY="your-api-key"
42
+ ```
43
+
44
+ Add `.env` to `.gitignore`.
45
+
37
46
  ## Quickstart
38
47
 
39
48
  Create a file named `quickstart.mjs`:
@@ -138,6 +147,26 @@ try {
138
147
  }
139
148
  ```
140
149
 
150
+ Stream output while the command is running:
151
+
152
+ ```js
153
+ import { Computer } from "@celestoai/sdk";
154
+
155
+ const computer = await Computer.get("curie");
156
+ const controller = new AbortController();
157
+
158
+ for await (const event of computer.runStream("npm test", {
159
+ timeout: 300,
160
+ signal: controller.signal,
161
+ })) {
162
+ if (event.type === "stdout") process.stdout.write(event.data);
163
+ if (event.type === "stderr") process.stderr.write(event.data);
164
+ if (event.type === "exit") console.log(`Exit code: ${event.exitCode}`);
165
+ }
166
+ ```
167
+
168
+ Call `controller.abort()` to stop the stream and the remote command.
169
+
141
170
  ### Manage Computers
142
171
 
143
172
  `computerId` can be `computer.id` from `Computer.create()` or a computer name
@@ -147,6 +176,7 @@ shown by the Celesto command-line tool: `celesto computer list`.
147
176
  | --- | --- |
148
177
  | `Computer.list()` | List computers in your account |
149
178
  | `Computer.get(computerId)` | Get one computer by name or ID |
179
+ | `computer.listCommandHistory()` | List recent commands and their status |
150
180
  | `computer.stop()` | Stop a running computer |
151
181
  | `computer.start()` | Start a stopped computer |
152
182
  | `computer.delete()` | Delete a computer |
@@ -175,13 +205,33 @@ await computer.unpublishPort(8000);
175
205
 
176
206
  ### Terminal Connections
177
207
 
178
- Use `getTerminalConnection()` when you are building your own interactive
179
- terminal. It returns the WebSocket URL, headers, and first message needed to
180
- connect. A WebSocket is a long-running connection for sending terminal input and
181
- receiving terminal output.
208
+ Use `createTerminalSession()` when you are building an interactive terminal.
209
+ Celesto returns a short-lived URL that connects directly to the fast terminal
210
+ gateway instead of sending terminal traffic through the control plane. Creating
211
+ a terminal session requires write access to the computer.
212
+
213
+ For Node.js, first install a WebSocket client:
214
+
215
+ ```bash
216
+ npm install ws
217
+ ```
218
+
219
+ Then connect with the authenticated URL:
220
+
221
+ ```js
222
+ import { Computer } from "@celestoai/sdk";
223
+ import WebSocket from "ws";
224
+
225
+ const computer = await Computer.get("curie");
226
+ const connection = await computer.createTerminalSession();
227
+ const ws = new WebSocket(connection.url);
228
+
229
+ ws.on("message", (data) => process.stdout.write(data));
230
+ ws.on("open", () => ws.send("pwd\n"));
231
+ ```
182
232
 
183
- The SDK does not install a WebSocket package for you. Use any WebSocket library
184
- that supports custom headers.
233
+ `connection.url` contains a short-lived terminal token. Treat it as a secret and
234
+ create a new terminal session after `connection.expiresAt`.
185
235
 
186
236
  ## Gatekeeper
187
237
 
@@ -224,8 +274,7 @@ Full Gatekeeper docs: https://docs.celesto.ai/celesto-sdk/gatekeeper
224
274
  | `headers` | Extra headers to send with every request |
225
275
 
226
276
  Pass these options as the second argument to `Computer.create()` or
227
- `Computer.get()`. Gatekeeper clients accept the same options in their
228
- constructor.
277
+ `Computer.get()`. An explicit `token` or `apiKey` takes precedence over local credential discovery. Gatekeeper clients accept the same options in their constructor and require an explicit token.
229
278
 
230
279
  JWT is a signed login token. Most users should use a Celesto API key.
231
280
 
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildRequestContext,
3
3
  request
4
- } from "./chunk-N3HU6ONW.js";
4
+ } from "./chunk-JS6BTDP5.js";
5
5
 
6
6
  // src/gatekeeper/client.ts
7
7
  var toConnectRequest = (payload) => ({
@@ -174,4 +174,4 @@ var GatekeeperClient = class {
174
174
  export {
175
175
  GatekeeperClient
176
176
  };
177
- //# sourceMappingURL=chunk-4KVRJSVJ.js.map
177
+ //# sourceMappingURL=chunk-5VVB6N33.js.map
@@ -85,7 +85,7 @@ var extractErrorMessage = (data, status) => {
85
85
  }
86
86
  return `Request failed with status ${status}`;
87
87
  };
88
- var request = async (ctx, options) => {
88
+ var buildRequestInit = (ctx, options) => {
89
89
  const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
90
90
  const headers = {
91
91
  ...ctx.headers ?? {},
@@ -103,13 +103,16 @@ var request = async (ctx, options) => {
103
103
  const init = {
104
104
  method: options.method,
105
105
  headers,
106
- body: void 0,
107
106
  signal: options.signal
108
107
  };
109
108
  if (options.body !== void 0) {
110
109
  headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
111
110
  init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
112
111
  }
112
+ return { url, init };
113
+ };
114
+ var request = async (ctx, options) => {
115
+ const { url, init } = buildRequestInit(ctx, options);
113
116
  let timeoutId;
114
117
  let controller;
115
118
  if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
@@ -137,12 +140,36 @@ var request = async (ctx, options) => {
137
140
  }
138
141
  }
139
142
  };
143
+ var requestStream = async (ctx, options) => {
144
+ const { url, init } = buildRequestInit(ctx, options);
145
+ try {
146
+ const response = await ctx.fetch(url, init);
147
+ if (!response.ok) {
148
+ const data = await parseResponseBody(response);
149
+ const message = extractErrorMessage(data, response.status);
150
+ throw new CelestoApiError(
151
+ message,
152
+ response.status,
153
+ data,
154
+ response.headers.get("x-request-id") ?? void 0
155
+ );
156
+ }
157
+ return response;
158
+ } catch (err) {
159
+ if (err instanceof CelestoApiError) {
160
+ throw err;
161
+ }
162
+ const error = err instanceof Error ? err : new Error(String(err));
163
+ throw new CelestoNetworkError(error.message, error);
164
+ }
165
+ };
140
166
 
141
167
  export {
142
168
  buildRequestContext,
143
169
  CelestoError,
144
170
  CelestoApiError,
145
171
  CelestoNetworkError,
146
- request
172
+ request,
173
+ requestStream
147
174
  };
148
- //# sourceMappingURL=chunk-N3HU6ONW.js.map
175
+ //# sourceMappingURL=chunk-JS6BTDP5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/errors.ts","../src/core/config.ts","../src/core/http.ts"],"sourcesContent":["/** Base error for all Celesto SDK errors. */\nexport class CelestoError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CelestoError\";\n }\n}\n\n/** Thrown when an API request returns a non-2xx HTTP status. */\nexport class CelestoApiError extends CelestoError {\n readonly status: number;\n readonly data: unknown;\n readonly requestId?: string;\n\n constructor(message: string, status: number, data: unknown, requestId?: string) {\n super(message);\n this.name = \"CelestoApiError\";\n this.status = status;\n this.data = data;\n this.requestId = requestId;\n }\n}\n\n/** Thrown when fetch() itself fails — DNS, network, timeout, abort. */\nexport class CelestoNetworkError extends CelestoError {\n readonly cause?: Error;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = \"CelestoNetworkError\";\n this.cause = cause;\n }\n}\n","export type FetchLike = typeof fetch;\n\nexport interface ClientConfig {\n /** Base API URL, e.g. https://api.celesto.ai */\n baseUrl?: string;\n /** Bearer token (API key or JWT). */\n token?: string;\n /** Alias for token. */\n apiKey?: string;\n /** Organization ID to send as X-Current-Organization. */\n organizationId?: string;\n /** Optional user agent for server-side requests. */\n userAgent?: string;\n /** Default request timeout in milliseconds. */\n timeoutMs?: number;\n /** Override fetch implementation (useful for testing). */\n fetch?: FetchLike;\n /** Default headers to include in every request. */\n headers?: Record<string, string>;\n}\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined | null | (string | number | boolean)[]>;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface RequestOverrides {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface RequestContext {\n fetch: FetchLike;\n baseUrl: string;\n token?: string;\n organizationId?: string;\n userAgent?: string;\n timeoutMs?: number;\n headers?: Record<string, string>;\n}\n\nexport const DEFAULT_BASE_URL = \"https://api.celesto.ai\";\n\nexport const buildRequestContext = (config: ClientConfig): RequestContext => ({\n fetch: config.fetch ?? fetch,\n baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,\n token: config.token ?? config.apiKey,\n organizationId: config.organizationId,\n userAgent: config.userAgent,\n timeoutMs: config.timeoutMs,\n headers: config.headers,\n});\n","import { CelestoApiError, CelestoNetworkError } from \"./errors\";\nimport { RequestContext, RequestOptions } from \"./config\";\n\nconst joinUrl = (baseUrl: string, path: string): string => {\n const trimmedBase = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${trimmedBase}${normalizedPath}`;\n};\n\nconst buildQuery = (\n query?: RequestOptions[\"query\"],\n): string => {\n if (!query) {\n return \"\";\n }\n\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n params.append(key, String(item));\n }\n continue;\n }\n params.set(key, String(value));\n }\n\n const serialized = params.toString();\n return serialized ? `?${serialized}` : \"\";\n};\n\nconst parseResponseBody = async (response: Response): Promise<unknown> => {\n if (response.status === 204) {\n return undefined;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n return response.json();\n }\n\n return response.text();\n};\n\nconst extractErrorMessage = (data: unknown, status: number): string => {\n if (data && typeof data === \"object\") {\n const record = data as Record<string, unknown>;\n if (typeof record.detail === \"string\") {\n return record.detail;\n }\n if (typeof record.message === \"string\") {\n return record.message;\n }\n if (typeof record.error === \"string\") {\n return record.error;\n }\n }\n return `Request failed with status ${status}`;\n};\n\nconst buildRequestInit = (\n ctx: RequestContext,\n options: RequestOptions,\n): { url: string; init: RequestInit } => {\n const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;\n const headers: Record<string, string> = {\n ...(ctx.headers ?? {}),\n ...(options.headers ?? {}),\n };\n\n if (ctx.token) {\n headers.Authorization = `Bearer ${ctx.token}`;\n }\n if (ctx.organizationId) {\n headers[\"X-Current-Organization\"] = ctx.organizationId;\n }\n if (ctx.userAgent && !headers[\"User-Agent\"]) {\n headers[\"User-Agent\"] = ctx.userAgent;\n }\n\n const init: RequestInit = {\n method: options.method,\n headers,\n signal: options.signal,\n };\n if (options.body !== undefined) {\n headers[\"Content-Type\"] = headers[\"Content-Type\"] ?? \"application/json\";\n init.body = headers[\"Content-Type\"].includes(\"application/json\")\n ? JSON.stringify(options.body)\n : (options.body as BodyInit);\n }\n return { url, init };\n};\n\nexport const request = async <T>(ctx: RequestContext, options: RequestOptions): Promise<T> => {\n const { url, init } = buildRequestInit(ctx, options);\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let controller: AbortController | undefined;\n\n if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {\n controller = new AbortController();\n timeoutId = setTimeout(() => controller?.abort(), ctx.timeoutMs);\n init.signal = controller.signal;\n }\n\n try {\n const response = await ctx.fetch(url, init);\n const data = await parseResponseBody(response);\n\n if (!response.ok) {\n const message = extractErrorMessage(data, response.status);\n throw new CelestoApiError(message, response.status, data, response.headers.get(\"x-request-id\") ?? undefined);\n }\n\n return data as T;\n } catch (err) {\n if (err instanceof CelestoApiError) {\n throw err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n throw new CelestoNetworkError(error.message, error);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n};\n\n/** Make an authenticated request without consuming its response body. */\nexport const requestStream = async (\n ctx: RequestContext,\n options: RequestOptions,\n): Promise<Response> => {\n const { url, init } = buildRequestInit(ctx, options);\n try {\n const response = await ctx.fetch(url, init);\n if (!response.ok) {\n const data = await parseResponseBody(response);\n const message = extractErrorMessage(data, response.status);\n throw new CelestoApiError(\n message,\n response.status,\n data,\n response.headers.get(\"x-request-id\") ?? undefined,\n );\n }\n return response;\n } catch (err) {\n if (err instanceof CelestoApiError) {\n throw err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n throw new CelestoNetworkError(error.message, error);\n }\n};\n"],"mappings":";AACO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,kBAAN,cAA8B,aAAa;AAAA,EAKhD,YAAY,SAAiB,QAAgB,MAAe,WAAoB;AAC9E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AACZ,SAAK,YAAY;AAAA,EACnB;AACF;AAGO,IAAM,sBAAN,cAAkC,aAAa;AAAA,EAGpD,YAAY,SAAiB,OAAe;AAC1C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ;AAAA,EACf;AACF;;;ACaO,IAAM,mBAAmB;AAEzB,IAAM,sBAAsB,CAAC,YAA0C;AAAA,EAC5E,OAAO,OAAO,SAAS;AAAA,EACvB,SAAS,OAAO,WAAW;AAAA,EAC3B,OAAO,OAAO,SAAS,OAAO;AAAA,EAC9B,gBAAgB,OAAO;AAAA,EACvB,WAAW,OAAO;AAAA,EAClB,WAAW,OAAO;AAAA,EAClB,SAAS,OAAO;AAClB;;;ACpDA,IAAM,UAAU,CAAC,SAAiB,SAAyB;AACzD,QAAM,cAAc,QAAQ,SAAS,GAAG,IAAI,QAAQ,MAAM,GAAG,EAAE,IAAI;AACnE,QAAM,iBAAiB,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI;AAC7D,SAAO,GAAG,WAAW,GAAG,cAAc;AACxC;AAEA,IAAM,aAAa,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AAe,iBAAiB;AAClC,YAAM;AAAA,IACR;AACA,UAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAChE,UAAM,IAAI,oBAAoB,MAAM,SAAS,KAAK;AAAA,EACpD,UAAE;AACA,QAAI,WAAW;AACb,mBAAa,SAAS;AAAA,IACxB;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB,OAC3B,KACA,YACsB;AACtB,QAAM,EAAE,KAAK,KAAK,IAAI,iBAAiB,KAAK,OAAO;AACnD,MAAI;AACF,UAAM,WAAW,MAAM,IAAI,MAAM,KAAK,IAAI;AAC1C,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,OAAO,MAAM,kBAAkB,QAAQ;AAC7C,YAAM,UAAU,oBAAoB,MAAM,SAAS,MAAM;AACzD,YAAM,IAAI;AAAA,QACR;AAAA,QACA,SAAS;AAAA,QACT;AAAA,QACA,SAAS,QAAQ,IAAI,cAAc,KAAK;AAAA,MAC1C;AAAA,IACF;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,eAAe,iBAAiB;AAClC,YAAM;AAAA,IACR;AACA,UAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAChE,UAAM,IAAI,oBAAoB,MAAM,SAAS,KAAK;AAAA,EACpD;AACF;","names":[]}
@@ -1,7 +1,60 @@
1
1
  import {
2
+ CelestoError,
3
+ CelestoNetworkError,
2
4
  buildRequestContext,
3
- request
4
- } from "./chunk-N3HU6ONW.js";
5
+ request,
6
+ requestStream
7
+ } from "./chunk-JS6BTDP5.js";
8
+
9
+ // src/core/auth.ts
10
+ import { execFile as execFileCallback } from "child_process";
11
+ import { readFile } from "fs/promises";
12
+ import path from "path";
13
+ import { promisify } from "util";
14
+ import { parse } from "dotenv";
15
+ var execFile = promisify(execFileCallback);
16
+ var MISSING_CREDENTIALS_MESSAGE = "No Celesto credentials found. Run pip install celesto && celesto auth login, or export CELESTO_API_KEY.";
17
+ function nonEmpty(value) {
18
+ const trimmed = value?.trim();
19
+ return trimmed ? trimmed : void 0;
20
+ }
21
+ async function readDotEnvApiKey(cwd, readDotEnv) {
22
+ try {
23
+ const contents = await readDotEnv(path.join(cwd, ".env"));
24
+ return nonEmpty(parse(contents).CELESTO_API_KEY);
25
+ } catch {
26
+ return void 0;
27
+ }
28
+ }
29
+ async function loadCliApiKey() {
30
+ try {
31
+ const { stdout } = await execFile("celesto", ["auth", "token"], {
32
+ encoding: "utf8",
33
+ timeout: 5e3,
34
+ maxBuffer: 64 * 1024
35
+ });
36
+ return nonEmpty(stdout);
37
+ } catch {
38
+ return void 0;
39
+ }
40
+ }
41
+ async function resolveCelestoApiKey(options = {}) {
42
+ const env = options.env ?? process.env;
43
+ const environmentKey = nonEmpty(env.CELESTO_API_KEY);
44
+ if (environmentKey) return environmentKey;
45
+ const dotEnvKey = await readDotEnvApiKey(
46
+ options.cwd ?? process.cwd(),
47
+ options.readDotEnv ?? ((filePath) => readFile(filePath, "utf8"))
48
+ );
49
+ if (dotEnvKey) return dotEnvKey;
50
+ return (options.loadSavedApiKey ?? loadCliApiKey)();
51
+ }
52
+ async function resolveClientConfig(config = {}, options = {}) {
53
+ if (nonEmpty(config.token) || nonEmpty(config.apiKey)) return config;
54
+ const apiKey = await resolveCelestoApiKey(options);
55
+ if (!apiKey) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
56
+ return { ...config, token: apiKey };
57
+ }
5
58
 
6
59
  // src/computers/client.ts
7
60
  var toConnection = (payload) => {
@@ -41,11 +94,42 @@ var toComputerInfo = (payload) => ({
41
94
  createdAt: payload.created_at,
42
95
  stoppedAt: payload.stopped_at ?? null
43
96
  });
44
- var toExecResponse = (payload) => ({
97
+ var toExecResponse = (payload) => {
98
+ const response = {
99
+ exitCode: payload.exit_code,
100
+ stdout: payload.stdout,
101
+ stderr: payload.stderr
102
+ };
103
+ if (payload.command_id !== void 0) response.commandId = payload.command_id;
104
+ if (payload.duration_ms !== void 0) response.durationMs = payload.duration_ms;
105
+ if (payload.timed_out !== void 0) response.timedOut = payload.timed_out;
106
+ return response;
107
+ };
108
+ var toCommandHistoryEntry = (payload) => ({
109
+ commandId: payload.command_id,
110
+ source: payload.source,
111
+ status: payload.status,
112
+ startedAt: payload.started_at,
113
+ endedAt: payload.ended_at,
114
+ durationMs: payload.duration_ms,
115
+ timeoutSeconds: payload.timeout_seconds,
45
116
  exitCode: payload.exit_code,
46
- stdout: payload.stdout,
47
- stderr: payload.stderr
117
+ stdoutBytes: payload.stdout_bytes,
118
+ stderrBytes: payload.stderr_bytes,
119
+ errorType: payload.error_type
48
120
  });
121
+ var toTerminalConnectionInfo = (payload) => {
122
+ const separator = payload.gateway_url.includes("?") ? "&" : "?";
123
+ return {
124
+ terminalId: payload.terminal_id,
125
+ gatewayUrl: payload.gateway_url,
126
+ url: `${payload.gateway_url}${separator}token=${encodeURIComponent(payload.token)}`,
127
+ token: payload.token,
128
+ expiresAt: payload.expires_at,
129
+ headers: {},
130
+ firstMessage: ""
131
+ };
132
+ };
49
133
  var toSandboxTemplateInfo = (payload) => ({
50
134
  id: payload.id,
51
135
  displayName: payload.display_name,
@@ -165,11 +249,104 @@ var buildCreateComputerBody = (params) => {
165
249
  }
166
250
  return body;
167
251
  };
168
- var computersPath = (path) => `/v1/computers${path}`;
252
+ var computersPath = (path2) => `/v1/computers${path2}`;
169
253
  var pickOverrides = (options) => ({
170
254
  headers: options?.headers,
171
255
  signal: options?.signal
172
256
  });
257
+ var optionalNumber = (value) => typeof value === "number" ? value : void 0;
258
+ var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
259
+ var parseExecStreamEvent = (value) => {
260
+ if (!value || typeof value !== "object") {
261
+ throw new Error("Celesto returned an invalid command stream event.");
262
+ }
263
+ const event = value;
264
+ if (event.type === "stdout" || event.type === "stderr") {
265
+ if (typeof event.data !== "string") {
266
+ throw new Error("Celesto returned command output without text data.");
267
+ }
268
+ return { type: event.type, data: event.data };
269
+ }
270
+ if (event.type === "started") {
271
+ if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
272
+ throw new Error("Celesto returned an invalid command-start event.");
273
+ }
274
+ return {
275
+ type: "started",
276
+ commandId: event.command_id,
277
+ startedAtUnixMs: event.started_at_unix_ms,
278
+ timeoutSeconds: event.timeout_seconds
279
+ };
280
+ }
281
+ if (event.type === "exit") {
282
+ if (typeof event.exit_code !== "number") {
283
+ throw new Error("Celesto returned an invalid command-exit event.");
284
+ }
285
+ const result = {
286
+ type: "exit",
287
+ exitCode: event.exit_code
288
+ };
289
+ if (typeof event.command_id === "string") result.commandId = event.command_id;
290
+ const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
291
+ const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
292
+ const durationMs = optionalNumber(event.duration_ms);
293
+ const timedOut = optionalBoolean(event.timed_out);
294
+ if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
295
+ if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
296
+ if (durationMs !== void 0) result.durationMs = durationMs;
297
+ if (timedOut !== void 0) result.timedOut = timedOut;
298
+ return result;
299
+ }
300
+ throw new Error("Celesto returned an unknown command stream event.");
301
+ };
302
+ var parseSseDataLine = (line) => {
303
+ const text = line.trim();
304
+ if (!text || !text.startsWith("data:")) {
305
+ return void 0;
306
+ }
307
+ const data = text.slice("data:".length).trim();
308
+ if (!data || data === "[DONE]") {
309
+ return void 0;
310
+ }
311
+ try {
312
+ return parseExecStreamEvent(JSON.parse(data));
313
+ } catch (error) {
314
+ if (error instanceof SyntaxError) {
315
+ throw new Error("Celesto returned malformed JSON in the command stream.");
316
+ }
317
+ throw error;
318
+ }
319
+ };
320
+ var createManagedSignal = (signal, timeoutMs) => {
321
+ if (!timeoutMs || timeoutMs <= 0) {
322
+ return { signal, cleanup: () => {
323
+ } };
324
+ }
325
+ const controller = new AbortController();
326
+ const abort = () => controller.abort();
327
+ if (signal?.aborted) {
328
+ abort();
329
+ } else {
330
+ signal?.addEventListener("abort", abort, { once: true });
331
+ }
332
+ const timer = setTimeout(abort, timeoutMs);
333
+ return {
334
+ signal: controller.signal,
335
+ cleanup: () => {
336
+ clearTimeout(timer);
337
+ signal?.removeEventListener("abort", abort);
338
+ }
339
+ };
340
+ };
341
+ var toNetworkError = (error) => {
342
+ if (error instanceof CelestoNetworkError) return error;
343
+ const cause = error instanceof Error ? error : new Error(String(error));
344
+ return new CelestoNetworkError(cause.message, cause);
345
+ };
346
+ var withFallbackCommandId = (event, commandId) => {
347
+ if (event.type !== "exit" || event.commandId || !commandId) return event;
348
+ return { ...event, commandId };
349
+ };
173
350
  var ComputersClient = class {
174
351
  constructor(config) {
175
352
  this.config = config;
@@ -221,17 +398,113 @@ var ComputersClient = class {
221
398
  return toComputerInfo(data);
222
399
  }
223
400
  async exec(computerId, command, params = {}, options) {
401
+ const ctx = buildRequestContext(this.config);
402
+ const managedSignal = createManagedSignal(
403
+ params.signal ?? options?.signal,
404
+ this.config.timeoutMs
405
+ );
406
+ try {
407
+ const data = await request(ctx, {
408
+ method: "POST",
409
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
410
+ body: {
411
+ command,
412
+ timeout: params.timeout ?? 30
413
+ },
414
+ headers: options?.headers,
415
+ signal: managedSignal.signal
416
+ });
417
+ return toExecResponse(data);
418
+ } finally {
419
+ managedSignal.cleanup();
420
+ }
421
+ }
422
+ async *execStream(computerId, command, params = {}, options) {
423
+ const ctx = buildRequestContext(this.config);
424
+ const managedSignal = createManagedSignal(
425
+ params.signal ?? options?.signal,
426
+ this.config.timeoutMs
427
+ );
428
+ let reader;
429
+ let completed = false;
430
+ try {
431
+ const response = await requestStream(ctx, {
432
+ method: "POST",
433
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
434
+ body: {
435
+ command,
436
+ timeout: params.timeout ?? 30
437
+ },
438
+ headers: options?.headers,
439
+ signal: managedSignal.signal
440
+ });
441
+ if (!response.body) {
442
+ throw new Error("Celesto did not return a command output stream.");
443
+ }
444
+ const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
445
+ reader = response.body.getReader();
446
+ const decoder = new TextDecoder();
447
+ let buffer = "";
448
+ while (true) {
449
+ let chunk;
450
+ try {
451
+ chunk = await reader.read();
452
+ } catch (error) {
453
+ throw toNetworkError(error);
454
+ }
455
+ if (chunk.done) {
456
+ completed = true;
457
+ buffer += decoder.decode();
458
+ break;
459
+ }
460
+ buffer += decoder.decode(chunk.value, { stream: true });
461
+ let newlineIndex = buffer.indexOf("\n");
462
+ while (newlineIndex !== -1) {
463
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
464
+ buffer = buffer.slice(newlineIndex + 1);
465
+ const parsed = parseSseDataLine(line);
466
+ if (parsed) {
467
+ const event = withFallbackCommandId(parsed, responseCommandId);
468
+ yield event;
469
+ if (event.type === "exit") return;
470
+ }
471
+ newlineIndex = buffer.indexOf("\n");
472
+ }
473
+ }
474
+ if (buffer) {
475
+ const parsed = parseSseDataLine(buffer);
476
+ if (parsed) {
477
+ const event = withFallbackCommandId(parsed, responseCommandId);
478
+ yield event;
479
+ if (event.type === "exit") return;
480
+ }
481
+ }
482
+ throw new Error("Command stream ended before Celesto returned an exit status.");
483
+ } finally {
484
+ if (reader) {
485
+ if (!completed) {
486
+ try {
487
+ await reader.cancel();
488
+ } catch {
489
+ }
490
+ }
491
+ reader.releaseLock();
492
+ }
493
+ managedSignal.cleanup();
494
+ }
495
+ }
496
+ async listCommandHistory(computerId, params = {}, options) {
224
497
  const ctx = buildRequestContext(this.config);
225
498
  const data = await request(ctx, {
226
- method: "POST",
227
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
228
- body: {
229
- command,
230
- timeout: params.timeout ?? 30
231
- },
499
+ method: "GET",
500
+ path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
501
+ query: { limit: params.limit },
232
502
  ...pickOverrides(options)
233
503
  });
234
- return toExecResponse(data);
504
+ return {
505
+ commands: data.commands.map(toCommandHistoryEntry),
506
+ count: data.count
507
+ };
235
508
  }
236
509
  async stop(computerId, options) {
237
510
  const ctx = buildRequestContext(this.config);
@@ -288,43 +561,19 @@ var ComputersClient = class {
288
561
  });
289
562
  return toPublishedPortInfo(data);
290
563
  }
291
- /**
292
- * Get connection info for opening a WebSocket terminal session.
293
- *
294
- * Accepts either a computer ID (e.g. `cmp_xxx`) or a human-readable name.
295
- * The name is resolved to the canonical ID via a GET call — the backend's
296
- * WebSocket endpoint does not resolve names on its own.
297
- *
298
- * Returns the URL, headers, and first message needed to open the connection
299
- * with any WebSocket library of your choice.
300
- *
301
- * @example
302
- * ```ts
303
- * const conn = await client.getTerminalConnection("my-computer");
304
- * const ws = new WebSocket(conn.url, { headers: conn.headers });
305
- * ws.on("open", () => ws.send(conn.firstMessage));
306
- * ws.on("message", (data) => process.stdout.write(data));
307
- * ```
308
- */
309
- async getTerminalConnection(computerIdOrName) {
310
- const info = await this.get(computerIdOrName);
564
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
565
+ async createTerminalSession(computerIdOrName, options) {
311
566
  const ctx = buildRequestContext(this.config);
312
- if (!ctx.token) {
313
- throw new Error("A token is required for terminal connections");
314
- }
315
- const wsBase = ctx.baseUrl.replace(/^https:/i, "wss:").replace(/^http:/i, "ws:");
316
- const url = `${wsBase}/v1/computers/${encodeURIComponent(info.id)}/terminal`;
317
- const headers = {
318
- Authorization: `Bearer ${ctx.token}`
319
- };
320
- if (ctx.organizationId) {
321
- headers["X-Current-Organization"] = ctx.organizationId;
322
- }
323
- return {
324
- url,
325
- headers,
326
- firstMessage: JSON.stringify({ token: ctx.token })
327
- };
567
+ const data = await request(ctx, {
568
+ method: "POST",
569
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
570
+ ...pickOverrides(options)
571
+ });
572
+ return toTerminalConnectionInfo(data);
573
+ }
574
+ /** @deprecated Use createTerminalSession(). */
575
+ async getTerminalConnection(computerIdOrName, options) {
576
+ return this.createTerminalSession(computerIdOrName, options);
328
577
  }
329
578
  };
330
579
 
@@ -338,26 +587,26 @@ var Computer = class _Computer {
338
587
  this.info = info;
339
588
  }
340
589
  /** Create a new computer and return an object with methods on it. */
341
- static async create(params = {}, config = defaultConfig()) {
342
- const client = new ComputersClient(config);
590
+ static async create(params = {}, config) {
591
+ const client = new ComputersClient(await resolveClientConfig(config));
343
592
  const info = await client.create(params);
344
593
  return new _Computer(client, info);
345
594
  }
346
595
  /** Load an existing computer by name or ID. */
347
- static async get(computerIdOrName, config = defaultConfig()) {
348
- const client = new ComputersClient(config);
596
+ static async get(computerIdOrName, config) {
597
+ const client = new ComputersClient(await resolveClientConfig(config));
349
598
  const info = await client.get(computerIdOrName);
350
599
  return new _Computer(client, info);
351
600
  }
352
601
  /** List computers in the current account. */
353
- static async list(params = {}, config = defaultConfig()) {
354
- const client = new ComputersClient(config);
602
+ static async list(params = {}, config) {
603
+ const client = new ComputersClient(await resolveClientConfig(config));
355
604
  const response = await client.list(params);
356
605
  return response.computers.map((info) => new _Computer(client, info));
357
606
  }
358
607
  /** List available computer templates. */
359
- static async listTemplates(config = defaultConfig()) {
360
- const client = new ComputersClient(config);
608
+ static async listTemplates(config) {
609
+ const client = new ComputersClient(await resolveClientConfig(config));
361
610
  return client.listTemplates();
362
611
  }
363
612
  /** Wrap an existing API response in the convenience object. */
@@ -427,6 +676,26 @@ var Computer = class _Computer {
427
676
  async exec(command, params = {}) {
428
677
  return this.run(command, params);
429
678
  }
679
+ /** Run a shell command and stream output and exit events as they arrive. */
680
+ runStream(command, params = {}) {
681
+ return this.client.execStream(this.id, command, params);
682
+ }
683
+ /** Alias for runStream(). */
684
+ execStream(command, params = {}) {
685
+ return this.runStream(command, params);
686
+ }
687
+ /** List recent commands executed on this computer. */
688
+ async listCommandHistory(params = {}) {
689
+ return this.client.listCommandHistory(this.id, params);
690
+ }
691
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
692
+ async createTerminalSession() {
693
+ return this.client.createTerminalSession(this.id);
694
+ }
695
+ /** @deprecated Use createTerminalSession(). */
696
+ async getTerminalConnection() {
697
+ return this.createTerminalSession();
698
+ }
430
699
  /** Stop this computer and update the local data. */
431
700
  async stop() {
432
701
  this.info = await this.client.stop(this.id);
@@ -470,6 +739,9 @@ var Computer = class _Computer {
470
739
  };
471
740
 
472
741
  export {
742
+ MISSING_CREDENTIALS_MESSAGE,
743
+ resolveCelestoApiKey,
744
+ resolveClientConfig,
473
745
  Computer
474
746
  };
475
- //# sourceMappingURL=chunk-LPTIN7LO.js.map
747
+ //# sourceMappingURL=chunk-XNTZDOKY.js.map