@h1r-ai/croche-cli 0.5.4 → 0.6.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 +267 -148
- package/THIRD-PARTY-NOTICES +7 -8
- package/dist/bin.js +29 -25
- package/dist/chunk-66EUX7EL.js +165 -0
- package/dist/chunk-DKT5HHSB.js +532 -0
- package/dist/chunk-K3UDT4EM.js +3110 -0
- package/dist/collector-credential.d.ts +9 -0
- package/dist/config-authoring.d.ts +19 -0
- package/dist/config-bases.d.ts +17 -0
- package/dist/config-push-base-35HX67AJ.js +2254 -0
- package/dist/config-push-base.d.ts +7 -0
- package/dist/control-address.d.ts +2 -0
- package/dist/control-server.d.ts +12 -15
- package/dist/control-server.js +9 -288
- package/dist/control-v2-auth.d.ts +24 -0
- package/dist/control-v2-capture.d.ts +34 -0
- package/dist/control-v2-json.d.ts +15 -0
- package/dist/control-v2-state.d.ts +90 -0
- package/dist/credentials.d.ts +2 -2
- package/dist/debugger/public/index.html +1 -0
- package/dist/debugger/public/stage-control.js +84 -0
- package/dist/debugger/public/stage-manifest.js +45 -0
- package/dist/debugger/public/stage-model.js +103 -0
- package/dist/debugger/public/stage-targets.js +18 -0
- package/dist/debugger/public/stage.css +459 -0
- package/dist/debugger/public/stage.html +17 -0
- package/dist/debugger/public/stage.js +113 -0
- package/dist/debugger/server/collector.js +42 -26
- package/dist/debugger/server/control-bridge.js +113 -0
- package/dist/debugger/server/server.js +10 -1
- package/dist/debugger/server/viewer-security.js +12 -0
- package/dist/debugger.d.ts +16 -6
- package/dist/index.d.ts +8 -1
- package/dist/index.js +17 -321
- package/dist/json-result.d.ts +2 -0
- package/package.json +2 -1
- package/dist/config.js +0 -100
- package/dist/control-client.js +0 -65
- package/dist/core-defaults.js +0 -2
- package/dist/credentials.js +0 -136
- package/dist/debug-keys.js +0 -141
- package/dist/debugger.js +0 -469
- package/dist/help.js +0 -158
- package/dist/text-file.js +0 -15
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import {flowRows,flowCost,inspectable,inputBubbles} from './stage-model.js';
|
|
2
|
+
import {readStageManifestFile,manifestLabels} from './stage-manifest.js';
|
|
3
|
+
import {mountControl} from './stage-control.js';
|
|
4
|
+
import {liveAttachments,selectedAgent,agentKey} from './stage-targets.js';
|
|
5
|
+
const $=id=>document.getElementById(id);
|
|
6
|
+
let snapshot={events:[]},session='',selected='',stream,manifest=null,manifestGeneration=0,project='',refreshing=false,refreshAgain=false;
|
|
7
|
+
let live=[],remoteActive=false,remoteEvents=[],remoteLost=false;
|
|
8
|
+
const node=(tag,cls,text)=>{const n=document.createElement(tag);n.className=cls;if(text!==undefined)n.textContent=text;return n;};
|
|
9
|
+
const control=mountControl({getRuntime:()=>selectedAgent(live,project,session),onRemote:active=>{const wasRemote=remoteActive;remoteActive=active;if(!active){remoteEvents=[];remoteLost=false;live=Array.isArray(snapshot.attachments)?liveAttachments(snapshot.attachments):[];if(wasRemote)queueMicrotask(()=>void refresh());}},onCapture:(events,gaps)=>{const seen=new Set(remoteEvents.map(e=>JSON.stringify([e.runtimeInstanceId,e.id,e.openSequence,e.sequence])));for(const e of events){const key=JSON.stringify([e.runtimeInstanceId,e.id,e.openSequence,e.sequence]);if(!seen.has(key)){remoteEvents.push(e);seen.add(key);}}remoteLost ||= gaps.length>0;if(remoteEvents.length>2000){remoteEvents=remoteEvents.slice(-2000);remoteLost=true;}},onRoster:attachments=>{live=liveAttachments(attachments);render();}});
|
|
10
|
+
function detail(row){
|
|
11
|
+
selected=row.event.id;$('inspector').hidden=false;document.querySelector('.workbench').classList.add('inspecting');
|
|
12
|
+
$('detail-title').textContent=row.event.type;$('raw').replaceChildren();
|
|
13
|
+
$('tool-detail').replaceChildren();$('tool-detail').hidden=!['tool','failed'].includes(row.category);
|
|
14
|
+
if(!$('tool-detail').hidden){
|
|
15
|
+
const safe=row.related.filter(inspectable),start=safe.find(event=>event.type==='tool.started'),end=safe.findLast(event=>['tool.completed','tool.failed'].includes(event.type));
|
|
16
|
+
let args=start?.data?.args;
|
|
17
|
+
const requested=safe.find(event=>event.type==='tool.requested');
|
|
18
|
+
if(args===undefined&&requested){try{args=typeof requested.data.arguments==='string'?JSON.parse(requested.data.arguments):requested.data.arguments;}catch{args=requested.data.arguments;}}
|
|
19
|
+
for(const [label,value] of [['Args',args],['Result',end?.type==='tool.completed'?end.data.result:undefined],['Failure',end?.type==='tool.failed'?end.data.error:undefined]]){
|
|
20
|
+
if(value!==undefined){const section=node('section','tool-value');section.append(node('h3','',label),node('pre','',JSON.stringify(value,null,2)));$('tool-detail').append(section);}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
for(const event of [row.event,...row.related.filter(event=>event.id!==row.event.id)]){
|
|
24
|
+
const block=node('section','raw-event');block.append(node('h3','',event.type));
|
|
25
|
+
if(inspectable(event)){const pre=node('pre','',JSON.stringify(event,null,2));pre.tabIndex=0;block.append(pre);}
|
|
26
|
+
else block.append(node('p','withheld','Detail withheld: not a runtime-visibility event, or contains a model body. No rewritten JSON is presented as verbatim.'));
|
|
27
|
+
$('raw').append(block);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function render(){
|
|
31
|
+
const viewEvents=remoteActive?remoteEvents:snapshot.events;
|
|
32
|
+
if(remoteActive){$('health').textContent=remoteLost?'Remote capture incomplete':'Remote broker connected';$('notice').textContent=remoteLost?'Some events were dropped or withheld. This capture is incomplete.':'';}
|
|
33
|
+
const focused=document.activeElement?.closest('.flow-row')?.dataset.id;
|
|
34
|
+
if(!project&&live.length)project=live[0].attachmentId;
|
|
35
|
+
const attachment=live.find(a=>a.attachmentId===project);
|
|
36
|
+
const runtimeOptions=live.map(a=>new Option(`${a.runtime?.project??'Runtime'} · ${a.runtime?.platform??'unknown platform'} · ${a.attachmentId.slice(-8)}`,a.attachmentId));
|
|
37
|
+
if(!attachment){const missing=new Option(project?'Disconnected — choose a live Runtime':'No connected Runtime',project);missing.disabled=true;runtimeOptions.unshift(missing);}
|
|
38
|
+
$('projects').replaceChildren(...runtimeOptions);$('projects').value=project;
|
|
39
|
+
if(!session&&attachment?.agents.length)session=agentKey(attachment.agents.find(a=>a.open)??attachment.agents[0]);
|
|
40
|
+
const labels=manifestLabels(manifest,viewEvents);
|
|
41
|
+
const agentOptions=(attachment?.agents??[]).map(row=>{
|
|
42
|
+
const recent=viewEvents.findLast(e=>e.runtimeInstanceId===row.runtimeInstanceId&&e.openSequence===row.openSequence);
|
|
43
|
+
const label=recent?labels.get(JSON.stringify([recent.runtimeInstanceId,recent.sessionId])):undefined;
|
|
44
|
+
return new Option(`${row.agentId} · ${row.instance??'default'}${row.open?'':' · not opened'}${label?' · '+label:''}`,agentKey(row));
|
|
45
|
+
});
|
|
46
|
+
if(!attachment?.agents.some(row=>agentKey(row)===session)){const missing=new Option('Agent closed/reopened — choose its open row',session);missing.disabled=true;agentOptions.unshift(missing);}
|
|
47
|
+
$('sessions').replaceChildren(...agentOptions);$('sessions').value=session;
|
|
48
|
+
const active=selectedAgent(live,project,session),events=active?viewEvents.filter(e=>e.runtimeInstanceId===active.runtimeInstanceId&&e.openSequence===active.target.openSequence):[],rows=flowRows(events,$('all').checked);
|
|
49
|
+
$('count').textContent=`(${events.length})`;
|
|
50
|
+
const cost=flowCost(events);
|
|
51
|
+
$('summary').textContent=`${cost.calls} LLM calls · ${cost.cost===null?'Cost not reported':(cost.partial?'≥ ':'')+'$'+cost.cost.toFixed(4)}`;
|
|
52
|
+
const sameTurn=(a,b)=>a.projectId===b.projectId&&a.runtimeInstanceId===b.runtimeInstanceId&&a.sessionId===b.sessionId&&a.agentId===b.agentId&&a.turnId&&a.turnId===b.turnId;
|
|
53
|
+
const makeRow=row=>{
|
|
54
|
+
const side=row.category==='input'?'app':'croche';
|
|
55
|
+
const failed=row.category==='failed'||row.title.includes(' → failed');
|
|
56
|
+
const button=node('button','flow-row '+row.category+(row.category==='failed'?' tool':'')+' '+side+(failed?' call-failed':''));button.type='button';button.dataset.type=row.event.type;button.dataset.id=row.event.id;button.setAttribute('aria-pressed',String(row.event.id===selected));
|
|
57
|
+
const kinds={input:['↗','input'],reply:['↩','message'],tool:['⚒','tool'],failed:['⚒','tool'],model:['◈','LLM call'],marker:['◆','marker'],diagnostic:['·','event'],withheld:['⊘','withheld']};
|
|
58
|
+
const [symbol,kind]=kinds[row.category]||kinds.diagnostic;
|
|
59
|
+
const identity=node('div','identity'),icon=node('span','kind-icon',symbol);icon.setAttribute('aria-hidden','true');
|
|
60
|
+
identity.append(icon,node('small','',kind));
|
|
61
|
+
if(!['input','reply','marker','model'].includes(row.category))identity.append(node('b','',row.title));
|
|
62
|
+
if(!['input','reply'].includes(row.category))button.append(identity);
|
|
63
|
+
if(row.category==='input'){
|
|
64
|
+
const group=node('div','input-group');
|
|
65
|
+
for(const part of inputBubbles(row.event)){
|
|
66
|
+
const line=node('div','input-line'),bubble=button.cloneNode(false);
|
|
67
|
+
bubble.append(node('span','preview',part.text));
|
|
68
|
+
bubble.onclick=()=>{detail(row);$('close').focus();};
|
|
69
|
+
line.append(node('small','input-kind',part.kind),bubble);group.append(line);
|
|
70
|
+
}
|
|
71
|
+
return group;
|
|
72
|
+
}
|
|
73
|
+
// Calls show only the actual tool + command; arguments/results remain in exact detail.
|
|
74
|
+
if(!['tool','failed'].includes(row.category))button.append(node('span','preview',row.preview));
|
|
75
|
+
button.append(node('time','',String(row.event.timestamp).slice(11,23)));
|
|
76
|
+
button.onclick=()=>{detail(row);$('close').focus();};return button;
|
|
77
|
+
};
|
|
78
|
+
$('rows').classList.toggle('all-events',$('all').checked);
|
|
79
|
+
$('rows').replaceChildren(...rows.flatMap(row=>{
|
|
80
|
+
if(row.category==='marker'&&rows.some(reply=>reply.category==='reply'&&sameTurn(reply.event,row.event)))return [];
|
|
81
|
+
if(row.category!=='reply')return [makeRow(row)];
|
|
82
|
+
const group=node('div','reply-group');
|
|
83
|
+
const markers=node('div','reply-markers');
|
|
84
|
+
for(const marker of rows.filter(marker=>marker.category==='marker'&&sameTurn(marker.event,row.event)))markers.append(makeRow(marker));
|
|
85
|
+
if(markers.childNodes.length)group.append(markers);
|
|
86
|
+
group.append(makeRow(row));return [group];
|
|
87
|
+
}));
|
|
88
|
+
if(focused)[...$('rows').querySelectorAll('.flow-row')].find(el=>el.dataset.id===focused)?.focus({preventScroll:true});
|
|
89
|
+
if($('follow').checked)$('rows').scrollTop=$('rows').scrollHeight;
|
|
90
|
+
if(!rows.length)$('rows').append(node('p','empty','No flow events captured. An empty view is not a successful run.'));
|
|
91
|
+
const existing=rows.find(row=>row.event.id===selected);if(existing&&!$('inspector').hidden)detail(existing);
|
|
92
|
+
control.update();
|
|
93
|
+
}
|
|
94
|
+
async function refresh(){
|
|
95
|
+
if(refreshing){refreshAgain=true;return;}refreshing=true;
|
|
96
|
+
try{const response=await fetch('/api/state',{credentials:'same-origin',cache:'no-store'});if(!response.ok)throw Error('Viewer pairing required or collector disconnected. Displayed events may be stale.');snapshot=await response.json();
|
|
97
|
+
const lost=['evicted','pausedDropped','clientDropped'].some(key=>snapshot.stats?.[key]>0);
|
|
98
|
+
$('health').textContent=snapshot.paused?'Capture paused':lost?'Capture incomplete':'Collector connected';
|
|
99
|
+
$('notice').textContent=lost?'Events were dropped. This capture is incomplete.':snapshot.paused?'New events are not being captured.':snapshot.controlStatus==='disconnected'?'Control broker disconnected. Captures are historical, not liveness.':snapshot.controlStatus==='unconfigured'?'No live roster configured. Start the debugger with its v2 broker connection; captured data alone does not prove liveness.':'';
|
|
100
|
+
if(!remoteActive&&Array.isArray(snapshot.attachments))live=liveAttachments(snapshot.attachments);render();
|
|
101
|
+
}catch(e){$('health').textContent='Collector disconnected';$('notice').textContent=e.message;}
|
|
102
|
+
finally{refreshing=false;if(refreshAgain){refreshAgain=false;void refresh();}}
|
|
103
|
+
}
|
|
104
|
+
$('projects').onchange=e=>{project=e.target.value;session='';selected='';$('close').click();render();};
|
|
105
|
+
$('sessions').onchange=e=>{session=e.target.value;selected='';$('inspector').hidden=true;document.querySelector('.workbench').classList.remove('inspecting');render();};
|
|
106
|
+
$('all').onchange=render;
|
|
107
|
+
$('load-labels').onclick=()=>$('manifest-file').click();
|
|
108
|
+
$('clear-labels').onclick=()=>{manifestGeneration++;manifest=null;$('manifest-file').value='';$('clear-labels').hidden=true;$('label-status').textContent='Runner labels cleared. The same flow remains available.';render();};
|
|
109
|
+
$('manifest-file').onchange=async()=>{const generation=++manifestGeneration;try{const file=$('manifest-file').files[0];if(!file)return;const parsed=await readStageManifestFile(file);if(generation!==manifestGeneration)return;manifest=parsed;$('clear-labels').hidden=false;$('label-status').textContent='Browser-local labels · progress counts captured inputs, not completed steps.';render();}catch{if(generation!==manifestGeneration)return;manifest=null;$('clear-labels').hidden=true;$('label-status').textContent='Could not load runner labels. Unlabelled flow remains available.';render();}};
|
|
110
|
+
$('close').onclick=()=>{$('inspector').hidden=true;document.querySelector('.workbench').classList.remove('inspecting');[...$('rows').querySelectorAll('.flow-row')].find(el=>el.dataset.id===selected)?.focus({preventScroll:true});};
|
|
111
|
+
document.addEventListener('keydown',event=>{if(event.key==='Escape')$('close').click();});
|
|
112
|
+
async function start(){const token=new URLSearchParams(location.hash.slice(1)).get('token');history.replaceState(null,'',location.pathname);if(token){const r=await fetch('/api/pair',{method:'POST',headers:{Authorization:'Bearer '+token,'Content-Type':'application/json'},body:'{}'});if(!r.ok){$('health').textContent='Pairing failed';return;}}await refresh();stream=new EventSource('/api/stream');stream.addEventListener('change',refresh);stream.onerror=()=>{$('health').textContent='Collector disconnected · shown data may be stale';};}
|
|
113
|
+
window.addEventListener('pagehide',()=>stream?.close());void start();
|
|
@@ -49,6 +49,8 @@ export class DebugCollector {
|
|
|
49
49
|
/** Every stored event takes the next cursor, assigned before any visibility filtering. */
|
|
50
50
|
nextCursor = 1;
|
|
51
51
|
storedBytes = 0;
|
|
52
|
+
liveAttachments = [];
|
|
53
|
+
controlStatus = 'unconfigured';
|
|
52
54
|
observe;
|
|
53
55
|
pid;
|
|
54
56
|
onShutdown;
|
|
@@ -211,6 +213,44 @@ export class DebugCollector {
|
|
|
211
213
|
listener(); this.observe.wake(); }
|
|
212
214
|
/** Ends every Studio observation stream with `collector_stopping`. */
|
|
213
215
|
stop() { this.observe.end('collector_stopping'); }
|
|
216
|
+
/** Server-owned v2 read adapter only; no new HTTP intake or credential authority. */
|
|
217
|
+
acceptV2(value) { const event = this.validate(value); this.store(event); this.publish(); }
|
|
218
|
+
controlRoster(attachments, connected) {
|
|
219
|
+
const next = connected ? 'connected' : 'disconnected';
|
|
220
|
+
if (JSON.stringify(this.liveAttachments) === JSON.stringify(attachments) && this.controlStatus === next)
|
|
221
|
+
return;
|
|
222
|
+
this.liveAttachments = attachments;
|
|
223
|
+
this.controlStatus = next;
|
|
224
|
+
this.publish();
|
|
225
|
+
}
|
|
226
|
+
controlLoss(count) { if (Number.isSafeInteger(count) && count > 0) {
|
|
227
|
+
this.clientDropped += count;
|
|
228
|
+
this.publish();
|
|
229
|
+
} }
|
|
230
|
+
store(event) {
|
|
231
|
+
const key = keyOf(event);
|
|
232
|
+
if (this.seen.has(key))
|
|
233
|
+
return 'duplicate';
|
|
234
|
+
const bytes = Buffer.byteLength(JSON.stringify(event));
|
|
235
|
+
if (bytes > this.limits.bytes)
|
|
236
|
+
deny(413, 'Event exceeds total capture capacity.');
|
|
237
|
+
this.received++;
|
|
238
|
+
if (this.paused) {
|
|
239
|
+
this.pausedDropped++;
|
|
240
|
+
return 'accepted';
|
|
241
|
+
}
|
|
242
|
+
this.entries.push({ key, event, bytes, cursor: this.nextCursor++, offset: this.storedBytes });
|
|
243
|
+
this.storedBytes += bytes;
|
|
244
|
+
this.seen.add(key);
|
|
245
|
+
this.bytes += bytes;
|
|
246
|
+
while (this.entries.length > this.limits.events || this.bytes > this.limits.bytes) {
|
|
247
|
+
const removed = this.entries.shift();
|
|
248
|
+
this.seen.delete(removed.key);
|
|
249
|
+
this.bytes -= removed.bytes;
|
|
250
|
+
this.evicted++;
|
|
251
|
+
}
|
|
252
|
+
return 'accepted';
|
|
253
|
+
}
|
|
214
254
|
snapshot() {
|
|
215
255
|
const runtimes = new Map();
|
|
216
256
|
for (const { event } of this.entries) {
|
|
@@ -218,7 +258,7 @@ export class DebugCollector {
|
|
|
218
258
|
runtimes.set(event.runtimeInstanceId, { id: event.runtimeInstanceId, appName: event.appName ?? prior?.appName ?? 'Unnamed app', projectId: event.projectId, sessionId: event.sessionId, lastSeenAt: event.timestamp, events: (prior?.events ?? 0) + 1 });
|
|
219
259
|
}
|
|
220
260
|
return {
|
|
221
|
-
revision: this.revision, paused: this.paused, limits: this.limits,
|
|
261
|
+
revision: this.revision, paused: this.paused, limits: this.limits, attachments: this.liveAttachments, controlStatus: this.controlStatus,
|
|
222
262
|
stats: { received: this.received, retained: this.entries.length, bytes: this.bytes, evicted: this.evicted, pausedDropped: this.pausedDropped, clientDropped: this.clientDropped },
|
|
223
263
|
runtimes: [...runtimes.values()].reverse(), events: this.entries.map(entry => entry.event), turns: summarizeTurns(this.entries.map(entry => entry.event)),
|
|
224
264
|
};
|
|
@@ -235,31 +275,7 @@ export class DebugCollector {
|
|
|
235
275
|
try {
|
|
236
276
|
const event = this.validate(raw);
|
|
237
277
|
id = event.id;
|
|
238
|
-
|
|
239
|
-
if (this.seen.has(key)) {
|
|
240
|
-
ack.duplicate.push(id);
|
|
241
|
-
continue;
|
|
242
|
-
}
|
|
243
|
-
const bytes = Buffer.byteLength(JSON.stringify(event));
|
|
244
|
-
if (bytes > this.limits.bytes)
|
|
245
|
-
deny(413, 'Event exceeds the total capture capacity.');
|
|
246
|
-
this.received++;
|
|
247
|
-
if (this.paused) {
|
|
248
|
-
this.pausedDropped++;
|
|
249
|
-
ack.accepted.push(id);
|
|
250
|
-
continue;
|
|
251
|
-
}
|
|
252
|
-
this.entries.push({ key, event, bytes, cursor: this.nextCursor++, offset: this.storedBytes });
|
|
253
|
-
this.storedBytes += bytes;
|
|
254
|
-
this.seen.add(key);
|
|
255
|
-
this.bytes += bytes;
|
|
256
|
-
while (this.entries.length > this.limits.events || this.bytes > this.limits.bytes) {
|
|
257
|
-
const removed = this.entries.shift();
|
|
258
|
-
this.seen.delete(removed.key);
|
|
259
|
-
this.bytes -= removed.bytes;
|
|
260
|
-
this.evicted++;
|
|
261
|
-
}
|
|
262
|
-
ack.accepted.push(id);
|
|
278
|
+
ack[this.store(event)].push(id);
|
|
263
279
|
}
|
|
264
280
|
catch (error) {
|
|
265
281
|
ack.rejected.push({ id, reason: error instanceof HttpError ? error.message : 'Invalid event.' });
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
2
|
+
const count = (v) => Number.isSafeInteger(v) && Number(v) >= 0;
|
|
3
|
+
/** Read-only adapter. It has no ingest credential and cannot submit a command. */
|
|
4
|
+
export class ControlBridge {
|
|
5
|
+
options;
|
|
6
|
+
collector;
|
|
7
|
+
fetcher;
|
|
8
|
+
abort = new AbortController();
|
|
9
|
+
cursors = new Map();
|
|
10
|
+
busy = false;
|
|
11
|
+
timer;
|
|
12
|
+
origin;
|
|
13
|
+
constructor(options, collector, fetcher = fetch) {
|
|
14
|
+
this.options = options;
|
|
15
|
+
this.collector = collector;
|
|
16
|
+
this.fetcher = fetcher;
|
|
17
|
+
const url = new URL(options.origin);
|
|
18
|
+
if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) || url.pathname !== '/' || url.search || url.hash || url.username || url.password || !/^[A-Za-z0-9._~-]{24,4096}$/.test(options.token))
|
|
19
|
+
throw Error('Control bridge requires a loopback origin and separate read credential.');
|
|
20
|
+
this.origin = url.origin;
|
|
21
|
+
}
|
|
22
|
+
async call(path, body) {
|
|
23
|
+
const r = await this.fetcher(this.origin + '/v2/control' + path, { method: body === undefined ? 'GET' : 'POST', headers: { Authorization: 'Bearer ' + this.options.token, ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), credentials: 'omit', redirect: 'error', signal: AbortSignal.any([this.abort.signal, AbortSignal.timeout(5000)]) });
|
|
24
|
+
if (!r.ok) {
|
|
25
|
+
await r.body?.cancel().catch(() => { });
|
|
26
|
+
if ([401, 403, 409].includes(r.status))
|
|
27
|
+
this.stop();
|
|
28
|
+
throw Error('Control read refused.');
|
|
29
|
+
}
|
|
30
|
+
const reader = r.body?.getReader();
|
|
31
|
+
if (!reader)
|
|
32
|
+
throw Error('Empty control read.');
|
|
33
|
+
let bytes = 0;
|
|
34
|
+
const chunks = [];
|
|
35
|
+
try {
|
|
36
|
+
for (;;) {
|
|
37
|
+
const next = await reader.read();
|
|
38
|
+
if (next.done)
|
|
39
|
+
break;
|
|
40
|
+
bytes += next.value.byteLength;
|
|
41
|
+
if (bytes > 1024 * 1024)
|
|
42
|
+
throw Error('Control read exceeds bound.');
|
|
43
|
+
chunks.push(next.value);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await reader.cancel().catch(() => { });
|
|
48
|
+
reader.releaseLock();
|
|
49
|
+
}
|
|
50
|
+
const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, bytes)));
|
|
51
|
+
if (!object(value))
|
|
52
|
+
throw Error('Invalid control read.');
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
async poll() {
|
|
56
|
+
if (this.busy || this.abort.signal.aborted)
|
|
57
|
+
return;
|
|
58
|
+
this.busy = true;
|
|
59
|
+
try {
|
|
60
|
+
const value = await this.call('/attachments');
|
|
61
|
+
if (!Array.isArray(value.attachments) || value.attachments.length > 100)
|
|
62
|
+
throw Error('Invalid live roster.');
|
|
63
|
+
const attachments = value.attachments.filter(object).filter(a => a.state === 'connected');
|
|
64
|
+
for (const a of attachments) {
|
|
65
|
+
if (typeof a.attachmentId !== 'string' || !Array.isArray(a.agents) || !Array.isArray(a.capabilities))
|
|
66
|
+
throw Error('Invalid live roster.');
|
|
67
|
+
const id = a.attachmentId, after = this.cursors.get(id) ?? 0, result = await this.call('/read', { attachmentId: id, after });
|
|
68
|
+
if (result.attachmentId !== id || !count(result.through) || result.through < after || !Array.isArray(result.entries) || !Array.isArray(result.gaps))
|
|
69
|
+
throw Error('Uncorrelated control read.');
|
|
70
|
+
const events = [];
|
|
71
|
+
let last = after;
|
|
72
|
+
for (const row of result.entries) {
|
|
73
|
+
if (!object(row) || !count(row.cursor) || row.cursor <= last || row.cursor > result.through || !object(row.capture) || !count(row.capture.seq) || !object(row.capture.event))
|
|
74
|
+
throw Error('Invalid control cursor.');
|
|
75
|
+
last = row.cursor;
|
|
76
|
+
if (row.capture.event.type !== 'roster')
|
|
77
|
+
events.push(row.capture.event);
|
|
78
|
+
}
|
|
79
|
+
for (const gap of result.gaps) {
|
|
80
|
+
if (!object(gap) || !count(gap.from) || !count(gap.through) || gap.from > gap.through || gap.through > result.through)
|
|
81
|
+
throw Error('Invalid control loss.');
|
|
82
|
+
}
|
|
83
|
+
for (const event of events)
|
|
84
|
+
this.collector.acceptV2(event);
|
|
85
|
+
// Count each missing viewer cursor once, including private/withheld entries.
|
|
86
|
+
const ranges = result.gaps.map(g => ({ from: Math.max(after + 1, g.from), through: g.through })).filter(g => g.from <= g.through).sort((a, b) => a.from - b.from);
|
|
87
|
+
let end = after, lost = 0;
|
|
88
|
+
for (const g of ranges) {
|
|
89
|
+
lost += Math.max(0, g.through - Math.max(end, g.from - 1));
|
|
90
|
+
end = Math.max(end, g.through);
|
|
91
|
+
}
|
|
92
|
+
if (lost)
|
|
93
|
+
this.collector.controlLoss(lost);
|
|
94
|
+
this.cursors.set(id, result.through);
|
|
95
|
+
}
|
|
96
|
+
if (this.abort.signal.aborted)
|
|
97
|
+
return;
|
|
98
|
+
for (const id of this.cursors.keys())
|
|
99
|
+
if (!attachments.some(a => a.attachmentId === id))
|
|
100
|
+
this.cursors.delete(id);
|
|
101
|
+
this.collector.controlRoster(attachments, true);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
if (!this.abort.signal.aborted)
|
|
105
|
+
this.collector.controlRoster([], false);
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
this.busy = false;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
start() { void this.poll(); this.timer = setInterval(() => void this.poll(), 1000); this.timer.unref?.(); }
|
|
112
|
+
stop() { clearInterval(this.timer); this.abort.abort(); this.collector.controlRoster([], false); }
|
|
113
|
+
}
|
|
@@ -2,6 +2,8 @@ import { createServer } from 'node:http';
|
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
3
|
import { Readable } from 'node:stream';
|
|
4
4
|
import { DebugCollector } from './collector.js';
|
|
5
|
+
import { ControlBridge } from './control-bridge.js';
|
|
6
|
+
import { stagePolicy } from './viewer-security.js';
|
|
5
7
|
const port = Number(process.env.CROCHE_DEBUGGER_PORT ?? 8790);
|
|
6
8
|
// Dev Studio origins (comma-separated) beside https://studio.croche.ai: `croche debug start --studio-origin`.
|
|
7
9
|
const studioOrigins = (process.env.CROCHE_DEBUGGER_STUDIO_ORIGINS ?? '').split(',').map(origin => origin.trim()).filter(Boolean);
|
|
@@ -12,13 +14,20 @@ function shutdown() {
|
|
|
12
14
|
return;
|
|
13
15
|
stopping = true;
|
|
14
16
|
collector.stop();
|
|
17
|
+
bridge?.stop();
|
|
15
18
|
setTimeout(() => { server.closeAllConnections(); server.close(() => process.exit(0)); }, 100).unref();
|
|
16
19
|
// Exit even if a connection outlives close.
|
|
17
20
|
setTimeout(() => process.exit(0), 3000).unref();
|
|
18
21
|
}
|
|
19
22
|
const collector = new DebugCollector({ port, token: process.env.DEBUG_TOKEN ?? process.env.CROCHE_DEBUGGER_TOKEN, studioOrigins, pid: process.pid, onShutdown: shutdown });
|
|
23
|
+
const bridge = process.env.CROCHE_DEBUGGER_CONTROL_URL && process.env.CROCHE_DEBUGGER_CONTROL_TOKEN ? new ControlBridge({ origin: process.env.CROCHE_DEBUGGER_CONTROL_URL, token: process.env.CROCHE_DEBUGGER_CONTROL_TOKEN }, collector) : undefined;
|
|
24
|
+
bridge?.start();
|
|
20
25
|
const files = { '/': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/styles.css': ['styles.css', 'text/css; charset=utf-8'] };
|
|
26
|
+
files['/stage'] = ['stage.html', 'text/html; charset=utf-8'];
|
|
27
|
+
for (const name of ['stage.js', 'stage-model.js', 'stage-manifest.js', 'stage-control.js', 'stage-targets.js', 'stage.css'])
|
|
28
|
+
files['/' + name] = [name, name.endsWith('.css') ? 'text/css; charset=utf-8' : 'text/javascript; charset=utf-8'];
|
|
21
29
|
const securityHeaders = { 'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'Referrer-Policy': 'no-referrer', 'Cache-Control': 'no-store' };
|
|
30
|
+
const stageCsp = stagePolicy(securityHeaders['Content-Security-Policy'], (process.env.CROCHE_DEBUGGER_REMOTE_CONTROL_ORIGINS ?? '').split(',').filter(Boolean));
|
|
22
31
|
const server = createServer(async (incoming, outgoing) => {
|
|
23
32
|
const abort = new AbortController();
|
|
24
33
|
outgoing.on('close', () => abort.abort());
|
|
@@ -49,7 +58,7 @@ const server = createServer(async (incoming, outgoing) => {
|
|
|
49
58
|
return;
|
|
50
59
|
}
|
|
51
60
|
const content = await readFile(new URL(`../public/${file[0]}`, import.meta.url));
|
|
52
|
-
outgoing.writeHead(200, { ...securityHeaders, 'Content-Type': file[1] });
|
|
61
|
+
outgoing.writeHead(200, { ...securityHeaders, ...(path === '/stage' ? { 'Content-Security-Policy': stageCsp } : {}), 'Content-Type': file[1] });
|
|
53
62
|
outgoing.end(request.method === 'HEAD' ? undefined : content);
|
|
54
63
|
return;
|
|
55
64
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
/** Remote capture destinations are operator-configured, never inferred from page input. */
|
|
3
|
+
export function stagePolicy(base, remoteOrigins = []) {
|
|
4
|
+
if (remoteOrigins.length > 16)
|
|
5
|
+
throw Error('Too many remote viewer destinations.');
|
|
6
|
+
for (const origin of remoteOrigins) {
|
|
7
|
+
const url = new URL(origin), host = url.hostname.replace(/^\[|\]$/g, '');
|
|
8
|
+
if (url.protocol !== 'http:' || url.origin !== origin || !isIP(host) || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
|
|
9
|
+
throw Error('Remote viewer destinations must be exact HTTP IP origins.');
|
|
10
|
+
}
|
|
11
|
+
return base.replace("connect-src 'self'", "connect-src 'self' http://127.0.0.1:* http://localhost:* http://[::1]:*" + (remoteOrigins.length ? ' ' + [...new Set(remoteOrigins)].join(' ') : ''));
|
|
12
|
+
}
|
package/dist/debugger.d.ts
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
type Env = Record<string, string | undefined>;
|
|
2
2
|
type Kind = 'debugger' | 'control';
|
|
3
|
+
type Connection = {
|
|
4
|
+
url: string;
|
|
5
|
+
token: string;
|
|
6
|
+
file: string;
|
|
7
|
+
ingest_token?: string;
|
|
8
|
+
observe_token?: string;
|
|
9
|
+
remoteAddress?: string;
|
|
10
|
+
origins?: string[];
|
|
11
|
+
};
|
|
12
|
+
type LaunchOptions = {
|
|
13
|
+
studioOrigins?: string[];
|
|
14
|
+
control?: Pick<Connection, 'url' | 'token'>;
|
|
15
|
+
viewerOrigin?: string;
|
|
16
|
+
remoteControlOrigins?: string[];
|
|
17
|
+
};
|
|
3
18
|
export interface DebuggerContext {
|
|
4
19
|
env: Env;
|
|
5
20
|
fetch?: typeof fetch;
|
|
@@ -9,12 +24,7 @@ export interface DebuggerContext {
|
|
|
9
24
|
label: string;
|
|
10
25
|
}[]) => Promise<string | undefined>;
|
|
11
26
|
/** Embeddings/tests may supply a process launcher; credentials are never argv. */
|
|
12
|
-
launch?: (kind: Kind, connection:
|
|
13
|
-
url: string;
|
|
14
|
-
token: string;
|
|
15
|
-
}, options?: {
|
|
16
|
-
studioOrigins?: string[];
|
|
17
|
-
}) => Promise<number | void>;
|
|
27
|
+
launch?: (kind: Kind, connection: Connection, options?: LaunchOptions) => Promise<number | void>;
|
|
18
28
|
}
|
|
19
29
|
export declare function defaultConnectionFile(kind: Kind, env?: Env, port?: number): string;
|
|
20
30
|
export declare function debugCommand(action: string, args: Record<string, string>, context: DebuggerContext): Promise<any>;
|
package/dist/index.d.ts
CHANGED
|
@@ -15,8 +15,11 @@ export interface CliContext {
|
|
|
15
15
|
writeFile?: (path: string, text: string) => Promise<void>;
|
|
16
16
|
serveControl?: (options: {
|
|
17
17
|
token: string;
|
|
18
|
+
ingestToken: string;
|
|
19
|
+
observeToken?: string;
|
|
18
20
|
port: number;
|
|
19
21
|
origins: string[];
|
|
22
|
+
remoteAddress?: string;
|
|
20
23
|
}) => Promise<unknown>;
|
|
21
24
|
selectRuntime?: DebuggerContext['selectRuntime'];
|
|
22
25
|
launchDebuggerService?: DebuggerContext['launch'];
|
|
@@ -36,13 +39,17 @@ type Client = {
|
|
|
36
39
|
key: string;
|
|
37
40
|
source: 'env' | 'stored';
|
|
38
41
|
}>;
|
|
42
|
+
cloud: () => {
|
|
43
|
+
cloud_url: string;
|
|
44
|
+
studio_url: string | null;
|
|
45
|
+
};
|
|
39
46
|
readFile: (path: string, what: string) => Promise<string>;
|
|
40
47
|
context: CliContext;
|
|
41
48
|
env: Record<string, string | undefined>;
|
|
42
49
|
};
|
|
43
|
-
/** Declarative command tree: future Studio features add one descriptor. */
|
|
44
50
|
export declare const commands: readonly Command[];
|
|
45
51
|
export declare function help(prefix?: string): string;
|
|
52
|
+
export declare function studioUrl(origin: string): string | null;
|
|
46
53
|
export declare function runCli(argv: string[], context?: CliContext): Promise<number>;
|
|
47
54
|
export declare function readResponse(response: Response, limit?: number): Promise<any>;
|
|
48
55
|
export {};
|