runcloud 0.1.106 → 0.1.108

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.
@@ -99,7 +99,7 @@ export function consumeSimulatorLogSse(raw) {
99
99
  function writeSimulatorLogEntry(entry, json) {
100
100
  console.log(json ? JSON.stringify(entry) : entry.message);
101
101
  }
102
- function parseLabels(labels) {
102
+ function parseTags(labels) {
103
103
  const out = {};
104
104
  for (const raw of labels ?? []) {
105
105
  const idx = raw.indexOf('=');
@@ -307,7 +307,7 @@ async function createSimulatorSession(platform, opts) {
307
307
  model: opts.model,
308
308
  region: opts.region,
309
309
  displayName: opts.displayName,
310
- labels: parseLabels(opts.label),
310
+ tags: parseTags(opts.label),
311
311
  installAssets,
312
312
  inactivityTimeout: opts.inactivityTimeout,
313
313
  hardTimeout: opts.hardTimeout,
@@ -263,6 +263,33 @@ function secretSelector(opts) {
263
263
  function collectRepeatable(value, previous) {
264
264
  return [...previous, value];
265
265
  }
266
+ export function parseTagPairs(values) {
267
+ return values.map((raw) => {
268
+ const at = raw.indexOf('=');
269
+ if (at <= 0) {
270
+ throw new Error(`--tag must be key=value (got ${JSON.stringify(raw)})`);
271
+ }
272
+ return [raw.slice(0, at), raw.slice(at + 1)];
273
+ });
274
+ }
275
+ export async function resolveSandboxByTag(api, tags) {
276
+ if (tags.length === 0) {
277
+ throw new Error('Provide a sandbox id, or --tag key=value to find one.');
278
+ }
279
+ const query = new URLSearchParams();
280
+ for (const [key, value] of parseTagPairs(tags))
281
+ query.append('tag', `${key}:${value}`);
282
+ const data = await api.get(`/run-cloud/sandboxes?${query}`);
283
+ const items = data?.items ?? [];
284
+ if (items.length === 0) {
285
+ throw new Error(`No sandbox matches ${tags.join(' ')}.`);
286
+ }
287
+ if (items.length > 1) {
288
+ const listed = items.map((s) => ` ${s.id}${s.name ? ` ${s.name}` : ''}`).join('\n');
289
+ throw new Error(`${items.length} sandboxes match ${tags.join(' ')} — narrow it, or pass an id:\n${listed}`);
290
+ }
291
+ return items[0].id;
292
+ }
266
293
  export function registerSandbox(program) {
267
294
  const sandbox = program.command('sandbox').description('Spawn and control microVM sandboxes');
268
295
  const defaultHelp = new Help();
@@ -362,12 +389,16 @@ export function registerSandbox(program) {
362
389
  .command('list')
363
390
  .description('List sandboxes')
364
391
  .option('--state <state>', 'filter by state')
365
- .option('--name <name>', 'filter by name (exact)')).action((opts) => run(async () => {
392
+ .option('--name <name>', 'filter by name (exact)')
393
+ .option('--tag <key=value>', 'filter by tag; repeatable, and a sandbox must carry every one', collectRepeatable, [])).action((opts) => run(async () => {
366
394
  const query = new URLSearchParams();
367
395
  if (opts.state)
368
396
  query.set('state', opts.state);
369
397
  if (opts.name)
370
398
  query.set('name', opts.name);
399
+ for (const [key, value] of parseTagPairs(opts.tag ?? [])) {
400
+ query.append('tag', `${key}:${value}`);
401
+ }
371
402
  const qs = query.size ? `?${query}` : '';
372
403
  const api = runCloudApi();
373
404
  const [data, boxes] = await Promise.all([
@@ -384,6 +415,23 @@ export function registerSandbox(program) {
384
415
  else
385
416
  console.log(renderSandboxList(items));
386
417
  }));
418
+ withOutput(sandbox
419
+ .command('tag')
420
+ .description('Set or remove tags on a sandbox')
421
+ .argument('<id>', 'sandbox id')
422
+ .argument('<pairs...>', 'key=value to set, or key= to remove')).action((id, pairs, opts) => run(async () => {
423
+ const tags = Object.fromEntries(parseTagPairs(pairs).map(([key, value]) => [key, value === '' ? null : value]));
424
+ const updated = await runCloudApi().patch(`/run-cloud/sandboxes/${encodeURIComponent(id)}/tags`, { tags });
425
+ if (opts.json)
426
+ printJson(updated);
427
+ else {
428
+ const applied = (updated?.tags ?? {});
429
+ const entries = Object.entries(applied);
430
+ console.log(entries.length === 0
431
+ ? `${id} now has no tags`
432
+ : `${id}\n${entries.map(([k, v]) => ` ${k}=${v}`).join('\n')}`);
433
+ }
434
+ }));
387
435
  withOutput(sandbox
388
436
  .command('get')
389
437
  .description('Inspect a sandbox, including its public hostname when exposed')
@@ -497,15 +545,17 @@ export function registerSandbox(program) {
497
545
  sandbox
498
546
  .command('shell')
499
547
  .description('Open an interactive shell (resumes paused sandboxes)')
500
- .argument('<id>', 'sandbox id')
501
- .action((id) => run(async () => {
548
+ .argument('[id]', 'sandbox id; omit when using --tag')
549
+ .option('--tag <key=value>', 'find the sandbox by tag instead of id; repeatable, must match exactly one', collectRepeatable, [])
550
+ .action((id, opts) => run(async () => {
502
551
  const credentials = requireCredentials();
503
552
  const api = new ApiClient(credentials.apiUrl, credentials.token);
504
- await prepareSandboxShell(api, id);
553
+ const sandboxId = id ?? (await resolveSandboxByTag(api, opts.tag ?? []));
554
+ await prepareSandboxShell(api, sandboxId);
505
555
  process.exitCode = await runSandboxShell({
506
556
  apiUrl: credentials.apiUrl,
507
557
  token: credentials.token,
508
- sandboxId: id,
558
+ sandboxId,
509
559
  });
510
560
  }));
511
561
  for (const lifecycle of [
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = '0.1.106';
1
+ export const CLI_VERSION = '0.1.108';
@@ -71,9 +71,14 @@ function escapeHtml(value) {
71
71
  .replaceAll('>', '&gt;');
72
72
  }
73
73
 
74
+ function scriptData(value) {
75
+ return JSON.stringify(value).replaceAll('<', '\\u003c');
76
+ }
77
+
74
78
  function embedUrl(value) {
75
79
  const url = new URL(value);
76
80
  url.searchParams.set('embed', '1');
81
+ url.searchParams.set('loadingGuard', '1');
77
82
  return url.toString();
78
83
  }
79
84
 
@@ -130,6 +135,7 @@ export function mosaicViewerHtml(sessions, deadline = Date.now() + DEMO_LEASE_MS
130
135
  const deadline = ${deadline};
131
136
  const tiles = [...document.querySelectorAll('.tile')];
132
137
  const frames = [...document.querySelectorAll('iframe')];
138
+ const frameOrigins = ${scriptData(sessions.map((session) => new URL(session.url).origin))};
133
139
  const ready = new Set();
134
140
  const count = document.querySelector('#ready-count');
135
141
  const timer = document.querySelector('#timer');
@@ -141,7 +147,12 @@ export function mosaicViewerHtml(sessions, deadline = Date.now() + DEMO_LEASE_MS
141
147
  setInterval(tick, 250);
142
148
  window.addEventListener('message', (event) => {
143
149
  const index = frames.findIndex((frame) => frame.contentWindow === event.source);
144
- if (index < 0 || !event.data || typeof event.data !== 'object') return;
150
+ if (
151
+ index < 0
152
+ || event.origin !== frameOrigins[index]
153
+ || !event.data
154
+ || typeof event.data !== 'object'
155
+ ) return;
145
156
  if (event.data.type === 'ios-simulator:status' && event.data.streaming === true) {
146
157
  ready.add(index);
147
158
  tiles[index].dataset.ready = 'true';
@@ -35,8 +35,11 @@ test('renders eight signed embeds without printing them into the viewer URL', as
35
35
  }));
36
36
  const html = mosaicViewerHtml(sessions, 601_000);
37
37
  assert.equal((html.match(/<iframe /g) || []).length, 8);
38
- assert.match(html, /embed=1/);
39
- assert.doesNotMatch(html, /loadingGuard=1/);
38
+ assert.equal((html.match(/embed=1/g) || []).length, 8);
39
+ assert.equal((html.match(/loadingGuard=1/g) || []).length, 8);
40
+ assert.match(html, /const frameOrigins = \["https:\/\/sim\.example"/);
41
+ assert.match(html, /frame\.contentWindow === event\.source/);
42
+ assert.match(html, /event\.origin !== frameOrigins\[index\]/);
40
43
  assert.match(html, /const deadline = 601000/);
41
44
 
42
45
  const viewer = await startMosaicViewer(sessions, 601_000);
@@ -87,6 +87,7 @@ function scriptData(value) {
87
87
  function embedUrl(value) {
88
88
  const url = new URL(value);
89
89
  url.searchParams.set('embed', '1');
90
+ url.searchParams.set('loadingGuard', '1');
90
91
  return url.toString();
91
92
  }
92
93
 
@@ -193,6 +194,7 @@ export function cameraViewerHtml(sessions, duration, roomId, now = Date.now()) {
193
194
  const deadline = ${deadline};
194
195
  const devices = [...document.querySelectorAll('.device')];
195
196
  const frames = [...document.querySelectorAll('iframe')];
197
+ const frameOrigins = ${scriptData(sessions.map((session) => new URL(session.url).origin))};
196
198
  const ready = new Set();
197
199
  const count = document.querySelector('#ready-count');
198
200
  const timer = document.querySelector('#timer');
@@ -287,7 +289,12 @@ export function cameraViewerHtml(sessions, duration, roomId, now = Date.now()) {
287
289
  setInterval(tick, 250);
288
290
  window.addEventListener('message', (event) => {
289
291
  const index = frames.findIndex((frame) => frame.contentWindow === event.source);
290
- if (index < 0 || !event.data || typeof event.data !== 'object') return;
292
+ if (
293
+ index < 0
294
+ || event.origin !== frameOrigins[index]
295
+ || !event.data
296
+ || typeof event.data !== 'object'
297
+ ) return;
291
298
  if (event.data.type === 'ios-simulator:status' && event.data.streaming === true) {
292
299
  ready.add(index);
293
300
  devices[index].dataset.ready = 'true';
@@ -67,8 +67,11 @@ test('renders three signed embeds while keeping credentials out of the local URL
67
67
  const demoSessions = sessions();
68
68
  const html = cameraViewerHtml(demoSessions, 60, 'room-12345678', 1_000);
69
69
  assert.equal((html.match(/<iframe /g) || []).length, 3);
70
- assert.match(html, /embed=1/);
71
- assert.doesNotMatch(html, /loadingGuard=1/);
70
+ assert.equal((html.match(/embed=1/g) || []).length, 3);
71
+ assert.equal((html.match(/loadingGuard=1/g) || []).length, 3);
72
+ assert.match(html, /const frameOrigins = \["https:\/\/sim\.example"/);
73
+ assert.match(html, /frame\.contentWindow === event\.source/);
74
+ assert.match(html, /event\.origin !== frameOrigins\[index\]/);
72
75
  assert.match(html, /Connect webcam/);
73
76
  assert.match(html, /com\.apple\.mobilesafari/);
74
77
  assert.match(html, /audio: false/);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runcloud",
3
- "version": "0.1.106",
3
+ "version": "0.1.108",
4
4
  "description": "Create and control run.cloud remote mobile simulators and cloud sandboxes",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -134,7 +134,7 @@ import { Client } from "@run-cloud/sdk";
134
134
  const cloud = new Client();
135
135
  const session = await cloud.ios.create({
136
136
  displayName: "Agent smoke",
137
- labels: { owner: "agent" },
137
+ tags: { owner: "agent" },
138
138
  inactivityTimeout: "60s",
139
139
  hardTimeout: "10m",
140
140
  codec: "auto",
@@ -159,7 +159,7 @@ The mobile SDK surface is:
159
159
  `delete`
160
160
  - `cloud.assets`: `upload`, `list`, `delete`
161
161
 
162
- Create options include `model`, `region`, `displayName`, `labels`,
162
+ Create options include `model`, `region`, `displayName`, `tags`,
163
163
  `installAssets`, `inactivityTimeout`, `hardTimeout`, and `codec`.
164
164
 
165
165
  Do not invent SDK methods for scripted taps, typing, recording, app lifecycle,
@@ -180,10 +180,13 @@ Delete uploaded assets when they are no longer needed.
180
180
 
181
181
  ## Embed a Session
182
182
 
183
+ - In React, use `RemoteControl` from `@runcloud/ui` with the signed session URL.
183
184
  - Add `embed=1` to the signed session URL for the clean iframe UI.
184
185
  - Add `loadingGuard=1` when the iframe should block interaction until streaming
185
186
  and app launch are ready.
186
- - Verify `event.source` is the expected iframe before processing messages.
187
+ - For raw iframes, verify both `event.source` and the exact signed-URL origin
188
+ before processing messages, and use that exact origin as the command
189
+ `postMessage` target.
187
190
  - Handle `ios-simulator:status`, `ios-simulator:auth-error`,
188
191
  `ios-simulator:session-ended`, and
189
192
  `ios-simulator:session-restart-requested`.
@@ -204,6 +204,76 @@ signed browser desktop. The CLI also provides `screenshot`, `click`, `type`,
204
204
  and `key` subcommands for explicit pixel-coordinate automation. Keep signed
205
205
  desktop URLs private and inspect each subcommand's help before automation.
206
206
 
207
+ ## Tag Sandboxes, and Find Them Again
208
+
209
+ Tags are arbitrary `key=value` metadata on a lease. They are how an operator
210
+ gets from a symptom back to the machine that caused it, and they **outlive the
211
+ sandbox** — so "which sandbox ran this?" is still answerable after the VM is
212
+ gone, which is usually when you are asking.
213
+
214
+ Tag on create, or on an existing sandbox:
215
+
216
+ ```bash
217
+ runcloud sandbox create --image runcloud/agent-base # then:
218
+ runcloud sandbox tag sbx_123 newly.run=run-42 owner=qasim
219
+ runcloud sandbox tag sbx_123 owner= # empty value removes the key
220
+ ```
221
+
222
+ Find by tag — repeatable, and a sandbox must carry every one:
223
+
224
+ ```bash
225
+ runcloud sandbox list --tag newly.run=run-42 --json
226
+ runcloud sandbox shell --tag newly.run=run-42 # resolves, then opens a shell
227
+ ```
228
+
229
+ `shell --tag` refuses to guess: no match and several matches are both errors,
230
+ and the ambiguous case lists what it found. Opening a shell on the wrong
231
+ machine is worse than being told to be precise.
232
+
233
+ Reserved keys the platform sets itself — do not overwrite them:
234
+
235
+ | key | meaning |
236
+ | --- | --- |
237
+ | `newly.kind` | what created it (`ci`, …) |
238
+ | `newly.run` | the CI run id |
239
+ | `newly.environment` | the CI environment id |
240
+ | `newly.session` / `newly.role` | Newly session association, for simulators |
241
+
242
+ ### Debugging when you have only a log line
243
+
244
+ The control plane logs a sandbox's tags on **create** and **destroy**, so the
245
+ first step needs no API token and no database access:
246
+
247
+ ```bash
248
+ gcloud logging read \
249
+ 'resource.labels.service_name="cp-api-dev" AND jsonPayload.message="run.cloud sandbox created"' \
250
+ --limit 20 --freshness=6h --format=json
251
+ ```
252
+
253
+ Then either query as a normal user (`runcloud sandbox list --tag …`), or use the
254
+ ops endpoint, which is org-agnostic and audited — the right tool when you do not
255
+ know whose org it was:
256
+
257
+ ```
258
+ GET /diagnose/sandbox?tag=newly.run:run-42
259
+ ```
260
+
261
+ It is gated by an ops OIDC token, not a user credential: mint one by
262
+ impersonating the `cp-diagnose-ops-<env>` service account, which every engineer
263
+ can do. Destroyed sandboxes are included on purpose.
264
+
265
+ **Credentials.** The CLI defaults to **prod**. For dev, set both:
266
+
267
+ ```bash
268
+ export RUN_CLOUD_API_URL=https://cp-api-dev-97683904813.us-east4.run.app
269
+ export RUN_CLOUD_API_TOKEN=... # RUN_CLOUD_DEV_API_TOKEN in secrets/dev.yaml
270
+ ```
271
+
272
+ Key names do not match the env vars, and `sops` needs
273
+ `gcloud auth application-default login` rather than plain `gcloud auth login` —
274
+ see the Secrets section of the root `CLAUDE.md`/`AGENTS.md` before concluding
275
+ you lack access.
276
+
207
277
  ## Guardrails
208
278
 
209
279
  - Destroy every sandbox created during a task unless the user explicitly asks
@@ -215,3 +285,5 @@ desktop URLs private and inspect each subcommand's help before automation.
215
285
  URLs in logs, screenshots, PR comments, or chat output.
216
286
  - Do not claim that CLI-only lifecycle, image, secret-group, desktop, or stable
217
287
  hostname commands are TypeScript SDK methods.
288
+ - Do not overwrite a `newly.*` tag; the platform sets those and support reads
289
+ them. Add your own key instead.