@raytrace-cli/cli 0.9.0 → 0.11.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.
@@ -13,7 +13,7 @@ import { readToken } from '../proxy/local-token.mjs';
13
13
 
14
14
  // The proxy API this CLI's dashboard needs (proxy/raytace-proxy.mjs PROXY_API).
15
15
  // A proxy from an older install answers without it, or with less.
16
- export const PROXY_API = 4;
16
+ export const PROXY_API = 5;
17
17
 
18
18
  /** The running proxy's API version: 0 for one from before it said. */
19
19
  export async function proxyApi(port) {
package/src/sandbox.mjs CHANGED
@@ -18,6 +18,7 @@ import { api, call, ApiError, unreachable } from './api.mjs';
18
18
  import { betaStatus, formatCreditDeadline } from './beta.mjs';
19
19
  import { ask, confirm, interactive } from './prompt.mjs';
20
20
  import * as local from './local-sandbox.mjs';
21
+ import { AGENTS } from './agents.mjs';
21
22
 
22
23
  const say = (line = '') => console.log(line);
23
24
  // What one project upload may be. RayTrace's API holds the dashboard's folder
@@ -258,7 +259,7 @@ export function betaExpiryWarning(beta, id, now = Date.now()) {
258
259
  export async function shell(id, flags = {}) {
259
260
  if (!interactive()) throw new Error('Connecting to a sandbox needs a terminal.');
260
261
  // With no id and no cloud sign-in, the one local sandbox is the likely one.
261
- if (flags.local || local.isLocal(id) || (!id && Object.keys(local.registry()).length && !account())) return local.shell(id, { claude: flags.claude });
262
+ if (flags.local || local.isLocal(id) || (!id && Object.keys(local.registry()).length && !account())) return local.shell(id, { agent: flags.agent });
262
263
  id = await pickId(id);
263
264
  try {
264
265
  const warning = betaExpiryWarning(await betaStatus(), id);
@@ -284,11 +285,12 @@ export async function shell(id, flags = {}) {
284
285
  });
285
286
  });
286
287
  req.on('upgrade', (_response, socket, head) => {
287
- say(flags.claude ? `Connected to ${id}, starting Claude Code without permission prompts (the sandbox is what contains it); when it exits you are in the sandbox's shell. The sandbox keeps running.\n`
288
+ const agent = AGENTS[flags.agent];
289
+ say(agent ? `Connected to ${id}, starting ${agent.name} without approval prompts (the sandbox is what contains it); when it exits you are in the sandbox's shell. The sandbox keeps running.\n`
288
290
  : `Connected to ${id}. Run \`claude\` (or codex) here; exit to leave. The sandbox keeps running.\n`);
289
291
  if (head.length) stdout.write(head);
290
- // The API's shell takes no command: Claude Code is started by typing it, which the terminal holds until the shell reads it.
291
- if (flags.claude) socket.write('claude --dangerously-skip-permissions\r');
292
+ // The API's shell takes no command: the agent is started by typing it, which the terminal holds until the shell reads it.
293
+ if (agent) socket.write(`${agent.command}\r`);
292
294
  stdin.setRawMode(true);
293
295
  stdin.resume();
294
296
  stdin.pipe(socket);
@@ -232,6 +232,13 @@ def init_db(path):
232
232
  id INTEGER PRIMARY KEY, connection TEXT NOT NULL, received_ms INTEGER NOT NULL,
233
233
  container_id TEXT NOT NULL, kind TEXT NOT NULL, body TEXT NOT NULL)''')
234
234
  db.execute('CREATE INDEX IF NOT EXISTS runtime_container ON runtime_events(container_id,id)')
235
+ db.execute("CREATE TABLE IF NOT EXISTS collector_state (id INTEGER PRIMARY KEY CHECK(id=1), instance_id TEXT NOT NULL, heartbeat_ms INTEGER NOT NULL)")
236
+ db.execute("""CREATE TABLE IF NOT EXISTS capture_streams (
237
+ id TEXT PRIMARY KEY, collector_id TEXT NOT NULL, container_id TEXT NOT NULL,
238
+ started_ms INTEGER NOT NULL, ended_ms INTEGER, heartbeat_ms INTEGER NOT NULL,
239
+ dropped INTEGER NOT NULL DEFAULT 0, errors INTEGER NOT NULL DEFAULT 0,
240
+ capabilities_json TEXT NOT NULL)""")
241
+ db.execute('CREATE INDEX IF NOT EXISTS capture_stream_container ON capture_streams(container_id,started_ms)')
235
242
  db.commit()
236
243
  return db
237
244
 
@@ -244,26 +251,64 @@ class Writer(threading.Thread):
244
251
  super().__init__(daemon=True, name='raytace-writer')
245
252
  self.database = database
246
253
  self.rows = queue.SimpleQueue()
254
+ self.instance_id = str(uuid.uuid4())
255
+ self.last_heartbeat = None
256
+ self.capabilities = {'processes': True, 'files': False, 'network': False}
247
257
 
248
258
  def put(self, connection, event):
249
- self.rows.put((connection, int(time.time() * 1000), event.get('container_id', ''), event['kind'], json.dumps(event)))
259
+ now = int(time.time() * 1000)
260
+ event = {**event, 'source_instance_id': self.instance_id, 'source_connection_id': connection, 'received_ms': now}
261
+ self.rows.put((connection, now, event.get('container_id', ''), event['kind'], json.dumps(event)))
262
+
263
+ def write_batch(self, db, batch, now=None):
264
+ """Events and health progress commit together; idle heartbeats add no event rows."""
265
+ now = int(time.time() * 1000) if now is None else now
266
+ wrote_heartbeat = False
267
+ with db:
268
+ for connection, received, container, kind, body in batch:
269
+ db.execute('INSERT INTO runtime_events(connection,received_ms,container_id,kind,body) VALUES(?,?,?,?,?)',
270
+ (connection, received, container, kind, body))
271
+ event = json.loads(body)
272
+ db.execute("""INSERT INTO capture_streams VALUES(?,?,?,?,?,?,?,?,?)
273
+ ON CONFLICT(id) DO UPDATE SET
274
+ container_id=CASE WHEN excluded.container_id <> '' THEN excluded.container_id ELSE capture_streams.container_id END,
275
+ ended_ms=COALESCE(excluded.ended_ms,capture_streams.ended_ms),
276
+ heartbeat_ms=CASE WHEN excluded.ended_ms IS NOT NULL THEN excluded.ended_ms ELSE capture_streams.heartbeat_ms END,
277
+ dropped=capture_streams.dropped+excluded.dropped,
278
+ errors=capture_streams.errors+excluded.errors""",
279
+ (connection, self.instance_id, container, received,
280
+ received if kind == 'collector_disconnected' else None, received,
281
+ event.get('dropped_delta', 0) if kind == 'collection_gap' else 0,
282
+ 1 if kind == 'collection_error' else 0, json.dumps(self.capabilities)))
283
+ if container:
284
+ # The greeting precedes container identification. Bind only
285
+ # this connection's greeting once a real event names it.
286
+ db.execute("UPDATE runtime_events SET container_id=? WHERE connection=? AND container_id=''", (container, connection))
287
+ if self.rows.empty() and (self.last_heartbeat is None or now-self.last_heartbeat>=5000):
288
+ wrote_heartbeat = True
289
+ db.execute('INSERT INTO collector_state VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET instance_id=excluded.instance_id,heartbeat_ms=excluded.heartbeat_ms', (self.instance_id, now))
290
+ db.execute('UPDATE capture_streams SET heartbeat_ms=? WHERE collector_id=? AND ended_ms IS NULL', (now, self.instance_id))
291
+ if wrote_heartbeat:
292
+ self.last_heartbeat = now
250
293
 
251
294
  def run(self):
252
295
  db = init_db(self.database)
253
296
  while True:
254
- batch = [self.rows.get()]
297
+ try:
298
+ batch = [self.rows.get(timeout=5)]
299
+ except queue.Empty:
300
+ batch = []
255
301
  deadline = time.monotonic() + 0.25
256
- while len(batch) < 200:
302
+ while batch and len(batch) < 200:
257
303
  try:
258
304
  batch.append(self.rows.get(timeout=max(0.0, deadline - time.monotonic())))
259
305
  except queue.Empty:
260
306
  break
261
307
  while True:
262
308
  try:
263
- db.executemany('INSERT INTO runtime_events(connection,received_ms,container_id,kind,body) VALUES(?,?,?,?,?)', batch)
264
- db.commit()
309
+ self.write_batch(db, batch)
265
310
  break
266
- except sqlite3.Error as error: # a locked or full database: keep the batch and try again
311
+ except sqlite3.Error as error:
267
312
  print(f'RayTrace collector: runtime_events not written ({error}); retrying', flush=True)
268
313
  time.sleep(1)
269
314
 
@@ -283,6 +328,7 @@ def serve(endpoint, database):
283
328
  try:
284
329
  engine = facts_engine.Engine(database)
285
330
  engine.start()
331
+ writer.capabilities.update(files=True, network=True)
286
332
  except Exception as error:
287
333
  print(f'RayTrace collector: fact engine not started ({error}); recording processes only', flush=True)
288
334
 
@@ -306,6 +352,7 @@ def serve(endpoint, database):
306
352
  conn.settimeout(None)
307
353
  record({'kind': 'collector_connected', 'source': 'collector'})
308
354
  previous_dropped = 0
355
+ previous_received = int(time.time()*1000)
309
356
  while True:
310
357
  packet, _, flags, _ = conn.recvmsg(MAX_PACKET)
311
358
  if not packet:
@@ -317,10 +364,11 @@ def serve(endpoint, database):
317
364
  container = event['container_id']
318
365
  if event['dropped_count'] != previous_dropped:
319
366
  gap = {'kind': 'collection_gap', 'container_id': event['container_id'],
320
- 'dropped_delta': (event['dropped_count'] - previous_dropped) % (1 << 32)}
367
+ 'gap_from_ms': previous_received, 'dropped_delta': (event['dropped_count'] - previous_dropped) % (1 << 32)}
321
368
  record(gap)
322
369
  taken(gap)
323
370
  previous_dropped = event['dropped_count']
371
+ previous_received = int(time.time()*1000)
324
372
  if not taken(event):
325
373
  record(with_raw(event, packet))
326
374
  except Exception as error:
@@ -109,10 +109,18 @@ def stage_archive(sid):
109
109
  out.write(chunk)
110
110
  return path
111
111
 
112
+ # Codex the same: no approval prompts, and none of its own sandboxing, which
113
+ # the sandbox already is (and gVisor would not let it set up).
114
+ # What `shell --agent` starts: the agent's name and its command line.
115
+ AGENTS = {'claude': ('Claude Code', 'claude --dangerously-skip-permissions'),
116
+ 'codex': ('Codex', 'codex --dangerously-bypass-approvals-and-sandbox')}
117
+ CODEX_MANAGED = b'approval_policy = "never"\nsandbox_mode = "danger-full-access"\n'
118
+
112
119
  def install_claude_hooks(container, hook):
113
120
  """The hook script, root-owned, with Claude Code's managed settings, which
114
- user and project settings cannot override: the agent can read both, not
115
- change them. Re-running replaces them with the current version."""
121
+ user and project settings cannot override, and Codex's managed config: the
122
+ agent can read them, not change them. Re-running replaces them with the
123
+ current version."""
116
124
  if not 0 < len(hook) <= 262144:
117
125
  raise ValueError('Expected the hook script')
118
126
  command = 'node /opt/raytace-claude/hook.mjs'
@@ -129,8 +137,9 @@ def install_claude_hooks(container, hook):
129
137
  # Needs the container running. Files an older install left node-owned
130
138
  # are emptied by node, then their directories removed by root.
131
139
  subprocess.run(['docker', 'exec', '-u', '1000', container, 'sh', '-c',
132
- 'rm -rf /opt/raytace-claude/* /etc/claude-code/*'], stderr=subprocess.DEVNULL)
133
- for path, content in (('/opt/raytace-claude/hook.mjs', hook), ('/etc/claude-code/managed-settings.json', settings)):
140
+ 'rm -rf /opt/raytace-claude/* /etc/claude-code/* /etc/codex/*'], stderr=subprocess.DEVNULL)
141
+ for path, content in (('/opt/raytace-claude/hook.mjs', hook), ('/etc/claude-code/managed-settings.json', settings),
142
+ ('/etc/codex/managed_config.toml', CODEX_MANAGED)):
134
143
  write_as_root(container, path, content)
135
144
 
136
145
  def write_as_root(container, path, content):
@@ -491,6 +500,14 @@ def evidence(container, forget=False):
491
500
  return
492
501
  with sqlite3.connect(RUNTIME_DB, timeout=30) as db:
493
502
  tables = {name for (name,) in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
503
+ if 'capture_streams' in tables:
504
+ if forget:
505
+ db.execute('DELETE FROM capture_streams WHERE container_id=?', (container,))
506
+ else:
507
+ for row in db.execute('SELECT id,collector_id,started_ms,ended_ms,heartbeat_ms,dropped,errors,capabilities_json FROM capture_streams WHERE container_id=?', (container,)):
508
+ names=('id','collector_id','started_ms','ended_ms','heartbeat_ms','dropped','errors','capabilities')
509
+ body=dict(zip(names,row)); body['capabilities']=json.loads(body['capabilities'])
510
+ print(json.dumps({'table':'capture_streams','body':body}))
494
511
  for table, columns in (('runtime_events', 'kind, received_ms, body'), ('facts', 'kind, at_ns, received_ms, body')):
495
512
  if table not in tables:
496
513
  continue
@@ -550,7 +567,7 @@ def main():
550
567
  parser.add_argument('--since', type=int, default=0, help='activity: from this epoch ms')
551
568
  parser.add_argument('--until', type=int, default=0, help='activity: up to this epoch ms')
552
569
  parser.add_argument('--forget-evidence', action='store_true', help='delete: also delete what the collector recorded for it')
553
- parser.add_argument('--claude', action='store_true', help='shell: start Claude Code first; its exit leaves the shell')
570
+ parser.add_argument('--agent', choices=sorted(AGENTS), help='shell: start this agent first, without approval prompts; its exit leaves the shell')
554
571
  opts = parser.parse_args()
555
572
  if opts.action == 'list':
556
573
  ids = subprocess.check_output(['docker', 'ps', '-aq', '--filter', 'label='+LABEL], text=True).split()
@@ -649,8 +666,9 @@ def main():
649
666
  return
650
667
  # Exiting this shell or Codex never stops/removes the persistent container.
651
668
  start = 'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; '
652
- if opts.claude:
653
- start += 'cd /workspace 2>/dev/null; if command -v claude >/dev/null; then claude --dangerously-skip-permissions; else echo "Claude Code is not installed in this sandbox."; fi; '
669
+ if opts.agent:
670
+ name, line = AGENTS[opts.agent]
671
+ start += f'cd /workspace 2>/dev/null; if command -v {opts.agent} >/dev/null; then {line}; else echo "{name} is not installed in this sandbox."; fi; '
654
672
  proc = subprocess.run(['docker', 'exec', '-it', opts.id, '/bin/bash', '-c', start+'exec /bin/bash'], check=False)
655
673
  sys.exit(proc.returncode)
656
674
  elif opts.action == 'stop':
@@ -1,7 +1,7 @@
1
- """Loopback-only, read-only evidence viewer, forwarded by Lima to the Mac.
2
-
3
- A forwarded port is open to every account on the Mac, so each request carries
4
- the token the CLI writes here (src/local-sandbox.mjs). No token, no evidence.
1
+ """Loopback-only, read-only evidence viewer, forwarded by Lima to the Mac and
2
+ tunnelled to the control plane. A forwarded port is open to every account on
3
+ the machine at its end, so each request carries the token in this file. No
4
+ token, no evidence.
5
5
  """
6
6
  import hmac
7
7
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -47,24 +47,60 @@ def event_page(db, query):
47
47
  clauses.append('received_ms >= ?'); params.append(since)
48
48
  if until:
49
49
  clauses.append('received_ms <= ?'); params.append(until)
50
- if after:
50
+ if 'after' in query:
51
51
  clauses.append('id > ?'); params.append(after)
52
52
  elif before:
53
53
  clauses.append('id < ?'); params.append(before)
54
54
  if query.get('processes', [''])[0] == '1':
55
- clauses.append("kind IN ('exec_succeeded','exec_failed','process_exit','collection_gap','collection_error','collector_disconnected')")
55
+ clauses.append("kind IN ('exec_succeeded','exec_failed','process_exit','collection_gap','collection_error','collector_connected','collector_disconnected')")
56
56
  where = ' WHERE ' + ' AND '.join(clauses) if clauses else ''
57
- order = 'ASC' if after else 'DESC'
58
- rows = db.execute('SELECT id,body FROM runtime_events'+where+' ORDER BY id '+order+' LIMIT ?', (*params, limit+1)).fetchall()
57
+ order = 'ASC' if 'after' in query else 'DESC'
58
+ rows = db.execute('SELECT id,body,container_id FROM runtime_events'+where+' ORDER BY id '+order+' LIMIT ?', (*params, limit+1)).fetchall()
59
59
  events = []
60
- for identifier, body in rows[:limit]:
60
+ for identifier, body, bound_container in rows[:limit]:
61
61
  event=json.loads(body); event.pop('raw_packet_base64',None)
62
- event['event_id']=identifier; events.append(event)
63
- page = {'events':events,'next_before':None if after else (rows[limit-1][0] if len(rows)>limit else None)}
64
- if after:
62
+ event['event_id']=identifier; event['container_id']=bound_container; events.append(event)
63
+ page = {'events':events,'next_before':None if 'after' in query else (rows[limit-1][0] if len(rows)>limit else None)}
64
+ if 'after' in query:
65
65
  page['next_after'] = rows[limit-1][0] if len(rows) > limit else None
66
+ # Metadata comes from the same selected container and time interval,
67
+ # independently of pagination or the processes-only display filter.
68
+ page['coverage'] = coverage_page(db, query)
69
+ page['gaps'] = page['coverage']['gaps']
66
70
  return page
67
71
 
72
+
73
+ def coverage_page(db, query):
74
+ container = query.get('container', [''])[0]
75
+ since, until = (int(query.get(key, ['0'])[0]) for key in ('since', 'until'))
76
+ clauses, params = [], []
77
+ for sql, value in [('container_id=?', container), ('received_ms>=?', since), ('received_ms<=?', until)]:
78
+ if value:
79
+ clauses.append(sql); params.append(value)
80
+ where = ' WHERE ' + ' AND '.join(clauses) if clauses else ''
81
+ gap_clauses, gap_params = ["kind IN ('collection_gap','collection_error')"], []
82
+ if container:
83
+ gap_clauses.append('container_id=?'); gap_params.append(container)
84
+ if since:
85
+ gap_clauses.append('received_ms>=?'); gap_params.append(since)
86
+ if until:
87
+ gap_clauses.append("COALESCE(json_extract(body,'$.gap_from_ms'),received_ms)<=?"); gap_params.append(until)
88
+ gaps = db.execute('SELECT COUNT(*) FROM runtime_events WHERE ' + ' AND '.join(gap_clauses), gap_params).fetchone()[0]
89
+ latest = db.execute('SELECT COALESCE(MAX(id),0) FROM runtime_events' + (' WHERE container_id=?' if container else ''), (container,) if container else ()).fetchone()[0]
90
+ result = {'version': 1, 'container_id': container, 'gaps': gaps, 'latest': latest, 'streams': [], 'checked_at_ms': int(time.time()*1000)}
91
+ try:
92
+ state = db.execute('SELECT instance_id,heartbeat_ms FROM collector_state WHERE id=1').fetchone()
93
+ if state:
94
+ result.update(source_instance_id=state[0], heartbeat_ms=state[1])
95
+ rows = db.execute('SELECT id,collector_id,container_id,started_ms,ended_ms,heartbeat_ms,dropped,errors,capabilities_json FROM capture_streams WHERE container_id=? ORDER BY started_ms', (container,)).fetchall()
96
+ result['streams'] = [dict(zip(('id','collector_id','container_id','started_ms','ended_ms','heartbeat_ms','dropped','errors','capabilities'), row)) for row in rows]
97
+ for stream in result['streams']:
98
+ stream['capabilities'] = json.loads(stream['capabilities'])
99
+ except sqlite3.OperationalError:
100
+ pass # Old collectors remain readable, with unknown health.
101
+ return result
102
+
103
+
68
104
  def fact_page(db, query):
69
105
  """Facts the engine drew (engine.py), oldest first after `after`: the
70
106
  control plane's cursor over every sandbox of this host, or with `container`
@@ -90,7 +126,7 @@ PAGE = '''<!doctype html><meta charset="utf-8"><title>RayTrace runtime evidence<
90
126
  <table><thead><tr><th>Event</th><th>PID / parent</th><th>Executable / arguments / result</th></tr></thead><tbody id="events"></tbody></table>
91
127
  <script>
92
128
  const select=document.getElementById('jobs');
93
- async function refresh(){try{const response=await fetch('events');if(!response.ok)throw Error('Collector unavailable');const data=await response.json();
129
+ async function refresh(){try{const response=await fetch('events'+(select.value?'?container='+encodeURIComponent(select.value):''));if(!response.ok)throw Error('Collector unavailable');const data=await response.json();
94
130
  const chosen=select.value;select.replaceChildren(new Option('All sandboxes and collector health',''));for(const id of data.containers)select.add(new Option(id.slice(0,16),id));select.value=chosen;
95
131
  const rows=data.events.filter(e=>!select.value||e.container_id===select.value);
96
132
  document.getElementById('status').textContent='Latest '+rows.length+' events (up to 500). '+data.gaps+' recorded collection errors/gaps.';
@@ -125,13 +161,21 @@ class Handler(BaseHTTPRequestHandler):
125
161
  except (sqlite3.Error, ValueError):
126
162
  self.send_error(503, 'Evidence database unavailable')
127
163
  return
164
+ elif urlparse(self.path).path == '/coverage':
165
+ try:
166
+ with sqlite3.connect('file:/var/lib/raytace/runtime.db?mode=ro', uri=True) as db:
167
+ body = json.dumps(coverage_page(db, parse_qs(urlparse(self.path).query))).encode()
168
+ mime = 'application/json'
169
+ except (sqlite3.Error, ValueError):
170
+ self.send_error(503, 'Recording health unavailable')
171
+ return
128
172
  elif urlparse(self.path).path == '/events':
129
173
  try:
130
174
  with sqlite3.connect('file:/var/lib/raytace/runtime.db?mode=ro', uri=True) as db:
131
175
  page = event_page(db, parse_qs(urlparse(self.path).query))
132
176
  containers = [r[0] for r in db.execute("SELECT DISTINCT container_id FROM runtime_events WHERE container_id != ''")]
133
- gaps = db.execute("SELECT COUNT(*) FROM runtime_events WHERE kind IN ('collection_error','collection_gap')").fetchone()[0]
134
- body = json.dumps({**page, 'containers': containers, 'gaps': gaps, 'coverage':'Selected process events; completeness not certified'}).encode()
177
+ gaps = page['gaps']
178
+ body = json.dumps({**page, 'containers': containers, 'gaps': gaps, 'coverage':page['coverage']}).encode()
135
179
  mime = 'application/json'
136
180
  except (sqlite3.Error, ValueError):
137
181
  self.send_error(503, 'Evidence database unavailable')