raytrace-cli 0.11.1__py3-none-win_arm64.whl

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.
Files changed (165) hide show
  1. raytrace/__init__.py +1 -0
  2. raytrace/__main__.py +33 -0
  3. raytrace/app/LICENSE +21 -0
  4. raytrace/app/README.md +599 -0
  5. raytrace/app/bin/raytrace.mjs +297 -0
  6. raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  7. raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  8. raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  9. raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  10. raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  11. raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  12. raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  13. raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  14. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  15. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  16. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  17. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  18. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  19. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  20. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  21. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  22. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  23. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  24. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  25. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  26. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  27. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  28. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  29. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  30. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  31. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  32. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  33. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  34. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  35. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  36. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  37. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  38. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  39. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  40. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  41. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  42. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  43. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  44. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  45. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  46. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  47. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  48. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  49. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  50. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  51. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  52. raytrace/app/dist/dashboard/assets/index-DepcI8Fi.js +38 -0
  53. raytrace/app/dist/dashboard/assets/index-H97VLD5l.css +1 -0
  54. raytrace/app/dist/dashboard/favicon.svg +6 -0
  55. raytrace/app/dist/dashboard/index.html +15 -0
  56. raytrace/app/package.json +48 -0
  57. raytrace/app/proxy/agent-intent-schema.test.mjs +142 -0
  58. raytrace/app/proxy/call-assessment.mjs +385 -0
  59. raytrace/app/proxy/call-assessment.test.mjs +167 -0
  60. raytrace/app/proxy/call-category.mjs +461 -0
  61. raytrace/app/proxy/capture-health.mjs +30 -0
  62. raytrace/app/proxy/capture-health.test.mjs +44 -0
  63. raytrace/app/proxy/capture.mjs +38 -0
  64. raytrace/app/proxy/capture.test.mjs +49 -0
  65. raytrace/app/proxy/claude-code-adapter.mjs +301 -0
  66. raytrace/app/proxy/claude-code-hook.mjs +22 -0
  67. raytrace/app/proxy/codex-config.mjs +36 -0
  68. raytrace/app/proxy/codex.mjs +14 -0
  69. raytrace/app/proxy/evidence-schema.test.mjs +240 -0
  70. raytrace/app/proxy/evidence-store.mjs +993 -0
  71. raytrace/app/proxy/evidence-store.test.mjs +301 -0
  72. raytrace/app/proxy/exec-narrative.mjs +625 -0
  73. raytrace/app/proxy/exec-narrative.test.mjs +262 -0
  74. raytrace/app/proxy/execution-correlation.mjs +185 -0
  75. raytrace/app/proxy/execution-correlation.test.mjs +146 -0
  76. raytrace/app/proxy/execution-runner.mjs +89 -0
  77. raytrace/app/proxy/execution-runner.test.mjs +38 -0
  78. raytrace/app/proxy/experiment-engine.mjs +195 -0
  79. raytrace/app/proxy/experiment-engine.test.mjs +93 -0
  80. raytrace/app/proxy/explanations.mjs +36 -0
  81. raytrace/app/proxy/explanations.test.mjs +20 -0
  82. raytrace/app/proxy/failure-signature.mjs +56 -0
  83. raytrace/app/proxy/gvisor-forwarder.mjs +493 -0
  84. raytrace/app/proxy/gvisor-forwarder.test.mjs +433 -0
  85. raytrace/app/proxy/init-evidence-db.mjs +227 -0
  86. raytrace/app/proxy/local-sandboxes.mjs +94 -0
  87. raytrace/app/proxy/local-token.mjs +30 -0
  88. raytrace/app/proxy/playground-recovery.test.mjs +130 -0
  89. raytrace/app/proxy/playground.mjs +439 -0
  90. raytrace/app/proxy/prompt-context.mjs +278 -0
  91. raytrace/app/proxy/prompt-traces.mjs +40 -0
  92. raytrace/app/proxy/prompt-traces.test.mjs +32 -0
  93. raytrace/app/proxy/providers.mjs +65 -0
  94. raytrace/app/proxy/providers.test.mjs +76 -0
  95. raytrace/app/proxy/proxy.integration.test.mjs +135 -0
  96. raytrace/app/proxy/raytace-proxy.mjs +941 -0
  97. raytrace/app/proxy/request-metrics.mjs +13 -0
  98. raytrace/app/proxy/request-metrics.test.mjs +19 -0
  99. raytrace/app/proxy/request-policy.mjs +45 -0
  100. raytrace/app/proxy/request-policy.test.mjs +47 -0
  101. raytrace/app/proxy/run-recap.mjs +139 -0
  102. raytrace/app/proxy/runtime-attribution.mjs +110 -0
  103. raytrace/app/proxy/sandbox-bridge.mjs +49 -0
  104. raytrace/app/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  105. raytrace/app/proxy/schema/agent_intent.sql +101 -0
  106. raytrace/app/proxy/schema/auxiliary.sql +90 -0
  107. raytrace/app/proxy/schema/capture_health.sql +14 -0
  108. raytrace/app/proxy/schema/classification.sql +89 -0
  109. raytrace/app/proxy/schema/file_context.sql +53 -0
  110. raytrace/app/proxy/schema/runtime_evidence.sql +201 -0
  111. raytrace/app/proxy/schema/search.sql +66 -0
  112. raytrace/app/proxy/schema/shared_storage.sql +21 -0
  113. raytrace/app/proxy/search.mjs +418 -0
  114. raytrace/app/proxy/search.test.mjs +161 -0
  115. raytrace/app/proxy/smoke.test.mjs +93 -0
  116. raytrace/app/proxy/step-attribution.mjs +380 -0
  117. raytrace/app/proxy/step-lab.mjs +78 -0
  118. raytrace/app/proxy/step-lab.test.mjs +38 -0
  119. raytrace/app/proxy/summaries.mjs +151 -0
  120. raytrace/app/proxy/summaries.test.mjs +69 -0
  121. raytrace/app/proxy/tool-metadata.mjs +111 -0
  122. raytrace/app/proxy/tool-metadata.test.mjs +38 -0
  123. raytrace/app/proxy/trace-view.mjs +324 -0
  124. raytrace/app/proxy/trace-view.test.mjs +92 -0
  125. raytrace/app/proxy/typesafe.mjs +63 -0
  126. raytrace/app/proxy/typesafe.test.mjs +39 -0
  127. raytrace/app/src/agents.mjs +7 -0
  128. raytrace/app/src/api.mjs +57 -0
  129. raytrace/app/src/auth.mjs +205 -0
  130. raytrace/app/src/beta.mjs +96 -0
  131. raytrace/app/src/claude-code.mjs +93 -0
  132. raytrace/app/src/commands.mjs +285 -0
  133. raytrace/app/src/config.mjs +49 -0
  134. raytrace/app/src/export.mjs +200 -0
  135. raytrace/app/src/lima.mjs +176 -0
  136. raytrace/app/src/local-sandbox.mjs +358 -0
  137. raytrace/app/src/mcp.mjs +688 -0
  138. raytrace/app/src/paths.mjs +33 -0
  139. raytrace/app/src/prompt.mjs +42 -0
  140. raytrace/app/src/proxy-process.mjs +143 -0
  141. raytrace/app/src/sandbox.mjs +306 -0
  142. raytrace/app/src/share.mjs +86 -0
  143. raytrace/app/src/terminal.mjs +68 -0
  144. raytrace/app/src/upload.mjs +198 -0
  145. raytrace/app/worker/sandbox/Dockerfile +8 -0
  146. raytrace/app/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  147. raytrace/app/worker/sandbox/claude-hook.mjs +364 -0
  148. raytrace/app/worker/sandbox/collector.py +405 -0
  149. raytrace/app/worker/sandbox/dns_forwarder.py +255 -0
  150. raytrace/app/worker/sandbox/engine.py +940 -0
  151. raytrace/app/worker/sandbox/file_scan.py +491 -0
  152. raytrace/app/worker/sandbox/lima.yaml +29 -0
  153. raytrace/app/worker/sandbox/network.py +90 -0
  154. raytrace/app/worker/sandbox/projects.py +702 -0
  155. raytrace/app/worker/sandbox/setup.py +159 -0
  156. raytrace/app/worker/sandbox/syscall_catalog.sql +985 -0
  157. raytrace/app/worker/sandbox/transcript-delivery.test.mjs +153 -0
  158. raytrace/app/worker/sandbox/viewer.py +195 -0
  159. raytrace/node/LICENSE +2946 -0
  160. raytrace/node/node.exe +4 -0
  161. raytrace_cli-0.11.1.dist-info/LICENSE +21 -0
  162. raytrace_cli-0.11.1.dist-info/METADATA +42 -0
  163. raytrace_cli-0.11.1.dist-info/RECORD +165 -0
  164. raytrace_cli-0.11.1.dist-info/WHEEL +4 -0
  165. raytrace_cli-0.11.1.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,205 @@
1
+ // `raytrace auth`: sign in to RayTrace with WorkOS's device login.
2
+ //
3
+ // `login` asks WorkOS for a short code, opens the approval page, and polls
4
+ // until the code is approved. The tokens never touch a file in plain text:
5
+ // they go in the macOS Keychain or the Linux secret service, and only fall
6
+ // back to a file readable by you alone (with a warning) where neither exists.
7
+ // The client id is public by design: a CLI cannot keep a secret.
8
+ import { spawn, spawnSync } from 'node:child_process';
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { hostname } from 'node:os';
11
+ import { join } from 'node:path';
12
+ import { paths } from './paths.mjs';
13
+
14
+ const say = (line = '') => console.log(line);
15
+ const WORKOS = 'https://api.workos.com/user_management';
16
+ export const CLIENT_ID = process.env.RAYTRACE_WORKOS_CLIENT_ID || 'client_01M4BC8GZZ9HG67EAV65SBRCPX';
17
+ const SERVICE = 'raytrace-cli';
18
+ const ACCOUNT = 'raytrace';
19
+ const FILE = join(paths.home, 'credentials.json');
20
+
21
+ // ------------------------------------------------------------- storage
22
+
23
+ function save(session) {
24
+ const value = Buffer.from(JSON.stringify(session)).toString('base64');
25
+ if (process.platform === 'darwin') {
26
+ // `security -i` reads its command from stdin, so the token never shows in a process list.
27
+ const result = spawnSync('security', ['-i'], { input: `add-generic-password -U -a ${ACCOUNT} -s ${SERVICE} -l "RayTrace CLI" -w ${value}\n`, encoding: 'utf8' });
28
+ if (result.status === 0 && !/error/i.test(result.stderr)) return 'the macOS Keychain';
29
+ } else if (spawnSync('secret-tool', ['--version']).status === 0) {
30
+ const result = spawnSync('secret-tool', ['store', '--label=RayTrace CLI', 'service', SERVICE, 'account', ACCOUNT], { input: value });
31
+ if (result.status === 0) return 'the system keyring';
32
+ }
33
+ mkdirSync(paths.home, { recursive: true });
34
+ writeFileSync(FILE, value, { mode: 0o600 });
35
+ chmodSync(FILE, 0o600);
36
+ return `${FILE} (no keychain found; readable only by you)`;
37
+ }
38
+
39
+ function load() {
40
+ let value = '';
41
+ if (process.platform === 'darwin') {
42
+ const result = spawnSync('security', ['find-generic-password', '-a', ACCOUNT, '-s', SERVICE, '-w'], { encoding: 'utf8' });
43
+ if (result.status === 0) value = result.stdout.trim();
44
+ } else if (spawnSync('secret-tool', ['--version']).status === 0) {
45
+ const result = spawnSync('secret-tool', ['lookup', 'service', SERVICE, 'account', ACCOUNT], { encoding: 'utf8' });
46
+ if (result.status === 0) value = result.stdout.trim();
47
+ }
48
+ if (!value && existsSync(FILE)) value = readFileSync(FILE, 'utf8').trim();
49
+ if (!value) return null;
50
+ try { return JSON.parse(Buffer.from(value, 'base64').toString('utf8')); } catch { return null; }
51
+ }
52
+
53
+ function forget() {
54
+ if (process.platform === 'darwin') spawnSync('security', ['delete-generic-password', '-a', ACCOUNT, '-s', SERVICE]);
55
+ else if (spawnSync('secret-tool', ['--version']).status === 0) spawnSync('secret-tool', ['clear', 'service', SERVICE, 'account', ACCOUNT]);
56
+ rmSync(FILE, { force: true });
57
+ }
58
+
59
+ // ------------------------------------------------------------- tokens
60
+
61
+ /** The access token's claims, read without verifying: RayTrace's API verifies. */
62
+ function claims(token) {
63
+ try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8')); } catch { return {}; }
64
+ }
65
+
66
+ async function workos(path, form) {
67
+ const response = await fetch(`${WORKOS}${path}`, {
68
+ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form),
69
+ });
70
+ return { status: response.status, data: await response.json().catch(() => ({})) };
71
+ }
72
+
73
+ function keep(data) {
74
+ return {
75
+ access_token: data.access_token, refresh_token: data.refresh_token,
76
+ user: { id: data.user?.id, email: data.user?.email, name: [data.user?.first_name, data.user?.last_name].filter(Boolean).join(' ') },
77
+ organization_id: data.organization_id ?? null,
78
+ last_used_at: Date.now(),
79
+ };
80
+ }
81
+
82
+ // Cloud use asks for a fresh sign-in after 2 idle days (sliding: any cloud
83
+ // command resets the clock). Local recording never consults this.
84
+ export const CLOUD_IDLE_LIMIT_MS = 2 * 86_400_000;
85
+ const TOUCH_EVERY_MS = 3_600_000; // last_used_at is rewritten at most hourly
86
+ let idleNotice = false;
87
+
88
+ export const isIdleExpired = (session, now = Date.now()) =>
89
+ Boolean(session?.last_used_at && now - session.last_used_at > CLOUD_IDLE_LIMIT_MS);
90
+
91
+ /** True once after accessToken() dropped a session for idleness. */
92
+ export function consumeIdleNotice() { const was = idleNotice; idleNotice = false; return was; }
93
+
94
+ /** A current access token, refreshed when it is about to expire; null when signed out. */
95
+ export async function accessToken() {
96
+ const session = load();
97
+ if (!session?.access_token) return null;
98
+ if (isIdleExpired(session)) {
99
+ // Idle too long: drop the session so the cloud path starts a fresh
100
+ // sign-in and continues (it says why via consumeIdleNotice()).
101
+ forget();
102
+ idleNotice = true;
103
+ return null;
104
+ }
105
+ const { exp = 0 } = claims(session.access_token);
106
+ if (exp * 1000 - Date.now() > 60_000) {
107
+ // Sliding window: cloud use resets the idle clock (throttled writes;
108
+ // sessions saved before this field existed start their clock now).
109
+ if (!session.last_used_at || Date.now() - session.last_used_at > TOUCH_EVERY_MS) {
110
+ try { save({ ...session, last_used_at: Date.now() }); } catch { /* the token still works */ }
111
+ }
112
+ return session.access_token;
113
+ }
114
+ if (!session.refresh_token) return null;
115
+ const { status, data } = await workos('/authenticate', {
116
+ grant_type: 'refresh_token', refresh_token: session.refresh_token, client_id: CLIENT_ID,
117
+ ...(session.organization_id ? { organization_id: session.organization_id } : {}),
118
+ });
119
+ if (status !== 200 || !data.access_token) {
120
+ throw new Error(`Your RayTrace sign-in expired and could not be renewed (${data.error_description || data.error || data.message || `HTTP ${status}`}). Run: raytrace auth login`);
121
+ }
122
+ save(keep(data));
123
+ return data.access_token;
124
+ }
125
+
126
+ // ------------------------------------------------------------- commands
127
+
128
+ export function openUrl(url) {
129
+ const [command, args] = process.platform === 'darwin' ? ['open', [url]]
130
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
131
+ spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
132
+ }
133
+
134
+ /** Start WorkOS's device login. Returns the code and page to show at once;
135
+ * `done` settles when the code is approved (the session is then saved),
136
+ * declined, or expired. */
137
+ export async function startDeviceLogin() {
138
+ const start = await workos('/authorize/device', { client_id: CLIENT_ID });
139
+ if (start.status !== 200 || !start.data.device_code) {
140
+ throw new Error(`WorkOS refused to start the sign-in: ${start.data.error_description || start.data.message || `HTTP ${start.status}`}`);
141
+ }
142
+ const { device_code, user_code, verification_uri, verification_uri_complete } = start.data;
143
+ let interval = (start.data.interval || 5) * 1000;
144
+ const deadline = Date.now() + (start.data.expires_in || 300) * 1000;
145
+ const done = (async () => {
146
+ while (Date.now() < deadline) {
147
+ await new Promise((resolve) => setTimeout(resolve, interval));
148
+ const { status, data } = await workos('/authenticate', {
149
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code', device_code, client_id: CLIENT_ID,
150
+ device_id: hostname().slice(0, 100),
151
+ });
152
+ if (status === 200 && data.access_token) return { email: data.user?.email, where: save(keep(data)) };
153
+ if (data.error === 'authorization_pending') continue;
154
+ if (data.error === 'slow_down') { interval += 5000; continue; }
155
+ if (data.error === 'access_denied') throw new Error('The sign-in was declined.');
156
+ if (data.error === 'expired_token') break;
157
+ throw new Error(`Sign-in failed: ${data.error_description || data.error || `HTTP ${status}`}`);
158
+ }
159
+ throw new Error('The code expired before it was approved. Run raytrace auth login again.');
160
+ })();
161
+ return { user_code, verification_uri, verification_uri_complete, done };
162
+ }
163
+
164
+ export async function login() {
165
+ const { user_code, verification_uri, verification_uri_complete, done } = await startDeviceLogin();
166
+ say(`Your sign-in code: ${user_code}`);
167
+ say(`Opening ${verification_uri}: sign in, or create your account, and approve the code`);
168
+ say('(or open it yourself on any device).');
169
+ openUrl(verification_uri_complete || verification_uri);
170
+ say('Waiting for approval...');
171
+ const { email, where } = await done;
172
+ say(`\nSigned in as ${email}. Your sign-in is kept in ${where}.`);
173
+ }
174
+
175
+ /** `raytrace auth login`: sign in, then say what comes next. */
176
+ export async function loginCommand() {
177
+ await login();
178
+ say('\nNext, from a Git repository: raytrace sandbox create');
179
+ }
180
+
181
+ /** The signed-in account's email, for messages that need to say whose workspace this is; null when signed out. */
182
+ export function account() { return load()?.user?.email || null; }
183
+
184
+ export async function status() {
185
+ const session = load();
186
+ if (!session) { say('Not signed in. Run: raytrace auth login'); return; }
187
+ const { exp = 0, org_id: org } = claims(session.access_token);
188
+ say(`Signed in as ${session.user?.email}${session.user?.name ? ` (${session.user.name})` : ''}`);
189
+ say(`Organization: ${org || session.organization_id || 'personal'}`);
190
+ const left = Math.round((exp * 1000 - Date.now()) / 60000);
191
+ say(left > 0 ? `Access token valid for ${left} more min; renewed automatically.` : 'Access token expired; it is renewed on the next command.');
192
+ // Beta is a cloud entitlement, separate from any local licence tier.
193
+ try {
194
+ const { betaStatus, formatCreditDeadline } = await import('./beta.mjs');
195
+ const beta = await betaStatus();
196
+ if (beta?.sandbox_consumed) say(`Beta: $10 credit used${beta.credited_sandbox_id ? ` on ${beta.credited_sandbox_id}` : ''}.`);
197
+ else if (beta?.entitled) say(`Beta: $${beta.credit_usd ?? 10} credit available${beta.credit_expires_at ? ` until ${formatCreditDeadline(beta.credit_expires_at)}` : ''} (raytrace sandbox create).`);
198
+ } catch { /* no beta entitlement, old backend, or offline: nothing to add */ }
199
+ }
200
+
201
+ export async function logout() {
202
+ if (!load()) { say('Not signed in.'); return; }
203
+ forget();
204
+ say('Signed out: your RayTrace sign-in was removed from this machine.');
205
+ }
@@ -0,0 +1,96 @@
1
+ // `raytrace --code <code>`: redeem a single-use beta code handed out by
2
+ // RayTrace. Sign-in (`raytrace auth login`) is a prerequisite — this command
3
+ // never starts a sign-in flow and never sends the code anywhere until a
4
+ // signed-in account is known. The backend is the source of truth: on a
5
+ // successful redeem it deletes the code irreversibly and binds a $10
6
+ // OpenRouter credit (hard 3-day limit) to the signed-in account. Nothing
7
+ // about the code or entitlement is stored on this machine.
8
+ import { accessToken, consumeIdleNotice } from './auth.mjs';
9
+ import { call, hasApiKeyOverride } from './api.mjs';
10
+
11
+ const say = (line = '') => console.log(line);
12
+
13
+ export const normalizeBetaCode = (code) => String(code ?? '').trim().toUpperCase().replace(/\s+/g, '');
14
+
15
+ // Codes are minted only in the backend repo (raytrace:
16
+ // worker/gvisor/mint_beta_codes.py), which stores SHA-256 hashes of the
17
+ // normalized code in `beta_codes` and deletes the row on redemption. The
18
+ // shared contract: RTB-XXXX-XXXX-XXXX (Crockford Base32), normalized as
19
+ // above, 3-day expiry. This CLI only presents a code; it never mints one.
20
+
21
+ export function formatCreditDeadline(iso, now = Date.now()) {
22
+ if (!iso) return '';
23
+ const when = new Date(iso);
24
+ if (Number.isNaN(when.getTime())) return '';
25
+ const label = when.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
26
+ const ms = when.getTime() - now;
27
+ if (ms <= 0) return `${label} (expired)`;
28
+ const hours = Math.round(ms / 3_600_000);
29
+ return `${label} (about ${hours <= 1 ? '1 hour' : `${hours} hours`} left)`;
30
+ }
31
+
32
+ /** Signed-in check that never starts a login flow and never touches a code. */
33
+ export async function ensureSignedIn(getToken = accessToken) {
34
+ if (hasApiKeyOverride()) return;
35
+ const token = await getToken();
36
+ if (!token) {
37
+ throw new Error(consumeIdleNotice()
38
+ ? 'You have not used RayTrace cloud for 2 days, so you need to sign in again. Run: raytrace auth login, then re-run: raytrace --code <your-code>'
39
+ : 'Not signed in. Run: raytrace auth login, then re-run: raytrace --code <your-code>');
40
+ }
41
+ }
42
+
43
+ export async function betaStatus(apiCall = call) {
44
+ return apiCall('GET', '/v1/beta/status', { autoLogin: false });
45
+ }
46
+
47
+ function redeemError(error) {
48
+ switch (error?.status) {
49
+ case 401: return new Error('Not signed in. Run: raytrace auth login, then re-run: raytrace --code <your-code>');
50
+ case 422: return new Error("That code isn't valid. Check it and try again, or ask RayTrace for a new one.");
51
+ case 410: return new Error('That code has expired (codes must be redeemed within 3 days). Ask RayTrace for a new one.');
52
+ case 409: return new Error('This account already has beta credit, so this code was not used. '
53
+ + 'It can still be given to someone else until it expires.');
54
+ case 429: return new Error('Too many code attempts. Wait a while and try again.');
55
+ default: return null;
56
+ }
57
+ }
58
+
59
+ export async function redeemBetaCode(rawCode, { ensure = ensureSignedIn, apiCall = call, log = say } = {}) {
60
+ const code = normalizeBetaCode(rawCode);
61
+ if (!code) throw new Error('Usage: raytrace --code <code>');
62
+ // Prerequisite first: an unauthenticated attempt must not consume,
63
+ // validate, or delete the code on the backend.
64
+ await ensure();
65
+ let data;
66
+ try {
67
+ data = await apiCall('POST', '/v1/beta/redeem', {
68
+ body: JSON.stringify({ code }),
69
+ headers: { 'content-type': 'application/json' },
70
+ autoLogin: false,
71
+ });
72
+ } catch (error) {
73
+ const mapped = redeemError(error);
74
+ if (mapped) throw mapped;
75
+ // The code is deleted on success, so a lost response looks like a
76
+ // failure here while the entitlement already exists. Check before
77
+ // reporting failure; the entitlement is what the user needs.
78
+ try {
79
+ const status = await betaStatus(apiCall);
80
+ if (status?.entitled) {
81
+ log("You're already good for beta testing: this account has its beta credit.");
82
+ if (status.credit_expires_at) log(`Use it by ${formatCreditDeadline(status.credit_expires_at)}: raytrace sandbox create`);
83
+ return status;
84
+ }
85
+ } catch { /* fall through to the original error */ }
86
+ throw error;
87
+ }
88
+ const credit = data?.credit_usd ?? 10;
89
+ log(`You're good for beta testing: $${credit} of Claude Code credit (via OpenRouter) is on this account.`);
90
+ log('Your account now shows as Beta in the RayTrace dashboard.');
91
+ if (data?.credit_expires_at) {
92
+ log(`Hard limit: create your sandbox and use the credit by ${formatCreditDeadline(data.credit_expires_at)}. Unused credit expires.`);
93
+ }
94
+ log('Next, from a Git repository: raytrace sandbox create');
95
+ return data;
96
+ }
@@ -0,0 +1,93 @@
1
+ // RayTrace's hook in Claude Code's user settings (~/.claude/settings.json).
2
+ // Adds or removes only its own entries, leaving every other setting and hook
3
+ // as it was; the previous file is kept as settings.json.raytrace-backup.
4
+ //
5
+ // The hook runs `raytrace hook claude-code`, not a path into this package: a
6
+ // path breaks the day the package moves (an update, a cleared npx cache) and
7
+ // Claude Code then records nothing, silently.
8
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+
12
+ // After each tool, when Claude finishes answering, and when the session ends.
13
+ const EVENTS = ['PostToolUse', 'Stop', 'SubagentStop', 'SessionEnd'];
14
+ export const HOOK_COMMAND = 'raytrace hook claude-code';
15
+ const settingsFile = () => join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'settings.json');
16
+
17
+ const isOurs = (hook) => hook?.command === HOOK_COMMAND;
18
+ // The RayTrace repo's own hook (proxy/claude-code-install.mjs). Left alone,
19
+ // but worth knowing about: both would report the same sessions.
20
+ const isRepoHook = (hook) => typeof hook?.command === 'string' && hook.command.includes('claude-code-hook.mjs');
21
+
22
+ function readSettings() {
23
+ const file = settingsFile();
24
+ if (!existsSync(file)) return {};
25
+ try { return JSON.parse(readFileSync(file, 'utf8')); }
26
+ catch (error) { throw new Error(`${file} is not valid JSON (${error.message}); fix it, then try again.`); }
27
+ }
28
+
29
+ function allHooks(settings) {
30
+ return EVENTS.flatMap((event) => (settings.hooks?.[event] ?? []).flatMap((group) => group.hooks ?? []));
31
+ }
32
+
33
+ export function hookState() {
34
+ const settings = readSettings();
35
+ const hooks = allHooks(settings);
36
+ const repoHook = hooks.some(isRepoHook);
37
+
38
+ const missingEvents = [];
39
+ let invalidType = false;
40
+ let invalidMatcher = false;
41
+ let duplicates = false;
42
+
43
+ for (const event of EVENTS) {
44
+ const groups = settings.hooks?.[event] ?? [];
45
+ let count = 0;
46
+
47
+ for (const group of groups) {
48
+ for (const hook of group.hooks ?? []) {
49
+ if (isOurs(hook)) {
50
+ count += 1;
51
+ if (hook.type !== 'command') invalidType = true;
52
+ if (event === 'PostToolUse' && group.matcher && group.matcher !== '*') invalidMatcher = true;
53
+ }
54
+ }
55
+ }
56
+
57
+ if (count === 0) missingEvents.push(event);
58
+ else if (count > 1) duplicates = true;
59
+ }
60
+
61
+ const installed = missingEvents.length === 0;
62
+ const valid = installed && !invalidType && !invalidMatcher && !duplicates;
63
+
64
+ return {
65
+ file: settingsFile(),
66
+ installed,
67
+ valid,
68
+ missingEvents,
69
+ invalidType,
70
+ invalidMatcher,
71
+ duplicates,
72
+ repoHook
73
+ };
74
+ }
75
+
76
+ /** Installs (or with remove, removes) the hook. Returns the settings file. */
77
+ export function setHook({ remove = false } = {}) {
78
+ const file = settingsFile();
79
+ const settings = readSettings();
80
+ settings.hooks ??= {};
81
+ for (const event of EVENTS) {
82
+ const groups = (settings.hooks[event] ?? [])
83
+ .map((group) => ({ ...group, hooks: (group.hooks ?? []).filter((hook) => !isOurs(hook)) }))
84
+ .filter((group) => group.hooks.length);
85
+ if (!remove) groups.push({ ...(event === 'PostToolUse' ? { matcher: '*' } : {}), hooks: [{ type: 'command', command: HOOK_COMMAND, timeout: 5 }] });
86
+ if (groups.length) settings.hooks[event] = groups; else delete settings.hooks[event];
87
+ }
88
+ if (!Object.keys(settings.hooks).length) delete settings.hooks;
89
+ mkdirSync(dirname(file), { recursive: true });
90
+ if (existsSync(file)) copyFileSync(file, `${file}.raytrace-backup`);
91
+ writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
92
+ return file;
93
+ }