@raytrace-cli/cli 0.8.0 → 0.9.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
+ }
@@ -116,7 +116,9 @@ def install_claude_hooks(container, hook):
116
116
  if not 0 < len(hook) <= 262144:
117
117
  raise ValueError('Expected the hook script')
118
118
  command = 'node /opt/raytace-claude/hook.mjs'
119
- settings = json.dumps({'hooks': {
119
+ # No permission prompts for any Claude Code session here: the sandbox is
120
+ # what contains the agent, and the hook still refuses restricted files.
121
+ settings = json.dumps({'permissions': {'defaultMode': 'bypassPermissions'}, 'skipDangerousModePermissionPrompt': True, 'hooks': {
120
122
  # Bash for the call id; the file tools so an edit to a restricted file is refused (see guardrails()).
121
123
  'PreToolUse': [{'matcher': 'Bash|Write|Edit|MultiEdit|NotebookEdit', 'hooks': [{'type': 'command', 'command': command, 'timeout': 5}]}],
122
124
  **{event: [{**({'matcher': '*'} if event == 'PostToolUse' else {}),
@@ -548,6 +550,7 @@ def main():
548
550
  parser.add_argument('--since', type=int, default=0, help='activity: from this epoch ms')
549
551
  parser.add_argument('--until', type=int, default=0, help='activity: up to this epoch ms')
550
552
  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')
551
554
  opts = parser.parse_args()
552
555
  if opts.action == 'list':
553
556
  ids = subprocess.check_output(['docker', 'ps', '-aq', '--filter', 'label='+LABEL], text=True).split()
@@ -645,8 +648,10 @@ def main():
645
648
  if opts.action == 'start':
646
649
  return
647
650
  # 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)
651
+ 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; '
654
+ proc = subprocess.run(['docker', 'exec', '-it', opts.id, '/bin/bash', '-c', start+'exec /bin/bash'], check=False)
650
655
  sys.exit(proc.returncode)
651
656
  elif opts.action == 'stop':
652
657
  run('docker', 'stop', '-t', '10', opts.id)