@raytrace-cli/cli 0.3.0 → 0.5.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/README.md +155 -132
- package/bin/raytrace.mjs +51 -26
- package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
- package/dist/dashboard/assets/index-jyV5iYHJ.js +38 -0
- package/dist/dashboard/index.html +2 -2
- package/package.json +3 -1
- package/proxy/call-assessment.mjs +385 -0
- package/proxy/call-category.mjs +461 -0
- package/proxy/capture.mjs +31 -0
- package/proxy/claude-code-adapter.mjs +46 -3
- package/proxy/evidence-store.mjs +617 -15
- package/proxy/exec-narrative.mjs +625 -0
- package/proxy/execution-correlation.mjs +185 -0
- package/proxy/experiment-engine.mjs +7 -4
- package/proxy/failure-signature.mjs +56 -0
- package/proxy/gvisor-forwarder.mjs +454 -0
- package/proxy/init-evidence-db.mjs +136 -12
- package/proxy/local-sandboxes.mjs +94 -0
- package/proxy/playground.mjs +411 -0
- package/proxy/prompt-context.mjs +12 -7
- package/proxy/prompt-traces.mjs +6 -0
- package/proxy/raytace-proxy.mjs +460 -176
- package/proxy/run-recap.mjs +139 -0
- package/proxy/runtime-attribution.mjs +110 -0
- package/proxy/sandbox-bridge.mjs +46 -0
- package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
- package/proxy/schema/auxiliary.sql +48 -1
- package/proxy/schema/classification.sql +89 -0
- package/proxy/schema/file_context.sql +53 -0
- package/proxy/schema/runtime_evidence.sql +201 -0
- package/proxy/schema/search.sql +66 -0
- package/proxy/search.mjs +418 -0
- package/proxy/step-attribution.mjs +380 -0
- package/proxy/tool-metadata.mjs +36 -0
- package/proxy/trace-view.mjs +276 -0
- package/proxy/typesafe.mjs +63 -0
- package/src/auth.mjs +8 -1
- package/src/commands.mjs +80 -12
- package/src/lima.mjs +135 -0
- package/src/local-sandbox.mjs +324 -0
- package/src/proxy-process.mjs +20 -1
- package/src/sandbox.mjs +24 -6
- package/worker/sandbox/Dockerfile +8 -0
- package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- package/worker/sandbox/claude-hook.mjs +331 -0
- package/worker/sandbox/collector.py +357 -0
- package/worker/sandbox/dns_forwarder.py +255 -0
- package/worker/sandbox/engine.py +940 -0
- package/worker/sandbox/file_scan.py +491 -0
- package/worker/sandbox/lima.yaml +29 -0
- package/worker/sandbox/network.py +90 -0
- package/worker/sandbox/projects.py +678 -0
- package/worker/sandbox/setup.py +159 -0
- package/worker/sandbox/syscall_catalog.sql +985 -0
- package/worker/sandbox/viewer.py +132 -0
- package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
- package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
# Syscall catalog
|
|
2
|
+
|
|
3
|
+
`syscall_catalog.sql` is a standalone, version-controlled SQLite catalog (catalog
|
|
4
|
+
version **2**). It has one row for every syscall name gVisor knows, 353 in all,
|
|
5
|
+
in eight groups: files, network, process, identity, memory, IPC, time and other.
|
|
6
|
+
Version 1 held the 84 file rows only; they are unchanged.
|
|
7
|
+
|
|
8
|
+
The catalog is the rulebook the sandbox host runs from:
|
|
9
|
+
|
|
10
|
+
- `setup.py` builds gVisor's trace configuration from the rows whose `capture`
|
|
11
|
+
is `yes` or `watcher`, so what is subscribed cannot drift from what is listed.
|
|
12
|
+
- `engine.py` names raw events with `syscall_numbers` and reads each captured
|
|
13
|
+
call with the rule its row names in `effect_rule`.
|
|
14
|
+
|
|
15
|
+
Loading the file into a database still enables nothing by itself, and changing
|
|
16
|
+
a row changes what is captured only after `setup.py` runs again on a host.
|
|
17
|
+
|
|
18
|
+
## Import and query
|
|
19
|
+
|
|
20
|
+
From the repository root, create a disposable database:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
catalog_dir=$(mktemp -d)
|
|
24
|
+
sqlite3 "$catalog_dir/catalog.db" < worker/gvisor/syscall_catalog.sql
|
|
25
|
+
sqlite3 -header -column "$catalog_dir/catalog.db" \
|
|
26
|
+
"SELECT syscall_name, category, default_impact_level, capture, detail FROM syscall_catalog_readable WHERE syscall_name = 'unlinkat';"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Expected result:
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
syscall_name category default_impact_level capture detail
|
|
33
|
+
------------ -------- -------------------- ------- -----------
|
|
34
|
+
unlinkat Delete 3 watcher number_only
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
What RayTrace captures, and how much gVisor can tell of each:
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
sqlite3 -header -column "$catalog_dir/catalog.db" \
|
|
41
|
+
"SELECT group_id, syscall_name, capture, detail, effect_rule FROM syscall_catalog_readable WHERE capture != 'no' ORDER BY group_id, syscall_name;"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The import is transactional and idempotent. Re-importing restores catalog-owned
|
|
45
|
+
rows using upserts and preserves unrelated rows. It does not delete removed
|
|
46
|
+
entries or upgrade a version 1 database; use a fresh database. Use a dedicated
|
|
47
|
+
database, not the application or runtime evidence database. The script does not
|
|
48
|
+
modify `PRAGMA user_version`.
|
|
49
|
+
|
|
50
|
+
## Data model
|
|
51
|
+
|
|
52
|
+
| Table/view | Purpose |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `syscall_impact_levels` | Four file impact levels and their meanings. |
|
|
55
|
+
| `syscall_groups` | The eight top-level groups. |
|
|
56
|
+
| `syscall_categories` | Stable operation identifiers, labels, and descriptions; the second level under a group. |
|
|
57
|
+
| `syscall_catalog` | One row per syscall name: description, group, category, nullable default level, rule identifier, required evidence, interpretation notes, the capture decision, and catalog version. |
|
|
58
|
+
| `syscall_numbers` | Generated. The number of each call on `x86_64` and `aarch64`, and whether gVisor implements it. |
|
|
59
|
+
| `syscall_coverage` | Generated. For the pinned gVisor release, whether a call has a typed trace point and with which optional fields, and what a live test observed. |
|
|
60
|
+
| `syscall_catalog_readable` | Joined view with group, category and impact labels, `detail` and `observed`, for inspection or export. |
|
|
61
|
+
|
|
62
|
+
| Level | Label | Meaning |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| 0 | Observe | Read or inspect; sensitive reads and incidental access-time updates remain possible. |
|
|
65
|
+
| 1 | Create | Add an entry without replacing existing data. |
|
|
66
|
+
| 2 | Modify | Change contents, metadata, layout, or location. |
|
|
67
|
+
| 3 | Remove/replace | Remove an entry or replace an existing destination. |
|
|
68
|
+
|
|
69
|
+
Levels describe filesystem impact, **not maliciousness**. A level-0 secret read
|
|
70
|
+
can be concerning; a level-3 temporary-file deletion can be expected. Null means
|
|
71
|
+
conditional or not applicable, never level 0, and every row outside the file
|
|
72
|
+
group has a null level. Unknown syscall names have no row and must remain
|
|
73
|
+
unclassified. A recognized syscall with missing evidence may still have a known
|
|
74
|
+
operation category, but its actual effect stays unknown.
|
|
75
|
+
|
|
76
|
+
Names are not architecture-specific syscall numbers. For example, `newfstatat`
|
|
77
|
+
is a syscall name while `fstatat` is a common library interface. A listed name
|
|
78
|
+
need not exist on every architecture: `open`, `unlink` and `rename` have no
|
|
79
|
+
number on `aarch64`, where only the `*at` forms exist. Resolve numbers in
|
|
80
|
+
`syscall_numbers` against the execution architecture before lookup; do not
|
|
81
|
+
infer them from the collector host.
|
|
82
|
+
|
|
83
|
+
## What is captured
|
|
84
|
+
|
|
85
|
+
`capture` is RayTrace's decision for each row:
|
|
86
|
+
|
|
87
|
+
| `capture` | Meaning | Rows |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| `yes` | Its gVisor trace point is subscribed, with the optional fields in `capture_fields`. | `open`, `openat`, `creat`, `connect`, `listen`, `setuid`, `setgid`, `setresuid`, `setresgid` |
|
|
90
|
+
| `watcher` | Only its raw exit point is subscribed: which process, when, and whether it was refused. gVisor does not decode its path, so the host's file watcher supplies the name. | `unlink`, `unlinkat`, `rmdir`, `rename`, `renameat`, `renameat2`, `truncate`, `ftruncate`, `mkdir`, `mkdirat`, `chmod`, `fchmod`, `fchmodat` |
|
|
91
|
+
| `sentry` | Seen through gVisor's own process points (clone, exec, exit), whatever syscall caused them. | `clone`, `clone3`, `fork`, `vfork`, `execve`, `execveat`, `exit`, `exit_group` |
|
|
92
|
+
| `no` | Not captured. | everything else |
|
|
93
|
+
|
|
94
|
+
`read` and `write` are deliberately `no`: they are by far the most frequent
|
|
95
|
+
calls, and whether a file changed is settled by comparing it before and after.
|
|
96
|
+
Every other `no` row is there so that no call is without a group, and so the
|
|
97
|
+
coverage can be stated: "we read this", "we see it without its path", or "we do
|
|
98
|
+
not watch it".
|
|
99
|
+
|
|
100
|
+
`detail` in the view is what gVisor can tell of a call in the pinned release:
|
|
101
|
+
`full` (a typed point with decoded paths, flags or addresses), `number_only`
|
|
102
|
+
(the number and six integers) or `none` (that release has no such call, as for
|
|
103
|
+
`openat2`). `observed` records what a live test saw arrive and is null until
|
|
104
|
+
`spike_points.py` has run for the release.
|
|
105
|
+
|
|
106
|
+
## Regenerating the generated tables
|
|
107
|
+
|
|
108
|
+
`syscall_numbers` and `syscall_coverage` come from gVisor's own source for the
|
|
109
|
+
release `setup.py` installs. After changing that release:
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
python3 worker/gvisor/catalog_numbers.py # fetch the release, rewrite both tables
|
|
113
|
+
python3 worker/gvisor/catalog_numbers.py --check # change nothing; fail if a call has no row
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
A syscall the new release has and the catalog lacks is refused until its row
|
|
117
|
+
is written. What a spike observed is kept for the same release and cleared for
|
|
118
|
+
a new one, since it has to be seen again.
|
|
119
|
+
|
|
120
|
+
## Classification contract
|
|
121
|
+
|
|
122
|
+
The rule identifiers below are specifications. `engine.py` implements the ones
|
|
123
|
+
its captured rows name (`open_effect`, `remove_entry`, `rename_effect`,
|
|
124
|
+
`file_resize`, `directory_create`, `metadata_change`, `connect_effect`,
|
|
125
|
+
`listen_effect`, `identity_effect`); the others describe calls that are not
|
|
126
|
+
captured. Keep the raw observation, attempted operation, outcome, and confirmed
|
|
127
|
+
effect separate. Preserve the catalog version when persisting classifications.
|
|
128
|
+
|
|
129
|
+
Every event needs sandbox/process identity, timestamp, syscall identity, and
|
|
130
|
+
outcome. A missing exit result is unknown, not success. Apply the row-specific
|
|
131
|
+
`required_evidence` and rules only after decoding signed results and errno.
|
|
132
|
+
|
|
133
|
+
| Rule | Interpretation |
|
|
134
|
+
| --- | --- |
|
|
135
|
+
| `open_effect` | Read-only opens without mutation flags are level 0, but do not prove bytes were read. Confirmed creation is level 1; successful truncation of an existing file is level 2. Writable access alone has no confirmed mutation level. `O_CREAT` alone does not establish creation. `creat` implies `O_WRONLY\|O_CREAT\|O_TRUNC`; `openat2` requires decoding `open_how`. Successful `O_CREAT\|O_EXCL` can establish new creation. Other ambiguous cases stay unresolved. |
|
|
136
|
+
| `file_write` | Level 2 applies only to file targets. Positive returned bytes establish writes, not necessarily different contents or durable storage. Record actual bytes, not just requested bytes; zero-byte and failed writes do not confirm modification. Honor append/offset flags without inventing an unavailable actual offset. |
|
|
137
|
+
| `remove_entry` | Level 3 is the attempted operation. A successful result confirms entry removal; failure does not. `AT_REMOVEDIR` distinguishes directory deletion. Other hard links or open descriptors may retain data. |
|
|
138
|
+
| `rename_effect` | Confirmed non-replacing move is level 2; confirmed replacement is level 3. Unknown destination history remains unresolved. `RENAME_NOREPLACE` success excludes replacement; `RENAME_EXCHANGE` is an exchange at level 2. Same-object operations may be no-ops. `RENAME_WHITEOUT` and unsupported flag combinations stay unresolved until specifically decoded. An earlier directory scan alone is not race-free replacement evidence. |
|
|
139
|
+
| `file_resize` | Level 2 operation; record requested length. Success confirms a length-setting operation, not a change from an unknown prior size. |
|
|
140
|
+
| `directory_create` | Level 1 operation; success confirms creation. Requested mode may differ from effective permissions because of umask or ACLs. |
|
|
141
|
+
| `file_read` | Level 0 for file targets; positive returned bytes establish a read. Zero bytes, failures, and an open alone do not. Do not retain buffer contents. |
|
|
142
|
+
| `inspect` | Level 0 inspection; metadata and accessibility checks do not prove later content access. |
|
|
143
|
+
| `metadata_change` | Level 2 operation; success does not prove a value differed. Keep attribute names and relevant permissions/ownership/timestamps, not attribute payloads. |
|
|
144
|
+
| `link_create` | Level 1 entry creation; distinguish hard links from symbolic-link target text. No claim that contents were copied or the target is safe. |
|
|
145
|
+
| `copy_effect` | Positive transfer to a known existing file is level 2. Creation is established separately by creation evidence. Unknown targets remain unresolved; pipes and sockets are not filesystem edits. |
|
|
146
|
+
| `allocation_effect` | Successful, decoded file allocation/range changes are level 2. Distinguish allocation from punch-hole, zero-range, collapse-range and insert-range; allocation does not alone establish changed content. Unknown flags remain unresolved. |
|
|
147
|
+
| `ioctl_effect` | Decode command-specific semantics first. Supported file clone operations and attribute changes are level 2; supported inspection is level 0. Unknown commands have no default level. |
|
|
148
|
+
| `mapping_effect` | Record mapping capability/lifecycle, not confirmed reads or writes. `MAP_SHARED` plus writable protection permits edits but does not prove them. `msync`/`munmap` alone do not prove changed bytes. Leave confirmed impact unresolved without additional evidence. |
|
|
149
|
+
| `bookkeeping` | No direct filesystem impact level. Track descriptor duplication/reuse, working directories, offsets, synchronization, and command-dependent `fcntl` behavior as context. |
|
|
150
|
+
| `connect_effect` | Decode the address family, IP address and port. A zero result is a connection on a stream socket and only a default peer on a datagram socket. `EINPROGRESS` is an attempt whose outcome this call does not report. A destination in a range the sandbox firewall rejects is a refused attempt. The address is never a host name: a name shown beside it comes from DNS evidence and is a best match. No payload is captured. |
|
|
151
|
+
| `listen_effect` | Success means the process accepts connections on the bound address. Nothing outside the sandbox network is routed to it. |
|
|
152
|
+
| `identity_effect` | Record the requested IDs and the result. Success changes the identity the process acts as; the sandbox has no capabilities, so a successful change away from its one user is unexpected, and a failure is an attempt. |
|
|
153
|
+
| `process_lifecycle` | gVisor's clone, exec and exit points report every task, program start and exit, whichever syscall caused it. A successful exec proves a program started, not what it did; a zero result on the exec syscall point is not treated as success. Keep arguments as observed and, of the environment, only the two `RAYTRACE_` markers. |
|
|
154
|
+
| `not_classified` | The call is listed and grouped, and nothing is collected for it. No fact records its use and none rules it out. |
|
|
155
|
+
|
|
156
|
+
For example, successful `unlinkat` can display **L3 · Delete · Succeeded**;
|
|
157
|
+
`EACCES` can display **L3 · Delete · Failed: permission denied**. Neither label
|
|
158
|
+
requires a new process or PID. A failed operation must not appear in a list of
|
|
159
|
+
confirmed file changes.
|
|
160
|
+
|
|
161
|
+
Store the supplied pathname and directory base independently; do not label a
|
|
162
|
+
lexically joined path as fully resolved through symlinks. Descriptor identities
|
|
163
|
+
must account for reuse and inheritance. Unresolved target types/paths must stay
|
|
164
|
+
explicit. Preserve both source and destination for rename/link/copy events.
|
|
165
|
+
|
|
166
|
+
## Boundaries and validation
|
|
167
|
+
|
|
168
|
+
A row is not a completeness guarantee, and a default level is not evidence of
|
|
169
|
+
success. What the captured set does not see:
|
|
170
|
+
|
|
171
|
+
- **Bytes read or written.** An open for reading is recorded as a read of the
|
|
172
|
+
file; whether a file changed comes from comparing it before and after.
|
|
173
|
+
- **Memory-mapped writes and `io_uring`.** Both change files without the
|
|
174
|
+
ordinary calls. The file still has to be opened, and the before/after
|
|
175
|
+
comparison still sees the change.
|
|
176
|
+
- **Datagrams sent without `connect`.** `sendto` and `sendmsg` name their own
|
|
177
|
+
destination and are not captured. The firewall still applies, and DNS is seen
|
|
178
|
+
by the host resolver.
|
|
179
|
+
- **Paths of `watcher` calls.** A refused delete or rename is known by process
|
|
180
|
+
and time, not by file.
|
|
181
|
+
- **Calls gVisor does not implement** (`support = 'unsupported'` in
|
|
182
|
+
`syscall_numbers`) fail inside the sandbox whatever the catalog says.
|
|
183
|
+
|
|
184
|
+
No buffer contents or environment values are required by these rules. This
|
|
185
|
+
catalog does not change existing evidence storage, retention, or redaction.
|
|
186
|
+
|
|
187
|
+
Run isolated validation, including repeat import and constraints:
|
|
188
|
+
|
|
189
|
+
```sh
|
|
190
|
+
python3 -B -m unittest discover -s worker/gvisor -p 'test_syscall_catalog.py'
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Semantic references: [Linux syscall inventory](https://man7.org/linux/man-pages/man2/syscalls.2.html),
|
|
194
|
+
[open](https://man7.org/linux/man-pages/man2/open.2.html),
|
|
195
|
+
[rename](https://man7.org/linux/man-pages/man2/rename.2.html),
|
|
196
|
+
[memory mappings](https://man7.org/linux/man-pages/man2/mmap.2.html), and
|
|
197
|
+
[gVisor SecCheck](https://github.com/google/gvisor/blob/release-20260817.0/pkg/sentry/seccheck/README.md).
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Claude Code hook inside a RayTrace sandbox. projects.py enable-claude
|
|
4
|
+
* installs it root-owned with a managed-settings file, so the agent can
|
|
5
|
+
* neither edit nor turn it off.
|
|
6
|
+
*
|
|
7
|
+
* PreToolUse (Bash): starts the command with `export RAYTRACE_CALL_ID=<the
|
|
8
|
+
* tool call's id>`. The shell carries the id in its argv and every program it
|
|
9
|
+
* starts carries it in its environment, where the gVisor collector reads it
|
|
10
|
+
* (collector.py MARKER_KEYS): the evidence joins the call exactly instead of
|
|
11
|
+
* by command text.
|
|
12
|
+
*
|
|
13
|
+
* PreToolUse (a file tool): refuses an edit to a file the project's owner
|
|
14
|
+
* restricted (the list projects.py guardrails() writes beside this script),
|
|
15
|
+
* saying why. From the sandbox's next start the file is locked on the host
|
|
16
|
+
* as well, which is what stops every other way of writing it.
|
|
17
|
+
*
|
|
18
|
+
* An attempt on a file the owner restricted or watches (an edit refused, a
|
|
19
|
+
* read, a command naming it) is queued as one line in /tmp/raytace-claude and
|
|
20
|
+
* goes to RayTrace as `events` with the next send: nothing is sent from here
|
|
21
|
+
* before a tool runs, so a refusal is as fast as before. The owner is told.
|
|
22
|
+
*
|
|
23
|
+
* PostToolUse (a tool that can change files) and UserPromptSubmit: snapshots
|
|
24
|
+
* the project folder, so the lab can later put it back exactly as it was at
|
|
25
|
+
* any step. See snapshot() below.
|
|
26
|
+
*
|
|
27
|
+
* Every other event, and those two after their snapshot: sends the
|
|
28
|
+
* transcript's new whole lines, and the snapshot taken, to RayTrace through
|
|
29
|
+
* the RayTrace CLI's sandbox bridge on the host -- the only host service this
|
|
30
|
+
* sandbox can reach -- with the sandbox's token. How far it got is kept in /tmp; if that is lost,
|
|
31
|
+
* RayTrace answers 409 with the size of its copy and sending resumes from
|
|
32
|
+
* there.
|
|
33
|
+
*
|
|
34
|
+
* Never blocks or fails Claude Code: RayTrace being down means no capture.
|
|
35
|
+
*/
|
|
36
|
+
import { readFileSync, writeFileSync, appendFileSync, mkdirSync, rmdirSync, statSync, lstatSync, readdirSync, readlinkSync, existsSync, openSync, readSync, fstatSync, closeSync } from 'node:fs';
|
|
37
|
+
import { execFileSync } from 'node:child_process';
|
|
38
|
+
import { join, resolve } from 'node:path';
|
|
39
|
+
|
|
40
|
+
// The RayTrace CLI's sandbox bridge on the host, as projects.py set it on this
|
|
41
|
+
// sandbox (Lima's address for the host when unset).
|
|
42
|
+
const BROKER = `${process.env.RAYTRACE_BROKER || 'http://192.168.5.2:8799'}/raytace/ingest/claude-code`;
|
|
43
|
+
const CHUNK = 3 * 1024 * 1024; // under the manager's 4 MiB request limit
|
|
44
|
+
const home = process.env.HOME || '/home/node';
|
|
45
|
+
|
|
46
|
+
let input;
|
|
47
|
+
try { input = JSON.parse(readFileSync(0, 'utf8')); } catch { process.exit(0); }
|
|
48
|
+
|
|
49
|
+
const workspace = process.env.RAYTRACE_WORKSPACE || '/workspace';
|
|
50
|
+
const STATE_DIR = '/tmp/raytace-claude';
|
|
51
|
+
const MAX_QUEUED_BYTES = 128 * 1024;
|
|
52
|
+
|
|
53
|
+
// The owner's lists (projects.py guardrails()): `restricted` is refused,
|
|
54
|
+
// `watched` is reported. Nothing listed when the file is absent or unreadable.
|
|
55
|
+
const listed = (value) => (Array.isArray(value) ? value.filter((file) => typeof file === 'string' && file) : []);
|
|
56
|
+
let restricted = [];
|
|
57
|
+
let watched = [];
|
|
58
|
+
try {
|
|
59
|
+
const lists = JSON.parse(readFileSync(new URL('./guardrails.json', import.meta.url), 'utf8'));
|
|
60
|
+
restricted = listed(lists.restricted);
|
|
61
|
+
watched = listed(lists.watched);
|
|
62
|
+
} catch { /* nothing is restricted or watched */ }
|
|
63
|
+
|
|
64
|
+
/** A file the tool named, relative to the project; null when it is outside it. */
|
|
65
|
+
const inside = (named) => {
|
|
66
|
+
if (typeof named !== 'string' || !named) return null;
|
|
67
|
+
const path = resolve(input.cwd || workspace, named);
|
|
68
|
+
return path.startsWith(`${workspace}/`) ? path.slice(workspace.length + 1) : null;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** One line for the next send; never throws and never waits on the network. */
|
|
72
|
+
function queue(event) {
|
|
73
|
+
try {
|
|
74
|
+
if (!/^[0-9a-f-]{36}$/.test(input.session_id ?? '')) return;
|
|
75
|
+
mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
76
|
+
const file = join(STATE_DIR, `${input.session_id}.events.jsonl`);
|
|
77
|
+
try { if (statSync(file).size > MAX_QUEUED_BYTES) return; } catch { /* none yet */ }
|
|
78
|
+
appendFileSync(file, `${JSON.stringify({ at: new Date().toISOString(), call_id: input.tool_use_id ?? null, tool: input.tool_name, ...event })}\n`, { mode: 0o600 });
|
|
79
|
+
} catch { /* never disturb Claude Code */ }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (input.hook_event_name === 'PreToolUse') {
|
|
83
|
+
const named = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
|
|
84
|
+
if (input.tool_name !== 'Bash' && typeof named === 'string') {
|
|
85
|
+
const path = inside(named);
|
|
86
|
+
if (path && restricted.includes(path)) {
|
|
87
|
+
queue({ kind: 'blocked', path });
|
|
88
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
|
|
89
|
+
permissionDecisionReason: `RayTrace: ${path} is restricted by this project's owner and cannot be changed. `
|
|
90
|
+
+ 'Do not try another way to write it; tell the user it has to be unlocked under Initial scan in the RayTrace dashboard.' } }));
|
|
91
|
+
}
|
|
92
|
+
process.exit(0);
|
|
93
|
+
}
|
|
94
|
+
const id = input.tool_use_id;
|
|
95
|
+
const command = input.tool_input?.command;
|
|
96
|
+
// A command that names a restricted file is reported, not stopped: the text
|
|
97
|
+
// says what it mentions, not what it does. The file lock is what stops it.
|
|
98
|
+
if (input.tool_name === 'Bash' && typeof command === 'string') {
|
|
99
|
+
for (const path of restricted.slice(0, 200)) if (command.includes(path)) queue({ kind: 'named', path });
|
|
100
|
+
}
|
|
101
|
+
if (input.tool_name === 'Bash' && /^[A-Za-z0-9_-]{1,128}$/.test(id ?? '') && typeof command === 'string') {
|
|
102
|
+
// An input change needs a decision with it. Only a session that already
|
|
103
|
+
// skips permission prompts gets "allow"; any other still asks as usual.
|
|
104
|
+
const decision = input.permission_mode === 'bypassPermissions' ? 'allow' : 'ask';
|
|
105
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision,
|
|
106
|
+
updatedInput: { ...input.tool_input, command: `export RAYTRACE_CALL_ID=${id}\n${command}` } } }));
|
|
107
|
+
}
|
|
108
|
+
process.exit(0);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------- snapshots
|
|
112
|
+
// A separate git history of /workspace, kept in the sandbox's home: never the
|
|
113
|
+
// project's own git, and blind to the project's .gitignore (-f), so ignored
|
|
114
|
+
// and never-committed files are captured too. Only SKIPPED folders (large,
|
|
115
|
+
// regenerable) and files over MAX_FILE are left out; those are listed on the
|
|
116
|
+
// snapshot so a restore can say it is not exact. Unchanged content is stored
|
|
117
|
+
// once, so a step that changed nothing costs nothing and is not committed.
|
|
118
|
+
// It sits beside the agent, not above it: the agent could alter it, so it is
|
|
119
|
+
// a lab tool, not evidence.
|
|
120
|
+
const WORKSPACE = process.env.RAYTRACE_WORKSPACE || '/workspace';
|
|
121
|
+
const STORE = join(home, '.raytace', 'snapshots.git');
|
|
122
|
+
const SKIPPED = ['node_modules', '.git', '.next', '.vinext', 'dist', 'build', 'out', 'coverage', '.cache', '.turbo',
|
|
123
|
+
'.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', 'target', '.gradle', '.wrangler'];
|
|
124
|
+
const MAX_FILE = 5 * 1024 * 1024;
|
|
125
|
+
const MAX_LISTED = 300;
|
|
126
|
+
// Tools that only read. Anything else, including tools this list has never
|
|
127
|
+
// heard of, is assumed able to change files.
|
|
128
|
+
const READ_ONLY = new Set(['Read', 'Grep', 'Glob', 'LS', 'WebFetch', 'WebSearch', 'TodoWrite', 'TodoRead', 'ToolSearch',
|
|
129
|
+
'ListMcpResourcesTool', 'ReadMcpResourceTool', 'BashOutput', 'KillShell', 'ExitPlanMode', 'AskUserQuestion']);
|
|
130
|
+
|
|
131
|
+
/** Folders below /workspace with their own .git (a clone, or `git init` in
|
|
132
|
+
* a subfolder), outermost only. */
|
|
133
|
+
function nestedRepositories() {
|
|
134
|
+
const found = [];
|
|
135
|
+
const walk = (relative) => {
|
|
136
|
+
for (const entry of readdirSync(relative ? join(WORKSPACE, relative) : WORKSPACE, { withFileTypes: true })) {
|
|
137
|
+
if (!entry.isDirectory() || SKIPPED.includes(entry.name)) continue;
|
|
138
|
+
const path = relative ? `${relative}/${entry.name}` : entry.name;
|
|
139
|
+
if (existsSync(join(WORKSPACE, path, '.git'))) found.push(path); else walk(path);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
walk('');
|
|
143
|
+
return found;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* `git add` records a nested repository as a pointer to it, not its files,
|
|
148
|
+
* and refuses the whole add while it has no commit yet, so nested ones are
|
|
149
|
+
* kept out of the add and their files written into the snapshot directly:
|
|
150
|
+
* re-read in full each time (no change detection, so a very large nested
|
|
151
|
+
* repository makes snapshots slow). Returns the paths left out for size.
|
|
152
|
+
*/
|
|
153
|
+
function addNestedRepositories(git, nested) {
|
|
154
|
+
const tooBig = [];
|
|
155
|
+
// A folder whose names, sizes and times match last time is left as the
|
|
156
|
+
// index already has it: re-reading it costs several git calls per snapshot.
|
|
157
|
+
const seenFile = join(STORE, 'raytrace-nested.json');
|
|
158
|
+
let seen = {};
|
|
159
|
+
try { seen = JSON.parse(readFileSync(seenFile, 'utf8')); } catch { /* none yet */ }
|
|
160
|
+
const now = {};
|
|
161
|
+
for (const folder of nested) {
|
|
162
|
+
const files = [];
|
|
163
|
+
const walk = (relative) => {
|
|
164
|
+
for (const entry of readdirSync(join(WORKSPACE, relative), { withFileTypes: true })) {
|
|
165
|
+
const path = `${relative}/${entry.name}`;
|
|
166
|
+
if (entry.isDirectory()) { if (!SKIPPED.includes(entry.name)) walk(path); continue; }
|
|
167
|
+
if (!entry.isFile() && !entry.isSymbolicLink()) continue;
|
|
168
|
+
const info = lstatSync(join(WORKSPACE, path));
|
|
169
|
+
if (entry.isFile() && info.size > MAX_FILE) { tooBig.push(path); continue; }
|
|
170
|
+
files.push({ path, mode: entry.isSymbolicLink() ? '120000' : info.mode & 0o111 ? '100755' : '100644', size: info.size, time: info.mtimeMs });
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
walk(folder);
|
|
174
|
+
now[folder] = JSON.stringify(files.map(({ path, mode, size, time }) => [path, mode, size, time]));
|
|
175
|
+
if (seen[folder] === now[folder]) continue;
|
|
176
|
+
git('rm', '-q', '-r', '--cached', '--ignore-unmatch', '--', folder);
|
|
177
|
+
if (!files.length) continue;
|
|
178
|
+
// Symbolic links are stored as their target, the way git stores them.
|
|
179
|
+
const hashes = [];
|
|
180
|
+
for (const file of files) {
|
|
181
|
+
hashes.push(file.mode === '120000'
|
|
182
|
+
? execFileSync('git', ['hash-object', '-w', '--stdin'], { env: { ...process.env, GIT_DIR: STORE }, input: readlinkSync(join(WORKSPACE, file.path)), encoding: 'utf8' }).trim()
|
|
183
|
+
: null);
|
|
184
|
+
}
|
|
185
|
+
const regular = files.filter((file, index) => !hashes[index]);
|
|
186
|
+
const hashed = regular.length ? execFileSync('git', ['hash-object', '-w', '--no-filters', '--stdin-paths'],
|
|
187
|
+
{ cwd: WORKSPACE, env: { ...process.env, GIT_DIR: STORE }, input: regular.map((file) => file.path).join('\n'), encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }).trim().split('\n') : [];
|
|
188
|
+
let next = 0;
|
|
189
|
+
const lines = files.map((file, index) => `${file.mode} ${hashes[index] ?? hashed[next++]}\t${file.path}`);
|
|
190
|
+
execFileSync('git', ['update-index', '--add', '--index-info'], { cwd: WORKSPACE, env: { ...process.env, GIT_DIR: STORE, GIT_WORK_TREE: WORKSPACE }, input: lines.join('\n') + '\n' });
|
|
191
|
+
}
|
|
192
|
+
writeFileSync(seenFile, JSON.stringify(now));
|
|
193
|
+
return tooBig;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function snapshot(takenOn, callId) {
|
|
197
|
+
const env = { ...process.env, GIT_DIR: STORE, GIT_WORK_TREE: WORKSPACE, GIT_AUTHOR_NAME: 'RayTrace', GIT_AUTHOR_EMAIL: 'snapshots@raytrace.local',
|
|
198
|
+
GIT_COMMITTER_NAME: 'RayTrace', GIT_COMMITTER_EMAIL: 'snapshots@raytrace.local', GIT_TERMINAL_PROMPT: '0' };
|
|
199
|
+
const git = (...args) => execFileSync('git', args, { cwd: WORKSPACE, env, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
200
|
+
// Tools that run at once snapshot one at a time; a lock older than 30s was
|
|
201
|
+
// left by a hook that died.
|
|
202
|
+
const lock = `${STORE}.lock`;
|
|
203
|
+
const deadline = Date.now() + 4000;
|
|
204
|
+
mkdirSync(join(home, '.raytace'), { recursive: true, mode: 0o700 });
|
|
205
|
+
for (;;) {
|
|
206
|
+
try { mkdirSync(lock); break; } catch (error) {
|
|
207
|
+
if (error.code !== 'EEXIST' || Date.now() > deadline) return null;
|
|
208
|
+
try { if (Date.now() - statSync(lock).mtimeMs > 30_000) { rmdirSync(lock); continue; } } catch { continue; }
|
|
209
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
if (!existsSync(STORE)) {
|
|
214
|
+
git('init', '-q');
|
|
215
|
+
git('config', 'core.autocrlf', 'false');
|
|
216
|
+
}
|
|
217
|
+
const nested = nestedRepositories();
|
|
218
|
+
// A folder that was a nested repository last time and is not now (gone,
|
|
219
|
+
// or its .git removed) goes back to `git add` like any other folder.
|
|
220
|
+
try {
|
|
221
|
+
for (const folder of Object.keys(JSON.parse(readFileSync(join(STORE, 'raytrace-nested.json'), 'utf8')))) {
|
|
222
|
+
if (!nested.includes(folder)) git('rm', '-q', '-r', '--cached', '--ignore-unmatch', '--', folder);
|
|
223
|
+
}
|
|
224
|
+
} catch { /* none recorded yet */ }
|
|
225
|
+
git('add', '-A', '-f', '--', '.', ...SKIPPED.map((name) => `:(glob,exclude)**/${name}/**`),
|
|
226
|
+
...nested.map((folder) => `:(literal,exclude)${folder}`));
|
|
227
|
+
// Too big to keep: the snapshot holds its previous version, and says so.
|
|
228
|
+
const tooBig = git('diff', '--cached', '--name-only', '-z', '--diff-filter=AM').split('\0').filter(Boolean)
|
|
229
|
+
.filter((path) => { try { return statSync(join(WORKSPACE, path)).size > MAX_FILE; } catch { return false; } });
|
|
230
|
+
if (tooBig.length) git('reset', '-q', '--', ...tooBig);
|
|
231
|
+
tooBig.push(...addNestedRepositories(git, nested));
|
|
232
|
+
const tree = git('write-tree').trim();
|
|
233
|
+
let parent = null;
|
|
234
|
+
try { parent = git('rev-parse', '-q', '--verify', 'HEAD').trim(); } catch { /* first snapshot */ }
|
|
235
|
+
const parentTree = parent ? git('rev-parse', `${parent}^{tree}`).trim() : null;
|
|
236
|
+
let commit = parent;
|
|
237
|
+
const changes = [];
|
|
238
|
+
if (tree !== parentTree) {
|
|
239
|
+
commit = git('commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', `${takenOn} ${callId ?? ''}`.trim()).trim();
|
|
240
|
+
git('update-ref', 'HEAD', commit);
|
|
241
|
+
const range = parent ? [parent, commit] : ['--root', commit];
|
|
242
|
+
const counts = new Map(git('diff-tree', '-r', '--numstat', '-z', '--no-commit-id', ...range).split('\0').filter(Boolean)
|
|
243
|
+
.map((entry) => { const [added, removed, ...path] = entry.split('\t'); return [path.join('\t'), [added, removed]]; }));
|
|
244
|
+
const statuses = git('diff-tree', '-r', '--name-status', '-z', '--no-commit-id', ...range).split('\0').filter(Boolean);
|
|
245
|
+
for (let i = 0; i + 1 < statuses.length && changes.length < MAX_LISTED; i += 2) {
|
|
246
|
+
const [added, removed] = counts.get(statuses[i + 1]) ?? ['-', '-'];
|
|
247
|
+
changes.push({ path: statuses[i + 1], status: statuses[i][0],
|
|
248
|
+
added: added === '-' ? null : Number(added), removed: removed === '-' ? null : Number(removed) });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return { commit, parent, taken_on: takenOn, call_id: callId ?? null, taken_at: new Date().toISOString(),
|
|
252
|
+
changed: tree !== parentTree, changes, too_big: tooBig.slice(0, MAX_LISTED) };
|
|
253
|
+
} catch (error) {
|
|
254
|
+
if (process.env.RAYTRACE_HOOK_DEBUG) console.error(error); // silent otherwise: never disturb Claude Code
|
|
255
|
+
return null;
|
|
256
|
+
} finally { try { rmdirSync(lock); } catch { /* already gone */ } }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const session = input.session_id;
|
|
260
|
+
const transcript = input.transcript_path;
|
|
261
|
+
if (!/^[0-9a-f-]{36}$/.test(session ?? '') || typeof transcript !== 'string'
|
|
262
|
+
|| !transcript.startsWith(join(home, '.claude', 'projects') + '/')) process.exit(0);
|
|
263
|
+
|
|
264
|
+
const callId = /^[A-Za-z0-9_-]{1,128}$/.test(input.tool_use_id ?? '') ? input.tool_use_id : null;
|
|
265
|
+
// A read of a file the owner restricted or watches. A write that went through
|
|
266
|
+
// is in the snapshot below, with its size; a refused one was queued above.
|
|
267
|
+
if (input.hook_event_name === 'PostToolUse' && READ_ONLY.has(input.tool_name)) {
|
|
268
|
+
const path = inside(input.tool_input?.file_path ?? input.tool_input?.notebook_path);
|
|
269
|
+
if (path && (restricted.includes(path) || watched.includes(path))) queue({ kind: 'read', path });
|
|
270
|
+
}
|
|
271
|
+
const snap = input.hook_event_name === 'UserPromptSubmit' ? snapshot('prompt', null)
|
|
272
|
+
: input.hook_event_name === 'PostToolUse' && !READ_ONLY.has(input.tool_name) ? snapshot('tool', callId) : null;
|
|
273
|
+
|
|
274
|
+
try {
|
|
275
|
+
// The token projects.py set-token gave this sandbox.
|
|
276
|
+
const token = readFileSync(join(home, '.raytace', 'sandbox-token'), 'utf8').trim();
|
|
277
|
+
if (!token) process.exit(0);
|
|
278
|
+
const stateDir = STATE_DIR;
|
|
279
|
+
const stateFile = join(stateDir, `${session}.offset`);
|
|
280
|
+
let offset = 0;
|
|
281
|
+
try { offset = Number(readFileSync(stateFile, 'utf8')) || 0; } catch { /* first send, or /tmp was cleared */ }
|
|
282
|
+
// The attempts queued since the last send. They go with the first send that
|
|
283
|
+
// succeeds (RayTrace files each by an id of its own, so one that arrives
|
|
284
|
+
// twice counts once) and are then taken off the file, not what came after.
|
|
285
|
+
const queuedFile = join(stateDir, `${session}.events.jsonl`);
|
|
286
|
+
let queued = Buffer.alloc(0);
|
|
287
|
+
try { queued = readFileSync(queuedFile); } catch { /* none queued */ }
|
|
288
|
+
const events = queued.toString('utf8').split('\n').filter(Boolean).slice(0, 1000)
|
|
289
|
+
.map((line) => { try { return JSON.parse(line); } catch { return null; } }).filter(Boolean);
|
|
290
|
+
let delivered = events.length === 0;
|
|
291
|
+
|
|
292
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
293
|
+
// A new session's first prompt fires before Claude Code has written its
|
|
294
|
+
// transcript: send the snapshot anyway, with no lines yet.
|
|
295
|
+
let fd = null;
|
|
296
|
+
try { fd = openSync(transcript, 'r'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
297
|
+
let text = '';
|
|
298
|
+
let more = false;
|
|
299
|
+
if (fd !== null) try {
|
|
300
|
+
const available = fstatSync(fd).size - offset;
|
|
301
|
+
if (available > 0) {
|
|
302
|
+
const buffer = Buffer.alloc(Math.min(available, CHUNK));
|
|
303
|
+
readSync(fd, buffer, 0, buffer.length, offset);
|
|
304
|
+
const whole = buffer.lastIndexOf(10) + 1; // the last line may still be being written
|
|
305
|
+
text = buffer.subarray(0, whole).toString('utf8');
|
|
306
|
+
more = available > CHUNK && whole > 0;
|
|
307
|
+
}
|
|
308
|
+
} finally { closeSync(fd); }
|
|
309
|
+
const response = await fetch(BROKER, {
|
|
310
|
+
method: 'POST',
|
|
311
|
+
headers: { 'content-type': 'application/json', 'x-raytace-sandbox-token': token },
|
|
312
|
+
body: JSON.stringify({ session_id: session, hook_event_name: input.hook_event_name, offset, text, ...(snap ? { snapshot: snap } : {}),
|
|
313
|
+
...(delivered ? {} : { events }),
|
|
314
|
+
// A Playground fork's sandbox carries its own id (projects.py): RayTrace
|
|
315
|
+
// files the fork's steps under it, not under the project it forks.
|
|
316
|
+
...(/^rtf-[a-f0-9]{32}$/.test(process.env.RAYTRACE_SESSION ?? '') ? { fork: process.env.RAYTRACE_SESSION } : {}) }),
|
|
317
|
+
signal: AbortSignal.timeout(4000),
|
|
318
|
+
});
|
|
319
|
+
const body = await response.json().catch(() => ({}));
|
|
320
|
+
if (response.status === 409 && Number.isInteger(body.size)) { offset = body.size; continue; }
|
|
321
|
+
if (!response.ok || !Number.isInteger(body.size)) break;
|
|
322
|
+
if (!delivered) {
|
|
323
|
+
delivered = true;
|
|
324
|
+
try { writeFileSync(queuedFile, readFileSync(queuedFile).subarray(queued.length)); } catch { /* already gone */ }
|
|
325
|
+
}
|
|
326
|
+
offset = body.size;
|
|
327
|
+
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
328
|
+
writeFileSync(stateFile, String(offset));
|
|
329
|
+
if (!more) break;
|
|
330
|
+
}
|
|
331
|
+
} catch { /* RayTrace or the manager not running: stay silent */ }
|