@raytrace-cli/cli 0.17.16 → 0.18.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.
@@ -1,153 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { spawnSync } from 'node:child_process';
4
- import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs';
5
- import { join, resolve } from 'node:path';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import * as fsPromises from 'node:fs/promises';
8
- import { tmpdir } from 'node:os';
9
-
10
- const root = resolve(fileURLToPath(new URL('../../', import.meta.url)));
11
- const session = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
12
- const setup = (repo) => {
13
- const dir = mkdtempSync(join(tmpdir(), 'raytrace-delivery-'));
14
- const home = join(dir, 'isolated-home');
15
- const state = join(dir, 'offsets');
16
- const transcript = join(home, '.claude', 'projects', 'test', `${session}.jsonl`);
17
- mkdirSync(resolve(transcript, '..'), {recursive:true});
18
- mkdirSync(join(home,'.raytace'), {recursive:true});
19
- mkdirSync(join(home,'.raytace-codex'), {recursive:true});
20
- writeFileSync(join(home,'.raytace','sandbox-token'), 'synthetic-token');
21
- writeFileSync(join(home,'.raytace-codex','config.toml'), '"x-raytace-sandbox-token" = "synthetic-token"');
22
- const hookPath = fileURLToPath(new URL('./claude-hook.mjs', import.meta.url));
23
- const source = readFileSync(hookPath,'utf8')
24
- .replace("const home = process.env.HOME || '/home/node';", `const home = ${JSON.stringify(home)};`)
25
- .replace("const STATE_DIR = '/tmp/raytace-claude';", `const STATE_DIR = ${JSON.stringify(state)};`);
26
- const hook = join(dir,'hook.mjs'); writeFileSync(hook,source);
27
- const preloader = join(dir,'fake-transport.mjs');
28
- const adapter = pathToFileURL(resolve(root,'proxy/claude-code-adapter.mjs')).href;
29
- writeFileSync(preloader, `
30
- import {existsSync,readFileSync,writeFileSync,appendFileSync} from 'node:fs';
31
- import {join} from 'node:path';
32
- import {parseTranscript,exchangesFromTranscript} from ${JSON.stringify(adapter)};
33
- const dir=${JSON.stringify(dir)};
34
- globalThis.fetch=async (url,init)=>{
35
- const note=JSON.parse(init.body), calls=join(dir,'calls.jsonl'), server=join(dir,'received.txt');
36
- appendFileSync(calls, JSON.stringify({note,bytes:Buffer.byteLength(init.body)})+'\\n');
37
- const mode=JSON.parse(readFileSync(join(dir,'mode.json'),'utf8'));
38
- if(mode.grow){appendFileSync(${JSON.stringify(transcript)},mode.grow);writeFileSync(join(dir,'mode.json'),'{}');}
39
- let bytes=existsSync(server)?readFileSync(server):Buffer.alloc(0);
40
- const answer=(status,body)=>({status,ok:status===200,json:async()=>body});
41
- if(mode.fail) return answer(503,{});
42
- if(mode.conflict) return answer(409,{size:bytes.length});
43
- if(note.offset!==bytes.length) return answer(409,{size:bytes.length});
44
- bytes=Buffer.concat([bytes,Buffer.from(note.text)]);writeFileSync(server,bytes);
45
- if(mode.loseAck){writeFileSync(join(dir,'mode.json'),'{}');throw new Error('synthetic lost acknowledgement');}
46
- const lines=parseTranscript(bytes.toString('utf8'));
47
- const rows=exchangesFromTranscript(lines,{final:note.hook_event_name==='Stop'&&note.more!==true});
48
- for(const row of rows) appendFileSync(join(dir,'rows.jsonl'),JSON.stringify(row)+'\\n');
49
- return answer(200,{size:bytes.length});
50
- };`);
51
- writeFileSync(join(dir,'mode.json'),'{}');
52
- return {dir,state,transcript,run() {
53
- const result=spawnSync(process.execPath,['--import',preloader,hook],{
54
- input:JSON.stringify({session_id:session,transcript_path:transcript,hook_event_name:'Stop'}),
55
- encoding:'utf8',timeout:15000,maxBuffer:1024*1024,
56
- });
57
- assert.equal(result.error,undefined);assert.equal(result.status,0,result.stderr);
58
- }, calls(){return readFileSync(join(dir,'calls.jsonl'),'utf8').trim().split('\n').map(JSON.parse);},
59
- mode(value){writeFileSync(join(dir,'mode.json'),JSON.stringify(value));},
60
- offset(){return existsSync(join(state,`${session}.offset`))?Number(readFileSync(join(state,`${session}.offset`),'utf8')):0;},
61
- received(){return existsSync(join(dir,'received.txt'))?readFileSync(join(dir,'received.txt'),'utf8'):'';},
62
- close(){rmSync(dir,{recursive:true,force:true});}};
63
- };
64
- for (const repo of ['local']) {
65
- test(`${repo}: actual hook drains escaped oversized lines across UTF-8 boundaries and finalizes only once`,()=>{
66
- const fixture=setup(repo);
67
- try {
68
- const line=(type,message,extra={})=>JSON.stringify({type,sessionId:session,timestamp:'2026-10-28T00:00:00Z',message,...extra})+'\n';
69
- const raw=line('user',{content:'synthetic prompt'})
70
- +line('assistant',{id:'message',content:[{type:'text',text:'first part'}]},{requestId:'request'})
71
- +line('user',{content:[{type:'tool_result',tool_use_id:'call',content:'\\'.repeat(2_500_000)+'😀'.repeat(300_000)}]})
72
- +line('assistant',{id:'message',content:[{type:'text',text:'last part'}]},{requestId:'request'});
73
- writeFileSync(fixture.transcript,raw);fixture.run();
74
- assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
75
- const calls=fixture.calls();assert.ok(calls.length>8);
76
- assert.ok(calls.every(c=>c.bytes<=4*1024*1024));
77
- assert.ok(calls.slice(0,-1).every(c=>c.note.more===true));assert.equal(calls.at(-1).note.more,false);
78
- const rows=readFileSync(join(fixture.dir,'rows.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
79
- assert.equal(rows.length,1);assert.equal(rows[0].response.payload.output.length,2);
80
- } finally {fixture.close();}
81
- });
82
- test(`${repo}: failed send retains offset and retry delivers exact bytes`,()=>{
83
- const fixture=setup(repo);try {
84
- const raw=JSON.stringify({type:'user',message:{content:'hello 😀'}})+'\n';
85
- writeFileSync(fixture.transcript,raw);fixture.mode({fail:true});fixture.run();
86
- assert.equal(fixture.offset(),0);assert.equal(fixture.received(),'');
87
- fixture.mode({});fixture.run();assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
88
- } finally {fixture.close();}
89
- });
90
- test(`${repo}: lost acknowledgement resumes with 409 without duplicating bytes`,()=>{
91
- const fixture=setup(repo);try {
92
- const raw=JSON.stringify({type:'user',message:{content:'hello'}})+'\n';
93
- writeFileSync(fixture.transcript,raw);fixture.mode({loseAck:true});fixture.run();
94
- assert.equal(fixture.offset(),0);assert.equal(fixture.received(),raw);
95
- fixture.run();assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
96
- } finally {fixture.close();}
97
- });
98
- test(`${repo}: drain stops at entry size and a later hook sends concurrently appended bytes`,()=>{
99
- const fixture=setup(repo);try {
100
- const raw=JSON.stringify({type:'user',message:{content:'initial'}})+'\n';
101
- const added=JSON.stringify({type:'user',message:{content:'appended during send'}})+'\n';
102
- writeFileSync(fixture.transcript,raw);fixture.mode({grow:added});fixture.run();
103
- assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
104
- fixture.run();assert.equal(fixture.received(),raw+added);
105
- } finally {fixture.close();}
106
- });
107
- test(`${repo}: repeated conflicts have a bounded retry budget`,()=>{
108
- const fixture=setup(repo);try {
109
- writeFileSync(fixture.transcript,'{}\n');fixture.mode({conflict:true});fixture.run();
110
- assert.equal(fixture.calls().length,8);assert.equal(fixture.offset(),0);
111
- } finally {fixture.close();}
112
- });
113
- }
114
-
115
- const sessionPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
116
- for (const repo of ['local']) {
117
- test(`${repo}: real receiver accepts partial lines, enforces byte offsets and validates fragment flags`,async()=>{
118
- const dir=mkdtempSync(join(tmpdir(), 'raytrace-receiver-'));
119
- try {
120
- const source=readFileSync(resolve(root,'proxy/raytace-proxy.mjs'),'utf8');
121
- const start=source.indexOf('async function appendSandboxTranscript(');
122
- const end=source.indexOf('\n/**',start);
123
- const fn=new Function('join','sandboxTranscripts','CLAUDE_SESSION_ID','serially','mkdir','stat','appendFile',
124
- `${source.slice(start,end)};return appendSandboxTranscript;`)(join,dir,sessionPattern,(_path,job)=>job(),fsPromises.mkdir,fsPromises.stat,fsPromises.appendFile);
125
- const initial={session_id:session,offset:0,text:'{"value":"😀',more:true};
126
- const first=await fn('rtp-synthetic',initial);assert.equal(first.status,200);
127
- assert.equal(first.body.size,Buffer.byteLength(initial.text));
128
- const duplicate=await fn('rtp-synthetic',initial);assert.equal(duplicate.status,409);assert.equal(duplicate.body.size,first.body.size);
129
- const tail={session_id:session,offset:first.body.size,text:'"}\n',more:false};
130
- const final=await fn('rtp-synthetic',tail);assert.equal(final.status,200);
131
- assert.equal(readFileSync(join(dir,'rtp-synthetic',`${session}.jsonl`),'utf8'),initial.text+tail.text);
132
- assert.equal((await fn('rtp-synthetic',{...tail,offset:final.body.size,more:'false'})).status,400);
133
- assert.equal((await fn('rtp-synthetic',{...tail,offset:-1})).status,400);
134
- assert.equal((await fn('rtp-synthetic',{...tail,session_id:'../../bad'})).status,400);
135
- // Existing whole-line senders remain accepted without the new flag.
136
- assert.equal((await fn('rtp-synthetic',{session_id:session,offset:final.body.size,text:'{}\n'})).status,200);
137
- } finally {rmSync(dir,{recursive:true,force:true});}
138
- });
139
- test(`${repo}: actual serialized envelope is bounded and queued metadata is retained`,()=>{
140
- const fixture=setup(repo);try {
141
- mkdirSync(fixture.state,{recursive:true});
142
- const event={id:'synthetic-large-event',detail:'x'.repeat(3_700_000)};
143
- const queue=join(fixture.state,`${session}.events.jsonl`);
144
- writeFileSync(queue,JSON.stringify(event)+'\n');
145
- const raw=JSON.stringify({type:'user',message:{content:'\\'.repeat(400_000)}})+'\n';
146
- writeFileSync(fixture.transcript,raw);fixture.run();
147
- assert.equal(fixture.received(),raw);
148
- const calls=fixture.calls();assert.ok(calls.length>1);assert.ok(calls.every(c=>c.bytes<=4*1024*1024));
149
- assert.deepEqual(calls[0].note.events,[event]);assert.equal(readFileSync(queue,'utf8'),'');
150
- } finally {fixture.close();}
151
- });
152
- }
153
-