@keska/sandbox 0.49.0 → 0.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -5315,6 +5315,16 @@ declare class GuestHttp$1 {
5315
5315
  websocket(path?: string): Promise<WebSocket>;
5316
5316
  }
5317
5317
 
5318
+ /** Exchange a login JWT for one Matrix device. The homeserver follows the control plane. */
5319
+ /** One Matrix access token. It is one device for one person. */
5320
+ type MatrixToken = {
5321
+ accessToken: string;
5322
+ userId: string;
5323
+ deviceId: string;
5324
+ expiresAt: string;
5325
+ homeserver: string;
5326
+ };
5327
+
5318
5328
  type TimeoutOpts = {
5319
5329
  timeout?: number;
5320
5330
  signal?: AbortSignal;
@@ -6066,12 +6076,12 @@ declare class Sandbox$1 {
6066
6076
  missingOk?: boolean;
6067
6077
  signal?: AbortSignal;
6068
6078
  }): Promise<void>;
6069
- /** Named pin of the writable layer. Sleeps if Ready/Finished, pins, then wakes. */
6079
+ /** Named pin of the writable layer. The sandbox must already be sleeping. Call `sleep()` first. */
6070
6080
  snapshot(opts?: {
6071
6081
  name?: string;
6072
6082
  labels?: Record<string, string>;
6073
6083
  }): Promise<Snapshot>;
6074
- /** SDK glue: guest snap + N Create({ fromSnapshotId }). Not CreateMany. */
6084
+ /** SDK glue: guest snap + N Create({ fromSnapshotId }). Not CreateMany. The sandbox must already be sleeping. Call `sleep()` first. */
6075
6085
  clone(n?: number, opts?: {
6076
6086
  concurrency?: number;
6077
6087
  }): Promise<Sandbox$1[]>;
@@ -6299,6 +6309,7 @@ declare class Agents {
6299
6309
  create(name: string, opts?: {
6300
6310
  template?: string;
6301
6311
  messaging?: boolean;
6312
+ user?: User | string;
6302
6313
  userId?: string;
6303
6314
  displayName?: string;
6304
6315
  timeout?: Timeout;
@@ -6360,6 +6371,13 @@ declare class User {
6360
6371
  newToken(opts?: {
6361
6372
  timeout?: Timeout;
6362
6373
  }): Promise<LoginToken>;
6374
+ /**
6375
+ * Matrix access token for this person.
6376
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
6377
+ */
6378
+ matrixToken(opts?: {
6379
+ deviceId?: string;
6380
+ }): Promise<MatrixToken>;
6363
6381
  /** Sign this person out of every device. */
6364
6382
  revoke(opts?: {
6365
6383
  timeout?: Timeout;
@@ -6431,6 +6449,13 @@ declare class Client {
6431
6449
  newToken(opts?: {
6432
6450
  timeout?: Timeout;
6433
6451
  }): Promise<LoginToken>;
6452
+ /**
6453
+ * Matrix access token for the API caller.
6454
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
6455
+ */
6456
+ matrixToken(opts?: {
6457
+ deviceId?: string;
6458
+ }): Promise<MatrixToken>;
6434
6459
  /** Close the connection. */
6435
6460
  close(): void;
6436
6461
  /** `using` calls this. */
@@ -6867,14 +6892,11 @@ declare class Sandbox {
6867
6892
  private exec;
6868
6893
  /** Run one shell string with `/bin/sh -c`. */
6869
6894
  sh(command: string, opts?: Parameters<Sandbox["run"]>[1]): Promise<ExecResult>;
6870
- /** Start a command and return its handle. Omit `timeout` for no RPC deadline. */
6895
+ /** Start a command and return its handle. The process runs until it exits. */
6871
6896
  start(argv: string[], opts?: {
6872
6897
  env?: Record<string, string>;
6873
6898
  cwd?: string;
6874
- timeout?: Timeout;
6875
6899
  name?: string;
6876
- keepAlive?: boolean;
6877
- endsSandbox?: boolean;
6878
6900
  }): Promise<ProcessHandle>;
6879
6901
  /** Copy this sandbox's writable layer into new sandboxes. */
6880
6902
  clone(opts?: {
@@ -7045,4 +7067,4 @@ type GuestResponse = GuestResponse$1;
7045
7067
 
7046
7068
  declare const publicExports: readonly ["Agent", "Template", "AuthenticationError", "CapacityError", "Client", "CommandFailedError", "CommandTimeoutError", "CommandTooLargeError", "ConflictError", "DirectoryNotEmptyError", "ExecutableNotFoundError", "FileExistsError", "FileTooLargeError", "GuestRuntimeDeadError", "ImageTimeoutError", "InvalidArgumentError", "InvalidPathError", "Mkdir", "UNLIMITED", "NameTakenError", "NotFoundError", "Page", "PathNotFoundError", "PageExhaustedError", "PermissionDeniedError", "PortNotOpenError", "ProcessHandle", "Profile", "ResourceInUseError", "ResourcePolicy", "SecurityPolicy", "ProcessNotFoundError", "ProcessWaitTimeoutError", "Remove", "Sandbox", "SandboxConflictError", "SandboxError", "SandboxNotFoundError", "SandboxNotReadyError", "SandboxSleepingError", "SandboxStateError", "LogStream", "SandboxStatus", "SandboxWaitTimeoutError", "SandboxTimeoutError", "TimeoutError", "UnavailableError", "Write", "mkdir", "publicExports", "remove", "write"];
7047
7069
 
7048
- export { Agent, AuthenticationError, CapacityError, Client, type ClientOptions, CommandFailedError, CommandTimeoutError, CommandTooLargeError, ConflictError, DirectoryNotEmptyError, type ExecBytesResult, type ExecResult, ExecutableNotFoundError, FileExistsError, type FileInfo, type FileList, FileTooLargeError, type GuestHttp, type GuestResponse, GuestRuntimeDeadError, type HTTPGrant, type Image, type ImageKind, ImageTimeoutError, InvalidArgumentError, InvalidPathError, type LogEntry, LogStream, Mkdir, NameTakenError, NotFoundError, Page, PageExhaustedError, PathNotFoundError, PermissionDeniedError, PortNotOpenError, type Process, ProcessHandle, ProcessNotFoundError, ProcessWaitTimeoutError, Profile, Remove, ResourceInUseError, ResourcePolicy, type Resources, Sandbox, SandboxConflictError, type SandboxCreateParams, SandboxError, type SandboxInfo, SandboxNotFoundError, SandboxNotReadyError, type SandboxRow, SandboxSleepingError, SandboxStateError, SandboxStatus, SandboxTimeoutError, SandboxWaitTimeoutError, type Secret, SecurityPolicy, type Snapshot, type StreamChunk, Template, TimeoutError, UNLIMITED, UnavailableError, type Volume, Write, mkdir, publicExports, remove, write };
7070
+ export { Agent, AuthenticationError, CapacityError, Client, type ClientOptions, CommandFailedError, CommandTimeoutError, CommandTooLargeError, ConflictError, DirectoryNotEmptyError, type ExecBytesResult, type ExecResult, ExecutableNotFoundError, FileExistsError, type FileInfo, type FileList, FileTooLargeError, type GuestHttp, type GuestResponse, GuestRuntimeDeadError, type HTTPGrant, type Image, type ImageKind, ImageTimeoutError, InvalidArgumentError, InvalidPathError, type LogEntry, LogStream, type MatrixToken, Mkdir, NameTakenError, NotFoundError, Page, PageExhaustedError, PathNotFoundError, PermissionDeniedError, PortNotOpenError, type Process, ProcessHandle, ProcessNotFoundError, ProcessWaitTimeoutError, Profile, Remove, ResourceInUseError, ResourcePolicy, type Resources, Sandbox, SandboxConflictError, type SandboxCreateParams, SandboxError, type SandboxInfo, SandboxNotFoundError, SandboxNotReadyError, type SandboxRow, SandboxSleepingError, SandboxStateError, SandboxStatus, SandboxTimeoutError, SandboxWaitTimeoutError, type Secret, SecurityPolicy, type Snapshot, type StreamChunk, Template, TimeoutError, UNLIMITED, UnavailableError, type Volume, Write, mkdir, publicExports, remove, write };
package/dist/index.js CHANGED
@@ -1343,15 +1343,46 @@ function resolveBaseUrl(explicit, credentialApiUrl = "") {
1343
1343
  }
1344
1344
  return DEFAULT_BASE_URL;
1345
1345
  }
1346
+ function labForwardBase(cpUrl) {
1347
+ let parsed;
1348
+ try {
1349
+ parsed = new URL(cpUrl);
1350
+ } catch {
1351
+ return "";
1352
+ }
1353
+ const host = parsed.hostname.toLowerCase();
1354
+ const scheme = parsed.protocol.replace(/:$/u, "") || "http";
1355
+ if ((host === "127.0.0.1" || host === "localhost") && parsed.port === "18080") {
1356
+ return `${scheme}://${host}:18082`;
1357
+ }
1358
+ return "";
1359
+ }
1346
1360
  function resolveForwardBaseUrl(cpUrl = "") {
1347
1361
  const explicit = (process.env.NUMEN_FORWARD_BASE_URL ?? "").trim();
1348
1362
  if (explicit) {
1349
1363
  return explicit.replace(/\/$/u, "");
1350
1364
  }
1351
- if (cpUrl.includes("keska.dev")) {
1365
+ const cp = cpUrl.trim();
1366
+ if (!cp) {
1367
+ return DEFAULT_FORWARD_BASE_URL;
1368
+ }
1369
+ const lab = labForwardBase(cp);
1370
+ if (lab) {
1371
+ return lab;
1372
+ }
1373
+ let host = "";
1374
+ try {
1375
+ host = new URL(cp).hostname.toLowerCase();
1376
+ } catch {
1377
+ host = "";
1378
+ }
1379
+ if (host === "keska.io" || host.endsWith(".keska.io")) {
1380
+ return DEFAULT_FORWARD_BASE_URL;
1381
+ }
1382
+ if (host === "keska.dev" || host.endsWith(".keska.dev")) {
1352
1383
  return "https://sbx.keska.dev";
1353
1384
  }
1354
- return DEFAULT_FORWARD_BASE_URL;
1385
+ throw new Error(`no guest URL for ${cp}. Set NUMEN_FORWARD_BASE_URL.`);
1355
1386
  }
1356
1387
  function guestOrigin(base, sandboxId, port, scheme) {
1357
1388
  const parsed = new URL(base);
@@ -4122,6 +4153,73 @@ var Client = class {
4122
4153
  }
4123
4154
  };
4124
4155
 
4156
+ // src/matrixToken.ts
4157
+ var TOKEN_MS = 36e5;
4158
+ var HOMESERVERS = {
4159
+ "numenbox.keska.dev": "https://numen-matrix.keska.dev",
4160
+ "numenbox.keska.io": "https://numen-matrix.keska.io"
4161
+ };
4162
+ function matrixHomeserver(baseUrl) {
4163
+ let host = "";
4164
+ try {
4165
+ host = new URL(baseUrl).hostname;
4166
+ } catch {
4167
+ host = "";
4168
+ }
4169
+ const homeserver = HOMESERVERS[host];
4170
+ if (!homeserver) {
4171
+ throw new InvalidArgumentError(`no matrix homeserver for ${host || baseUrl}`, {
4172
+ code: "invalid_argument",
4173
+ reason: "HOMESERVER_UNKNOWN"
4174
+ });
4175
+ }
4176
+ return homeserver;
4177
+ }
4178
+ async function openMatrixToken(baseUrl, mint, opts, doFetch = fetch) {
4179
+ const homeserver = matrixHomeserver(baseUrl);
4180
+ const deviceId = opts?.deviceId || crypto.randomUUID();
4181
+ const jwt = await mint();
4182
+ const url = `${homeserver}/_matrix/client/v3/login`;
4183
+ let res;
4184
+ try {
4185
+ res = await doFetch(url, {
4186
+ method: "POST",
4187
+ headers: { "content-type": "application/json" },
4188
+ body: JSON.stringify({ type: "org.matrix.login.jwt", token: jwt, device_id: deviceId })
4189
+ });
4190
+ } catch (error) {
4191
+ throw new SandboxError(`matrix login ${error instanceof Error ? error.message : "failed"}`, {
4192
+ code: "unavailable",
4193
+ reason: "UNAVAILABLE"
4194
+ });
4195
+ }
4196
+ if (res.status === 401 || res.status === 403) {
4197
+ throw new AuthenticationError("matrix login refused", { code: "unauthenticated", reason: "UNAUTHENTICATED" });
4198
+ }
4199
+ if (!res.ok) throw new SandboxError(`matrix login ${res.status}`);
4200
+ const body = await res.json();
4201
+ if (!body.access_token || !body.user_id) {
4202
+ throw new AuthenticationError("matrix login returned no token", {
4203
+ code: "unauthenticated",
4204
+ reason: "UNAUTHENTICATED"
4205
+ });
4206
+ }
4207
+ if (body.device_id && body.device_id !== deviceId) {
4208
+ throw new AuthenticationError("matrix login changed the device", {
4209
+ code: "unauthenticated",
4210
+ reason: "UNAUTHENTICATED"
4211
+ });
4212
+ }
4213
+ const expiresInMs = body.expires_in_ms ?? TOKEN_MS;
4214
+ return {
4215
+ accessToken: body.access_token,
4216
+ userId: body.user_id,
4217
+ deviceId,
4218
+ expiresAt: new Date(Date.now() + expiresInMs).toISOString(),
4219
+ homeserver
4220
+ };
4221
+ }
4222
+
4125
4223
  // src/sandbox.ts
4126
4224
  import { createWriteStream as createWriteStream2, lstatSync } from "fs";
4127
4225
  import { rename as rename2, unlink as unlink2 } from "fs/promises";
@@ -5167,31 +5265,12 @@ var Sandbox = class _Sandbox {
5167
5265
  throw error;
5168
5266
  }
5169
5267
  }
5170
- /** Named pin of the writable layer. Sleeps if Ready/Finished, pins, then wakes. */
5268
+ /** Named pin of the writable layer. The sandbox must already be sleeping. Call `sleep()` first. */
5171
5269
  async snapshot(opts) {
5172
5270
  await this.get();
5173
- let sleeping = false;
5174
- if (this.status === "Ready" || this.status === "Finished") {
5175
- await this.sleep();
5176
- sleeping = true;
5177
- }
5178
- let snap;
5179
- try {
5180
- snap = await waitOverlayPublished(
5181
- () => this.wire.createSnapshot(this.id, { name: opts?.name, labels: opts?.labels })
5182
- );
5183
- } catch (error) {
5184
- if (sleeping) {
5185
- await this.wake().catch(() => void 0);
5186
- }
5187
- throw error;
5188
- }
5189
- if (sleeping) {
5190
- await this.wake();
5191
- }
5192
- return snap;
5271
+ return waitOverlayPublished(() => this.wire.createSnapshot(this.id, { name: opts?.name, labels: opts?.labels }));
5193
5272
  }
5194
- /** SDK glue: guest snap + N Create({ fromSnapshotId }). Not CreateMany. */
5273
+ /** SDK glue: guest snap + N Create({ fromSnapshotId }). Not CreateMany. The sandbox must already be sleeping. Call `sleep()` first. */
5195
5274
  async clone(n = 1, opts) {
5196
5275
  if (n < 1) {
5197
5276
  throw new InvalidArgumentError("clone: n must be >= 1", { code: "invalid_argument", reason: "CLONE" });
@@ -5669,10 +5748,12 @@ var Agents2 = class {
5669
5748
  client;
5670
5749
  templates;
5671
5750
  create(name, opts) {
5751
+ const bound = opts?.user;
5752
+ const userId = typeof bound === "string" ? bound : bound instanceof User ? bound.id : opts?.userId;
5672
5753
  return this.client.wire.agents.create(name, {
5673
5754
  template: opts?.template,
5674
5755
  messaging: opts?.messaging,
5675
- userId: opts?.userId,
5756
+ userId,
5676
5757
  displayName: opts?.displayName,
5677
5758
  timeout: timeoutSeconds(opts?.timeout)
5678
5759
  }).then((info) => new Agent(this.client, info));
@@ -5795,6 +5876,13 @@ var User = class {
5795
5876
  () => this.client.wire.tokens.create(this.id, { timeout: timeoutSeconds(opts?.timeout) })
5796
5877
  );
5797
5878
  }
5879
+ /**
5880
+ * Matrix access token for this person.
5881
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
5882
+ */
5883
+ matrixToken(opts) {
5884
+ return openMatrixToken(this.client.wire.baseUrl, async () => (await this.newToken()).token, opts);
5885
+ }
5798
5886
  /** Sign this person out of every device. */
5799
5887
  revoke(opts) {
5800
5888
  return retry(
@@ -5909,6 +5997,13 @@ var Client2 = class {
5909
5997
  newToken(opts) {
5910
5998
  return retry(this, () => this.wire.newToken({ timeout: timeoutSeconds(opts?.timeout) }));
5911
5999
  }
6000
+ /**
6001
+ * Matrix access token for the API caller.
6002
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
6003
+ */
6004
+ matrixToken(opts) {
6005
+ return openMatrixToken(this.wire.baseUrl, async () => (await this.newToken()).token, opts);
6006
+ }
5912
6007
  /** Close the connection. */
5913
6008
  close() {
5914
6009
  this.wire.close();
@@ -6647,15 +6742,12 @@ var Sandbox2 = class _Sandbox {
6647
6742
  sh(command, opts) {
6648
6743
  return this.run(["/bin/sh", "-c", command], opts);
6649
6744
  }
6650
- /** Start a command and return its handle. Omit `timeout` for no RPC deadline. */
6745
+ /** Start a command and return its handle. The process runs until it exits. */
6651
6746
  async start(argv, opts) {
6652
6747
  const inner = await this.inner.start(argv, {
6653
6748
  env: opts?.env,
6654
6749
  cwd: opts?.cwd,
6655
- timeout: timeoutSeconds(opts?.timeout, UNLIMITED),
6656
- serviceName: opts?.name,
6657
- holdsIdle: opts?.keepAlive,
6658
- endsSandbox: opts?.endsSandbox
6750
+ serviceName: opts?.name
6659
6751
  });
6660
6752
  return new ProcessHandle2(this, inner);
6661
6753
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keska/sandbox",
3
- "version": "0.49.0",
3
+ "version": "0.50.1",
4
4
  "description": "TypeScript client for the Numen sandbox API",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",