@raytrace-cli/cli 0.8.0 → 0.10.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.
package/src/share.mjs ADDED
@@ -0,0 +1,86 @@
1
+ // `raytrace share`: create, list, and revoke share links for recorded traces.
2
+ // Shares are time-limited links on https://app.raytracer.si/share/<token>.
3
+ import { call, ApiError } from './api.mjs';
4
+ import { liveSandboxes } from './sandbox.mjs';
5
+
6
+ const DASHBOARD = process.env.RAYTRACE_DASHBOARD_URL || 'https://app.raytracer.si';
7
+ const say = (line = '') => console.log(line);
8
+
9
+ export function formatTimeLeft(expiresEpoch) {
10
+ const leftSec = Math.round(expiresEpoch - Date.now() / 1000);
11
+ if (leftSec <= 0) return 'expired';
12
+ const min = Math.round(leftSec / 60);
13
+ if (min < 60) return `${min} min`;
14
+ const hr = Math.round(min / 60);
15
+ return `${hr} h`;
16
+ }
17
+
18
+ export async function sharePrompt(traceId, { sandboxId, allowFork = false } = {}) {
19
+ if (!traceId || !traceId.trim()) {
20
+ throw new Error('Trace ID is required. Usage: raytrace share <trace-id> [--sandbox <id>] [--fork]');
21
+ }
22
+ const cleanTrace = traceId.trim();
23
+
24
+ let targetSandbox = sandboxId?.trim();
25
+ if (!targetSandbox) {
26
+ const sandboxes = await liveSandboxes();
27
+ if (sandboxes.length === 1) {
28
+ targetSandbox = sandboxes[0].id;
29
+ } else if (sandboxes.length === 0) {
30
+ throw new Error('No live cloud sandboxes found. Create one first with: raytrace sandbox create');
31
+ } else {
32
+ throw new Error(`More than one cloud sandbox found. Specify which one with --sandbox <id>:\n ${sandboxes.map((s) => `${s.id} (${s.name})`).join('\n ')}`);
33
+ }
34
+ }
35
+
36
+ const result = await call('POST', '/v1/shares', {
37
+ body: {
38
+ trace_id: cleanTrace,
39
+ sandbox_id: targetSandbox,
40
+ allow_fork: Boolean(allowFork),
41
+ },
42
+ });
43
+
44
+ const fullUrl = `${DASHBOARD}${result.url}`;
45
+ const share = result.share;
46
+ say('Share link created:');
47
+ say(` ${fullUrl}`);
48
+ say();
49
+ say(`- Prompt: ${share.trace_id}`);
50
+ say(`- Sandbox: ${share.sandbox_id}`);
51
+ say(`- Forking: ${share.allow_fork ? 'allowed' : 'view only'}`);
52
+ say(`- Expires in: ${formatTimeLeft(share.expires)}`);
53
+ return { ...result, fullUrl };
54
+ }
55
+
56
+ export async function listShares() {
57
+ const result = await call('GET', '/v1/shares');
58
+ const shares = result.shares ?? [];
59
+ const tier = result.tier === 'enterprise' ? 'Team & Enterprise' : 'Individual';
60
+ say(`Active share links (${shares.length} of ${result.limit} on ${tier}):`);
61
+ if (!shares.length) {
62
+ say(' No active share links. Share a prompt with: raytrace share <trace-id>');
63
+ return result;
64
+ }
65
+ say();
66
+ for (const s of shares) {
67
+ const views = s.views?.length ?? 0;
68
+ const viewStr = views === 1 ? '1 view' : `${views} views`;
69
+ say(`- ${s.trace_id}: ${formatTimeLeft(s.expires)} remaining · ${s.allow_fork ? 'fork allowed' : 'view only'} · ${viewStr}`);
70
+ say(` Link: ${DASHBOARD}/share/${s.id}`);
71
+ say(` ID: ${s.id}`);
72
+ }
73
+ say();
74
+ say('Revoke a link at any time: raytrace share --revoke <id>');
75
+ return result;
76
+ }
77
+
78
+ export async function revokeShare(shareId) {
79
+ if (!shareId || !shareId.trim()) {
80
+ throw new Error('Share ID is required. Usage: raytrace share --revoke <id>');
81
+ }
82
+ const cleanId = shareId.trim();
83
+ await call('POST', `/v1/shares/${cleanId}/revoke`);
84
+ say(`Revoked share link ${cleanId}.`);
85
+ return { revoked: cleanId };
86
+ }
@@ -0,0 +1,68 @@
1
+ // A new terminal running one command, for `raytrace mcp` to open a sandbox's
2
+ // terminal next to the editor. The environment says where the agent itself
3
+ // runs (an MCP server inherits it from its client), and the new terminal goes
4
+ // there when that can be driven from outside: a tmux window beside it, an iTerm
5
+ // or WezTerm window or tab. Otherwise the system's own terminal. VS Code's
6
+ // built-in terminal cannot be opened from outside VS Code, so there it is a
7
+ // separate Terminal window.
8
+ import { spawnSync } from 'node:child_process';
9
+
10
+ /** One argument, quoted for sh. */
11
+ export const shellQuote = (arg) => (/^[A-Za-z0-9_./:=@%+-]+$/.test(arg) ? arg : `'${String(arg).replace(/'/g, `'\\''`)}'`);
12
+ const appleString = (text) => `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
13
+ const has = (program) => spawnSync('sh', ['-c', `command -v ${shellQuote(program)}`], { stdio: 'ignore' }).status === 0;
14
+
15
+ function attempt(how, program, args) {
16
+ const result = spawnSync(program, args, { stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8', timeout: 15_000 });
17
+ if (result.error || result.status !== 0) {
18
+ return { opened: false, how, error: (result.error?.message || result.stderr || `exit ${result.status}`).trim().split('\n').slice(-2).join(' ') };
19
+ }
20
+ return { opened: true, how };
21
+ }
22
+
23
+ /** Where to open it, best first: [label, program, args]. */
24
+ function candidates(args, title, env) {
25
+ const command = args.map(shellQuote).join(' ');
26
+ const found = [];
27
+ if (env.TMUX && has('tmux')) found.push(['a new tmux window', 'tmux', ['new-window', '-n', title, command]]);
28
+ if (process.platform === 'darwin') {
29
+ if (env.TERM_PROGRAM === 'iTerm.app') {
30
+ found.push(['a new iTerm window', 'osascript', ['-e', `tell application "iTerm"
31
+ activate
32
+ set w to (create window with default profile)
33
+ tell current session of w to write text ${appleString(command)}
34
+ end tell`]]);
35
+ }
36
+ if (env.TERM_PROGRAM === 'WezTerm' && has('wezterm')) found.push(['a new WezTerm tab', 'wezterm', ['cli', 'spawn', '--', '/bin/sh', '-c', command]]);
37
+ found.push(['a new Terminal window', 'osascript', ['-e', `tell application "Terminal"
38
+ activate
39
+ do script ${appleString(command)}
40
+ end tell`]]);
41
+ } else if (process.platform === 'win32') {
42
+ const line = args.map((arg) => (/[\s"]/.test(arg) ? `"${arg.replace(/"/g, '\\"')}"` : arg)).join(' ');
43
+ if (spawnSync('where', ['wt'], { stdio: 'ignore' }).status === 0) found.push(['a new Windows Terminal tab', 'wt', ['new-tab', '--title', title, 'cmd', '/k', line]]);
44
+ found.push(['a new Command Prompt window', 'cmd', ['/c', 'start', `"${title}"`, 'cmd', '/k', line]]);
45
+ } else if (env.DISPLAY || env.WAYLAND_DISPLAY) {
46
+ for (const [program, flag] of [['x-terminal-emulator', '-e'], ['gnome-terminal', '--'], ['konsole', '-e'], ['xfce4-terminal', '-x'],
47
+ ['kitty', null], ['alacritty', '-e'], ['wezterm', 'start'], ['xterm', '-e']]) {
48
+ if (has(program)) found.push([`a new ${program} window`, program, [...(flag ? [flag] : []), '/bin/sh', '-c', command]]);
49
+ }
50
+ }
51
+ return found;
52
+ }
53
+
54
+ /**
55
+ * Open a new terminal running `args` (a program and its arguments). Answers
56
+ * { opened, how, command }: how it was opened, or why not, and the command as
57
+ * the user would type it, for when it could not be.
58
+ */
59
+ export function openTerminal(args, { title = 'RayTrace', env = process.env } = {}) {
60
+ const command = args.map(shellQuote).join(' ');
61
+ const errors = [];
62
+ for (const [how, program, programArgs] of candidates(args, title, env)) {
63
+ const result = attempt(how, program, programArgs);
64
+ if (result.opened) return { opened: true, how, command };
65
+ errors.push(`${how}: ${result.error}`);
66
+ }
67
+ return { opened: false, how: errors.length ? errors.join('; ') : 'no terminal found to open', command };
68
+ }
@@ -109,14 +109,24 @@ 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'
119
- settings = json.dumps({'hooks': {
127
+ # No permission prompts for any Claude Code session here: the sandbox is
128
+ # what contains the agent, and the hook still refuses restricted files.
129
+ settings = json.dumps({'permissions': {'defaultMode': 'bypassPermissions'}, 'skipDangerousModePermissionPrompt': True, 'hooks': {
120
130
  # Bash for the call id; the file tools so an edit to a restricted file is refused (see guardrails()).
121
131
  'PreToolUse': [{'matcher': 'Bash|Write|Edit|MultiEdit|NotebookEdit', 'hooks': [{'type': 'command', 'command': command, 'timeout': 5}]}],
122
132
  **{event: [{**({'matcher': '*'} if event == 'PostToolUse' else {}),
@@ -127,8 +137,9 @@ def install_claude_hooks(container, hook):
127
137
  # Needs the container running. Files an older install left node-owned
128
138
  # are emptied by node, then their directories removed by root.
129
139
  subprocess.run(['docker', 'exec', '-u', '1000', container, 'sh', '-c',
130
- 'rm -rf /opt/raytace-claude/* /etc/claude-code/*'], stderr=subprocess.DEVNULL)
131
- 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)):
132
143
  write_as_root(container, path, content)
133
144
 
134
145
  def write_as_root(container, path, content):
@@ -548,6 +559,7 @@ def main():
548
559
  parser.add_argument('--since', type=int, default=0, help='activity: from this epoch ms')
549
560
  parser.add_argument('--until', type=int, default=0, help='activity: up to this epoch ms')
550
561
  parser.add_argument('--forget-evidence', action='store_true', help='delete: also delete what the collector recorded for it')
562
+ parser.add_argument('--agent', choices=sorted(AGENTS), help='shell: start this agent first, without approval prompts; its exit leaves the shell')
551
563
  opts = parser.parse_args()
552
564
  if opts.action == 'list':
553
565
  ids = subprocess.check_output(['docker', 'ps', '-aq', '--filter', 'label='+LABEL], text=True).split()
@@ -645,8 +657,11 @@ def main():
645
657
  if opts.action == 'start':
646
658
  return
647
659
  # Exiting this shell or Codex never stops/removes the persistent container.
648
- proc = subprocess.run(['docker', 'exec', '-it', opts.id, '/bin/bash', '-c',
649
- 'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; exec /bin/bash'], check=False)
660
+ start = 'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; '
661
+ if opts.agent:
662
+ name, line = AGENTS[opts.agent]
663
+ 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; '
664
+ proc = subprocess.run(['docker', 'exec', '-it', opts.id, '/bin/bash', '-c', start+'exec /bin/bash'], check=False)
650
665
  sys.exit(proc.returncode)
651
666
  elif opts.action == 'stop':
652
667
  run('docker', 'stop', '-t', '10', opts.id)