@h1r-ai/croche-cli 0.0.0-stage → 0.5.1
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/LICENSE +32 -0
- package/README.md +468 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +26 -0
- package/dist/config.d.ts +10 -0
- package/dist/config.js +100 -0
- package/dist/control-client.d.ts +1 -0
- package/dist/control-client.js +65 -0
- package/dist/control-server.d.ts +29 -0
- package/dist/control-server.js +288 -0
- package/dist/core-defaults.d.ts +1 -0
- package/dist/core-defaults.js +2 -0
- package/dist/credentials.d.ts +17 -0
- package/dist/credentials.js +136 -0
- package/dist/debug-keys.d.ts +19 -0
- package/dist/debug-keys.js +141 -0
- package/dist/debugger/public/app.js +271 -0
- package/dist/debugger/public/index.html +71 -0
- package/dist/debugger/public/styles.css +4 -0
- package/dist/debugger/server/collector.js +460 -0
- package/dist/debugger/server/observe.js +286 -0
- package/dist/debugger/server/server.js +89 -0
- package/dist/debugger/server/turns.js +94 -0
- package/dist/debugger.d.ts +21 -0
- package/dist/debugger.js +468 -0
- package/dist/help.d.ts +24 -0
- package/dist/help.js +158 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +321 -0
- package/dist/text-file.d.ts +7 -0
- package/dist/text-file.js +15 -0
- package/package.json +41 -4
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<meta name="color-scheme" content="dark" />
|
|
7
|
+
<title>Croche · Runtime debugger</title>
|
|
8
|
+
<link rel="stylesheet" href="/styles.css" />
|
|
9
|
+
<script src="/app.js" defer></script>
|
|
10
|
+
</head>
|
|
11
|
+
<body>
|
|
12
|
+
<header class="app-header">
|
|
13
|
+
<a class="brand" href="/" aria-label="Croche Runtime debugger">
|
|
14
|
+
<span class="brand-mark" aria-hidden="true">c</span>
|
|
15
|
+
<span><span class="brand-name">croche</span><span class="brand-divider">/</span><span class="brand-product">Runtime debugger</span></span>
|
|
16
|
+
</a>
|
|
17
|
+
<div class="header-actions">
|
|
18
|
+
<span id="connection-status" class="connection-status"><span class="status-dot"></span><span>Connecting</span></span>
|
|
19
|
+
<button id="connect-app" class="button button-primary">CLI connection <span aria-hidden="true">↗</span></button>
|
|
20
|
+
</div>
|
|
21
|
+
</header>
|
|
22
|
+
|
|
23
|
+
<main>
|
|
24
|
+
<section class="page-heading">
|
|
25
|
+
<div><p class="eyebrow">LOCAL DEVELOPMENT</p><h1>See what your Runtime is doing.</h1><p class="subtitle">Follow each input through the model, its tools, and the final response.</p></div>
|
|
26
|
+
<div class="capture-actions">
|
|
27
|
+
<button id="capture-toggle" class="button" disabled>Pause capture</button>
|
|
28
|
+
<a id="export-capture" href="/api/export" class="button" download>Export JSON</a>
|
|
29
|
+
<button id="clear-capture" class="button button-quiet" disabled>Clear</button>
|
|
30
|
+
</div>
|
|
31
|
+
</section>
|
|
32
|
+
|
|
33
|
+
<div id="notice" class="notice" role="status" hidden></div>
|
|
34
|
+
<section id="overview" class="overview" aria-label="Capture overview"></section>
|
|
35
|
+
|
|
36
|
+
<section class="trace-explorer" aria-label="Runtime trace explorer">
|
|
37
|
+
<div class="filters">
|
|
38
|
+
<label class="search-box"><span aria-hidden="true">⌕</span><input id="search" type="search" placeholder="Search inputs, tools, IDs, or content…" aria-label="Search trace" /></label>
|
|
39
|
+
<label><span class="sr-only">Runtime filter</span><select id="runtime-filter"><option value="">All runtimes</option></select></label>
|
|
40
|
+
<label><span class="sr-only">Event type filter</span><select id="type-filter"><option value="">All event types</option></select></label>
|
|
41
|
+
</div>
|
|
42
|
+
<div class="workbench">
|
|
43
|
+
<aside class="turn-column" aria-label="Captured turns">
|
|
44
|
+
<div class="column-heading"><h2>Turns</h2><span id="turn-count" class="count">0</span></div>
|
|
45
|
+
<div id="turn-list" class="turn-list"></div>
|
|
46
|
+
</aside>
|
|
47
|
+
<section id="inspector" class="inspector" aria-label="Selected turn inspector" aria-live="polite"></section>
|
|
48
|
+
</div>
|
|
49
|
+
</section>
|
|
50
|
+
<footer><span><span class="local-dot" aria-hidden="true"></span>Local capture · held in memory</span><span id="retention-note">Waiting for collector limits</span></footer>
|
|
51
|
+
</main>
|
|
52
|
+
|
|
53
|
+
<dialog id="connection-dialog" class="connection-dialog">
|
|
54
|
+
<div class="dialog-heading"><div><p class="eyebrow">CLI CONNECTION</p><h2>Inspect an attached Runtime</h2></div><button id="close-dialog" class="icon-button" aria-label="Close connection dialog">×</button></div>
|
|
55
|
+
<p class="dialog-description">Keep your app open. Run <code>croche debug</code>, choose its Runtime, then open the URL printed by the CLI. The CLI starts or reuses this server and attaches the selected Runtime.</p>
|
|
56
|
+
<div class="snippet-heading"><h3>Run in your terminal</h3><button id="copy-command" class="button button-small" type="button">Copy command</button></div>
|
|
57
|
+
<pre id="connection-commands" class="code-block snippet" tabindex="0">croche debug</pre>
|
|
58
|
+
<form id="pair-form">
|
|
59
|
+
<p class="dialog-description">Opened the server without its authenticated URL? Run <code>croche debug token</code> and enter that token here to authorize this viewer.</p>
|
|
60
|
+
<label for="pair-token">Viewer access token</label>
|
|
61
|
+
<div class="input-action"><input id="pair-token" type="password" autocomplete="off" placeholder="Token from croche debug token" required /><button class="button button-primary" type="submit">Authorize viewer</button></div>
|
|
62
|
+
<p id="pair-error" class="form-error" role="alert"></p>
|
|
63
|
+
</form>
|
|
64
|
+
<div id="connection-details" hidden>
|
|
65
|
+
<div class="paired-label"><span class="local-dot"></span>Viewer authorized for this local server</div>
|
|
66
|
+
<p class="dialog-description">Use the CLI to attach another Runtime. Select a captured Runtime above to inspect its events and turns.</p>
|
|
67
|
+
<p class="privacy-note">Full visibility includes system prompts, conversation content, tool data and provider reasoning. Use it in development only. Runtime authentication and provider keys are never captured.</p>
|
|
68
|
+
</div>
|
|
69
|
+
</dialog>
|
|
70
|
+
</body>
|
|
71
|
+
</html>
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
@font-face{font-family:LocalMono;src:local("SFMono-Regular"),local("Cascadia Code"),local("Liberation Mono")}*{box-sizing:border-box}html{background:#101412;color:#e6ebe6;font:14px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}body{margin:0}button,input,select{font:inherit}button,a,input,select{touch-action:manipulation}button,a{ -webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{opacity:.45;cursor:default}a{color:inherit;text-decoration:none}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,pre:focus-visible{outline:2px solid #b2d7a7;outline-offset:3px}h1,h2,h3,p{margin:0}h1{font-size:28px;font-weight:550;letter-spacing:-1px;line-height:1.25}h2{font-size:16px;font-weight:600;letter-spacing:-.3px}h3{font-size:13px;font-weight:600}button{color:inherit}input,select{background:#171d19;border:1px solid #343e35;color:#e1e8e0;border-radius:7px;min-height:38px;padding:8px 11px;max-width:100%}input::placeholder{color:#7d897d}select{padding-right:30px}.app-header{height:77px;padding:0 36px;border-bottom:1px solid #29312a;display:flex;align-items:center;justify-content:space-between;background:#121713}.brand{display:flex;align-items:center;gap:12px}.brand-mark{width:35px;height:35px;border:1px solid #779172;border-radius:50%;display:grid;place-items:center;font:italic 29px/1 Georgia,serif;color:#c4deb9;padding-bottom:4px}.brand-name{font:25px Georgia,serif;letter-spacing:-1px}.brand-divider{margin:0 16px;color:#647061;font-size:19px;font-weight:300}.brand-product{font-size:14px;color:#b0baad}.header-actions{display:flex;align-items:center;gap:22px}.connection-status{display:flex;align-items:center;gap:8px;font-size:12px;color:#a8b4a5}.status-dot,.local-dot{height:6px;width:6px;display:inline-block;border-radius:50%;background:#667465;flex-shrink:0}.connection-status.connected .status-dot,.local-dot{background:#a7cd95;box-shadow:0 0 0 4px #a7cd950b}.connection-status.error .status-dot{background:#e5a294}.connection-status.paused .status-dot{background:#d4b777}.button{display:inline-flex;align-items:center;justify-content:center;gap:9px;min-height:36px;border:1px solid #3a443a;border-radius:7px;background:#1b231d;padding:7px 12px;font-size:12px;font-weight:550;white-space:nowrap;transition:background .15s,border-color .15s}.button:hover:not(:disabled){background:#293429;border-color:#5e715b}.button-primary{background:#bbd8ab;border-color:#bbd8ab;color:#182117}.button-primary:hover:not(:disabled){background:#cce4be;border-color:#cce4be}.button-quiet{background:transparent;color:#aab6a6;border-color:transparent}.button-small{min-height:27px;padding:3px 9px;font-size:11px}.icon-button{border:0;background:none;font-size:27px;line-height:1;color:#a8b5a3;padding:8px}.eyebrow{font-size:10px;letter-spacing:1.6px;font-weight:650;color:#82947b;margin-bottom:10px}.page-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:22px;margin:36px 0 28px}.subtitle{margin-top:10px;color:#8d9b88;font-size:13px}.capture-actions{display:flex;gap:7px;align-items:center;padding-bottom:2px}main{max-width:1700px;padding:0 36px;margin:auto}.overview{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));border:1px solid #2e382e;border-radius:10px;margin-bottom:24px;background:#151b16;overflow:hidden}.metric{padding:18px 22px;border-right:1px solid #2e382e}.metric:last-child{border-right:0}.metric-label{font-size:11px;color:#93a08d;display:flex;justify-content:space-between;gap:8px}.metric-value{font-size:26px;letter-spacing:-.9px;font-variant-numeric:tabular-nums;line-height:1.2;margin:7px 0 4px}.metric-value.good{color:#bedcb1}.metric-value.warning{color:#ddbe7b}.metric-foot{font-size:11px;color:#71806d}.trace-explorer{border:1px solid #2e382e;border-radius:10px;overflow:hidden;background:#131914}.filters{padding:14px 16px;display:flex;gap:10px;border-bottom:1px solid #2e382e;background:#171e18}.filters>label:not(.search-box){max-width:230px}.filters select{width:100%;font-size:12px}.search-box{flex:1;display:flex;align-items:center;gap:9px;min-width:100px;color:#92a48a}.search-box>span{font-size:24px;line-height:1}.search-box input{width:100%;border-color:transparent;background:transparent;padding-left:0;font-size:12px}.workbench{display:grid;grid-template-columns:300px minmax(0,1fr);min-height:610px}.turn-column{border-right:1px solid #2e382e;background:#151c16;min-width:0}.column-heading{padding:17px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #263027}.column-heading h2{font-size:12px}.count{font-size:10px;color:#98a892;background:#273327;border-radius:5px;min-width:24px;text-align:center;padding:2px 6px}.turn-list{max-height:calc(100vh - 360px);min-height:390px;overflow:auto;padding:8px}.turn-card{display:block;width:100%;text-align:left;border:1px solid transparent;background:none;border-radius:7px;padding:13px 12px;margin-bottom:5px;color:#dbe4d6}.turn-card:hover{background:#1b251c}.turn-card.selected{border-color:#516747;background:#253221;box-shadow:inset 3px 0 #a8cc92}.turn-top{display:flex;justify-content:space-between;align-items:center;gap:9px;margin-bottom:8px}.turn-app{font-size:10px;color:#a3b59a;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:160px}.turn-time{font:10px LocalMono,monospace;color:#788974;white-space:nowrap}.turn-title{font-size:12px;line-height:1.6;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;overflow-wrap:anywhere;min-height:19px}.turn-bottom{display:flex;justify-content:space-between;align-items:center;gap:6px;margin-top:12px;font-size:10px;color:#879980}.turn-cost{font:10px LocalMono,monospace;color:#bed4b3}.state{display:inline-flex;align-items:center;gap:5px;font-size:10px;white-space:nowrap}.state:before{content:"";display:inline-block;width:5px;height:5px;background:#9dac96;border-radius:50%}.state.completed:before{background:#b6d6a6}.state.failed:before,.state.interrupted:before{background:#e89c87}.state.cancelled:before{background:#c6b489}.inspector{min-width:0;max-height:calc(100vh - 300px);overflow:auto;min-height:610px}.empty-state{padding:75px 30px;min-height:560px;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center}.empty-mark{display:grid;place-items:center;width:64px;height:64px;border-radius:16px;border:1px solid #3a4c35;background:#1c291b;color:#b2d1a2;font:26px LocalMono,monospace;margin-bottom:22px}.empty-state h2{font-size:20px;font-weight:500;letter-spacing:-.5px;margin-bottom:9px}.empty-state p{color:#869780;max-width:390px;font-size:12px;margin-bottom:22px}.list-empty{padding:30px 16px;color:#84957d;font-size:12px;text-align:center}.inspection-heading{padding:22px 25px 19px;border-bottom:1px solid #2e382e}.inspection-topline{display:flex;justify-content:space-between;align-items:center;gap:12px}.inspection-label{font-size:10px;color:#819376;text-transform:uppercase;letter-spacing:1.1px}.inspection-input{font-size:18px;line-height:1.5;font-weight:500;letter-spacing:-.4px;margin:10px 0 12px;overflow-wrap:anywhere}.badges{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.badge{font-size:10px;line-height:1.4;color:#a3b49a;border:1px solid #354830;background:#1c2919;padding:4px 7px;border-radius:4px}.badge.warning{border-color:#6b572c;background:#302819;color:#dfc287}.badge.error{border-color:#684134;background:#342119;color:#e7b09e}.identifier{font:10px/1.7 LocalMono,monospace;color:#74876b;overflow-wrap:anywhere;margin-top:10px}.turn-metrics{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;padding:16px 25px;border-bottom:1px solid #2b362b;background:#172017}.small-metric-label{font-size:10px;color:#809278;margin-bottom:3px}.small-metric-value{font:13px LocalMono,monospace;color:#c8d9bf;overflow-wrap:anywhere}.subset-note{font-size:10px;color:#73886a;padding:9px 25px;background:#172017;border-bottom:1px solid #2b362b}.tabs{display:flex;gap:20px;padding:0 25px;border-bottom:1px solid #2b362b;position:sticky;top:0;background:#141c15;z-index:2}.tab{border:0;border-bottom:2px solid transparent;background:none;color:#8c9f83;padding:13px 0 11px;font-size:11px}.tab.selected{color:#c6deb9;border-bottom-color:#b6d49f}.inspection-body{padding:20px 25px 26px}.section-label{display:flex;justify-content:space-between;align-items:center;font-size:11px;color:#a7b99d;margin-bottom:12px}.call-card{border:1px solid #354431;border-radius:8px;margin:0 0 13px;background:#171f17;overflow:hidden}.call-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:13px 14px;border-bottom:1px solid #2d3b29}.call-identity{display:flex;align-items:center;gap:10px;min-width:0}.call-number{font:11px LocalMono,monospace;color:#a9c795;width:29px;height:29px;display:grid;place-items:center;background:#2a3a23;border-radius:5px}.call-name{font-size:12px;color:#d1dfc7;overflow-wrap:anywhere}.call-description{font-size:10px;color:#84957c;margin-top:2px}.call-money{font:11px LocalMono,monospace;color:#bed6ae;white-space:nowrap}.call-usage{padding:10px 14px;display:flex;gap:17px;flex-wrap:wrap;border-bottom:1px solid #2b3828;font-size:10px;color:#889d7e}.call-usage strong{font:11px LocalMono,monospace;font-weight:400;color:#bbceb0;margin-left:4px}.call-flags{padding:11px 14px;border-bottom:1px solid #2b3828}.fold{border-bottom:1px solid #2a3727}.fold:last-child{border-bottom:0}.fold>summary{cursor:pointer;list-style:none;display:flex;justify-content:space-between;align-items:center;gap:9px;padding:12px 14px;font-size:11px;color:#adc39f;user-select:none}.fold>summary::-webkit-details-marker{display:none}.fold>summary:after{content:"+";font:17px LocalMono,monospace;color:#769369}.fold[open]>summary:after{content:"−"}.fold-content{padding:0 14px 14px;min-width:0}.code-block{font:11px/1.75 LocalMono,"SFMono-Regular",Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#0f160f;border:1px solid #2a3926;border-radius:5px;padding:12px;margin:0;max-height:420px;overflow:auto;color:#b6caaa;tab-size:2}.message{border:1px solid #30432b;border-radius:6px;margin-bottom:9px;overflow:hidden}.message-role{padding:7px 10px;font:10px LocalMono,monospace;color:#a6c092;background:#24351f;border-bottom:1px solid #30432b;display:flex;justify-content:space-between}.message .code-block{border:0;border-radius:0;max-height:300px}.message.system .message-role{color:#d4c69b;background:#302c1e;border-color:#4c422b}.message.system{border-color:#4c422b}.message.tool .message-role{color:#a7c6cd;background:#1a3033}.response-label{font-size:10px;color:#8aa17e;margin:12px 0 6px}.response-label:first-child{margin-top:0}.response-reasoning{border-color:#413947;color:#c0aec9;background:#19141d}.inner-note{padding:10px 12px;border:1px dashed #42513b;border-radius:5px;color:#a3b398;background:#1b2718;font-size:11px;line-height:1.65;margin-bottom:12px}.inner-note.warning{color:#cbb27a;background:#282317;border-color:#665a35}.timeline{display:flex;flex-direction:column;gap:7px}.event-button{width:100%;display:flex;align-items:center;gap:12px;text-align:left;padding:12px;border:1px solid #2f402a;border-radius:6px;background:#172116}.event-button:hover,.event-button.selected{background:#22311e;border-color:#556d47}.event-sequence{font:10px LocalMono,monospace;color:#789169;min-width:26px}.event-info{flex:1;min-width:0}.event-type{font:11px LocalMono,monospace;color:#c0d6b2}.event-description{font-size:10px;color:#7f9973;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:3px}.event-detail{margin:0 0 8px}.event-detail .code-block{max-height:500px}.notice{padding:12px 15px;border:1px solid #604f2b;border-radius:7px;background:#282318;color:#d1b780;font-size:12px;margin-bottom:16px}.notice.error{background:#2e201a;border-color:#674435;color:#e5b09c}.notice:empty{display:none}footer{display:flex;justify-content:space-between;gap:15px;margin:18px 1px 26px;font-size:10px;color:#6e8465}footer>span:first-child{display:flex;gap:9px;align-items:center}.connection-dialog{background:#172017;color:#d0dfc7;border:1px solid #475e3b;border-radius:12px;padding:26px;width:650px;max-width:calc(100vw - 30px);max-height:90vh;box-shadow:0 25px 120px #000a}.connection-dialog::backdrop{background:#071005cf;backdrop-filter:blur(5px)}.dialog-heading{display:flex;justify-content:space-between;align-items:flex-start}.dialog-heading h2{font-size:22px;font-weight:500;letter-spacing:-.7px}.dialog-heading .eyebrow{margin-bottom:6px}.dialog-description{font-size:12px;color:#8fa482;margin:15px 0 20px}.connection-dialog label{font-size:11px;color:#a4ba96;display:block;margin:12px 0 7px}.input-action{display:flex;gap:7px}.input-action input{min-width:0;flex:1;font:12px LocalMono,monospace;background:#111b10}.form-error{font-size:12px;color:#e1a08a;margin-top:9px}.paired-label{font-size:11px;color:#b7d5a4;display:flex;align-items:center;gap:9px;margin-bottom:20px}.snippet-heading{display:flex;align-items:center;justify-content:space-between;margin:23px 0 9px}.snippet{font-size:10px;line-height:1.75;max-height:330px}.privacy-note{font-size:11px;color:#8aa07c;line-height:1.75;margin-top:16px}.sr-only{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}[hidden]{display:none!important}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-thumb{background:#364831;border:2px solid #151c16;border-radius:10px}::-webkit-scrollbar-track{background:#141b14}
|
|
2
|
+
@media(min-width:1550px){.workbench{grid-template-columns:340px minmax(0,1fr)}.turn-list{max-height:760px}.inspector{max-height:800px}}
|
|
3
|
+
@media(max-width:1100px){main{padding:0 22px}.app-header{padding:0 22px}.page-heading{align-items:flex-start;flex-direction:column;gap:18px}.page-heading h1{font-size:25px}.workbench{grid-template-columns:265px minmax(0,1fr)}.turn-metrics{grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.inspection-heading,.inspection-body{padding-left:18px;padding-right:18px}.tabs{padding:0 18px}.turn-list{max-height:720px}.inspector{max-height:850px}.metric{padding:16px}.filters>label:not(.search-box){max-width:180px}}
|
|
4
|
+
@media(max-width:700px){.app-header{height:67px;padding:0 16px}.brand-mark{width:29px;height:29px;font-size:24px}.brand{gap:8px}.brand-name{font-size:23px}.brand-divider{margin:0 9px}.brand-product{font-size:11px}.header-actions{gap:8px}.header-actions>.button{font-size:10px;min-height:31px;padding:5px 8px}.connection-status{font-size:0;gap:0}.status-dot{width:7px;height:7px}main{padding:0 14px}.page-heading{margin:25px 0 21px;gap:15px}.page-heading h1{font-size:25px;max-width:315px}.subtitle{font-size:12px;max-width:325px}.eyebrow{font-size:9px}.capture-actions{width:100%;gap:7px}.capture-actions .button{font-size:11px;min-height:33px}.overview{grid-template-columns:repeat(2,minmax(0,1fr));margin-bottom:18px}.metric{padding:13px 16px}.metric:nth-child(2){border-right:0}.metric:nth-child(-n+2){border-bottom:1px solid #2e382e}.metric-value{font-size:23px}.metric-label{font-size:10px}.metric-foot{font-size:10px}.filters{padding:10px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px}.search-box{grid-column:1/-1;border-bottom:1px solid #303f2d}.filters>label:not(.search-box){max-width:none;min-width:0}.filters select{font-size:11px;min-height:35px;padding:7px}.workbench{display:flex;flex-direction:column;min-height:500px}.turn-column{border-right:0;border-bottom:1px solid #3b5033}.column-heading{padding:12px 14px}.turn-list{display:flex;gap:7px;padding:9px;min-height:0;max-height:none;overflow:auto}.turn-card{min-width:245px;max-width:245px;margin:0;border-color:#2c3b29;padding:12px}.turn-title{-webkit-line-clamp:2;min-height:38px}.turn-bottom{margin-top:8px}.list-empty{text-align:left;padding:14px 9px}.inspector{max-height:none;min-height:480px;overflow:visible}.inspection-heading{padding:18px 15px}.inspection-input{font-size:16px}.turn-metrics{padding:14px 15px;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.small-metric-label{font-size:9px}.small-metric-value{font-size:12px}.subset-note{padding:8px 15px;font-size:9px}.tabs{padding:0 15px;gap:22px}.inspection-body{padding:15px}.call-heading{padding:11px}.call-name{font-size:11px}.call-money{font-size:10px}.call-usage{padding:9px 11px;gap:11px;font-size:9px}.call-usage strong{font-size:10px}.fold>summary{padding:11px;font-size:10px}.fold-content{padding:0 10px 10px}.code-block{font-size:10px;padding:10px;max-height:340px}.event-button{gap:8px;padding:10px}.event-type{font-size:10px}.event-sequence{font-size:9px;min-width:20px}.empty-state{min-height:430px;padding:48px 20px}.empty-state h2{font-size:18px}.empty-state p{font-size:11px}.connection-dialog{padding:19px}.dialog-heading h2{font-size:20px}.input-action{flex-wrap:wrap}.input-action input{width:100%;min-width:140px}.input-action .button{font-size:11px}.snippet-heading h3{font-size:11px}.privacy-note{font-size:10px}footer{flex-direction:column;gap:7px;font-size:9px;margin-bottom:20px}}
|
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { summarizeTurns } from './turns.js';
|
|
3
|
+
import { ObserveError, ObserveHub } from './observe.js';
|
|
4
|
+
const KNOWN = new Set(['id', 'timestamp', 'sequence', 'openSequence', 'runtimeInstanceId', 'sessionId', 'projectId', 'appName', 'turnId', 'operationId', 'callId', 'type', 'data', 'visibility', 'agentId', 'v']);
|
|
5
|
+
class HttpError extends Error {
|
|
6
|
+
status;
|
|
7
|
+
constructor(status, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.status = status;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function deny(status, message) { throw new HttpError(status, message); }
|
|
13
|
+
const isObject = (value) => Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
|
14
|
+
const json = (value, status = 200, headers = {}) => new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json', ...headers } });
|
|
15
|
+
const equal = (left, right) => { const a = Buffer.from(left), b = Buffer.from(right); return a.length === b.length && timingSafeEqual(a, b); };
|
|
16
|
+
const field = (value, name, max = 200) => {
|
|
17
|
+
if (typeof value !== 'string' || !value.trim() || value.length > max || /[\u0000-\u001f]/.test(value))
|
|
18
|
+
deny(400, `Invalid ${name}.`);
|
|
19
|
+
return value.trim();
|
|
20
|
+
};
|
|
21
|
+
const keyOf = (event) => `${event.runtimeInstanceId}\u0000${event.id}`;
|
|
22
|
+
const SECRET_FIELD = /^(?:(?:openrouter|openai|anthropic|croche|debugger)[-_]?)?(?:authorization|proxy[-_]?authorization|cookie|set[-_]?cookie|password|passwd|secret|(?:api|provider)[-_]?key|(?:runtime|access|refresh|auth|id|invite|invitation|pairing|operator|session|client)[-_]?token|token)$/i;
|
|
23
|
+
// Configuration identities are digests, not secrets, and the 64-hex rule would make every
|
|
24
|
+
// configuration look the same (Atlas, #178). Each is kept only at its defined path and only in its
|
|
25
|
+
// defined form; anything else there is redacted as before.
|
|
26
|
+
const DIGEST = /^sha256:[0-9a-f]{64}$/;
|
|
27
|
+
const IDENTITIES = {
|
|
28
|
+
'input.received': [[['config', 'app', 'id'], DIGEST], [['config', 'croche', 'renderer'], /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\+sha256:[0-9a-f]{64}$/]],
|
|
29
|
+
'model.request': [[['tools'], DIGEST]],
|
|
30
|
+
};
|
|
31
|
+
/** A passive, bounded event collector. It has no Runtime or Cloud dependency. */
|
|
32
|
+
export class DebugCollector {
|
|
33
|
+
token;
|
|
34
|
+
port;
|
|
35
|
+
limits;
|
|
36
|
+
now;
|
|
37
|
+
entries = [];
|
|
38
|
+
seen = new Set();
|
|
39
|
+
sessions = new Map();
|
|
40
|
+
listeners = new Set();
|
|
41
|
+
bytes = 0;
|
|
42
|
+
paused = false;
|
|
43
|
+
revision = 0;
|
|
44
|
+
received = 0;
|
|
45
|
+
evicted = 0;
|
|
46
|
+
pausedDropped = 0;
|
|
47
|
+
clientDropped = 0;
|
|
48
|
+
dropSources = new Map();
|
|
49
|
+
/** Every stored event takes the next cursor, assigned before any visibility filtering. */
|
|
50
|
+
nextCursor = 1;
|
|
51
|
+
storedBytes = 0;
|
|
52
|
+
observe;
|
|
53
|
+
pid;
|
|
54
|
+
onShutdown;
|
|
55
|
+
constructor(options = {}) {
|
|
56
|
+
this.port = options.port ?? 8790;
|
|
57
|
+
this.pid = options.pid;
|
|
58
|
+
this.onShutdown = options.onShutdown;
|
|
59
|
+
this.token = options.token ?? randomBytes(32).toString('hex');
|
|
60
|
+
this.now = options.now ?? Date.now;
|
|
61
|
+
this.limits = { events: options.maxEvents ?? 2000, bytes: options.maxBytes ?? 8 * 1024 * 1024, bodyBytes: options.maxBodyBytes ?? 1024 * 1024, eventBytes: options.maxEventBytes ?? 128 * 1024 };
|
|
62
|
+
if (!/^[A-Za-z0-9._~-]{16,4096}$/.test(this.token))
|
|
63
|
+
throw new Error('Debugger pairing token must contain 16–4096 URL-safe characters.');
|
|
64
|
+
if (!Number.isInteger(this.port) || this.port < 1 || this.port > 65535)
|
|
65
|
+
throw new Error('Debugger port must be between 1 and 65535.');
|
|
66
|
+
if (Object.values(this.limits).some(value => !Number.isSafeInteger(value) || value < 1))
|
|
67
|
+
throw new Error('Debugger limits must be positive integers.');
|
|
68
|
+
const entries = this.entries, collector = this;
|
|
69
|
+
this.observe = new ObserveHub({
|
|
70
|
+
now: this.now,
|
|
71
|
+
low: () => entries[0]?.cursor ?? this.nextCursor,
|
|
72
|
+
high: () => this.nextCursor - 1,
|
|
73
|
+
at: cursor => entries.length ? entries[cursor - entries[0].cursor] : undefined,
|
|
74
|
+
storedBytes: () => this.storedBytes,
|
|
75
|
+
entries: () => entries,
|
|
76
|
+
capture: () => ({ paused: collector.paused, received: collector.received, retained: entries.length, evicted: collector.evicted, paused_dropped: collector.pausedDropped, source_dropped: collector.clientDropped }),
|
|
77
|
+
}, options.studioOrigins, `http://127.0.0.1:${this.port}`);
|
|
78
|
+
}
|
|
79
|
+
get connectionUrl() { return `http://127.0.0.1:${this.port}/#token=${encodeURIComponent(this.token)}`; }
|
|
80
|
+
trustedHost(request) {
|
|
81
|
+
const url = new URL(request.url);
|
|
82
|
+
const allowed = new Set([`127.0.0.1:${this.port}`, `localhost:${this.port}`]);
|
|
83
|
+
const host = request.headers.get('Host') ?? url.host;
|
|
84
|
+
if (url.protocol !== 'http:' || !allowed.has(url.host) || !allowed.has(host.toLowerCase()) || host.toLowerCase() !== url.host.toLowerCase())
|
|
85
|
+
deny(403, 'Only the local debugger host is allowed.');
|
|
86
|
+
}
|
|
87
|
+
sameOrigin(request) {
|
|
88
|
+
const origin = request.headers.get('Origin');
|
|
89
|
+
if (origin && origin !== new URL(request.url).origin)
|
|
90
|
+
deny(403, 'Debugger controls require the same origin.');
|
|
91
|
+
const site = request.headers.get('Sec-Fetch-Site');
|
|
92
|
+
if (site && !['same-origin', 'none'].includes(site))
|
|
93
|
+
deny(403, 'Cross-site debugger access is not allowed.');
|
|
94
|
+
}
|
|
95
|
+
bearer(request) {
|
|
96
|
+
const header = request.headers.get('Authorization');
|
|
97
|
+
return Boolean(header?.startsWith('Bearer ') && equal(header.slice(7), this.token));
|
|
98
|
+
}
|
|
99
|
+
localAppOrigin(request) {
|
|
100
|
+
const origin = request.headers.get('Origin');
|
|
101
|
+
if (!origin)
|
|
102
|
+
return null;
|
|
103
|
+
try {
|
|
104
|
+
const url = new URL(origin);
|
|
105
|
+
if (url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) && url.origin === origin)
|
|
106
|
+
return origin;
|
|
107
|
+
}
|
|
108
|
+
catch { }
|
|
109
|
+
deny(403, 'A bearer-authenticated debugger probe must come from a localhost app.');
|
|
110
|
+
}
|
|
111
|
+
localSession(request) {
|
|
112
|
+
this.sameOrigin(request);
|
|
113
|
+
const token = request.headers.get('Cookie')?.split(';').map(value => value.trim()).find(value => value.startsWith('croche_debugger='))?.slice(16);
|
|
114
|
+
if (!token || (this.sessions.get(token) ?? 0) <= this.now())
|
|
115
|
+
deny(401, 'Open the pairing link printed by the debugger, or enter its pairing token.');
|
|
116
|
+
}
|
|
117
|
+
async body(request, limit = this.limits.bodyBytes) {
|
|
118
|
+
if (request.headers.get('Content-Type')?.split(';')[0].trim().toLowerCase() !== 'application/json')
|
|
119
|
+
deny(415, 'Use application/json.');
|
|
120
|
+
if (Number(request.headers.get('Content-Length') ?? 0) > limit)
|
|
121
|
+
deny(413, 'Request exceeds the debugger body limit.');
|
|
122
|
+
const reader = request.body?.getReader();
|
|
123
|
+
if (!reader)
|
|
124
|
+
deny(400, 'A JSON body is required.');
|
|
125
|
+
const chunks = [];
|
|
126
|
+
let size = 0;
|
|
127
|
+
while (true) {
|
|
128
|
+
const next = await reader.read();
|
|
129
|
+
if (next.done)
|
|
130
|
+
break;
|
|
131
|
+
size += next.value.byteLength;
|
|
132
|
+
if (size > limit) {
|
|
133
|
+
await reader.cancel();
|
|
134
|
+
deny(413, 'Request exceeds the debugger body limit.');
|
|
135
|
+
}
|
|
136
|
+
chunks.push(next.value);
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
140
|
+
if (!isObject(parsed))
|
|
141
|
+
deny(400, 'Expected a JSON object.');
|
|
142
|
+
return parsed;
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error instanceof HttpError)
|
|
146
|
+
throw error;
|
|
147
|
+
return deny(400, 'Invalid JSON.');
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
redact(value, depth = 0) {
|
|
151
|
+
if (typeof value === 'string')
|
|
152
|
+
return value.split(this.token).join('[REDACTED]').replace(/\bBearer\s+[A-Za-z0-9._~+\/=\-]{12,}/gi, 'Bearer [REDACTED]').replace(/\bsk-(?:or-v1-)?[A-Za-z0-9_-]{16,}\b/g, '[REDACTED]').replace(/\b[a-f0-9]{64}\b/gi, '[REDACTED]');
|
|
153
|
+
if (!value || typeof value !== 'object')
|
|
154
|
+
return value;
|
|
155
|
+
if (depth >= 20)
|
|
156
|
+
return '[Depth limited]';
|
|
157
|
+
if (Array.isArray(value))
|
|
158
|
+
return value.map(entry => this.redact(entry, depth + 1));
|
|
159
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, SECRET_FIELD.test(key) ? '[REDACTED]' : this.redact(entry, depth + 1)]));
|
|
160
|
+
}
|
|
161
|
+
validate(raw) {
|
|
162
|
+
if (!isObject(raw))
|
|
163
|
+
deny(400, 'Event must be an object.');
|
|
164
|
+
const value = raw;
|
|
165
|
+
if (Buffer.byteLength(JSON.stringify(value)) > this.limits.eventBytes)
|
|
166
|
+
deny(413, 'Event exceeds the debugger event limit.');
|
|
167
|
+
const event = {
|
|
168
|
+
id: field(value.id, 'event id'), timestamp: field(value.timestamp, 'timestamp', 64),
|
|
169
|
+
sequence: value.sequence, runtimeInstanceId: field(value.runtimeInstanceId, 'runtimeInstanceId'),
|
|
170
|
+
sessionId: field(value.sessionId, 'sessionId'), projectId: field(value.projectId, 'projectId'),
|
|
171
|
+
type: field(value.type, 'event type', 80), data: {},
|
|
172
|
+
};
|
|
173
|
+
if (!Number.isSafeInteger(event.sequence) || event.sequence < 0 || !Number.isFinite(Date.parse(event.timestamp)))
|
|
174
|
+
deny(400, 'Event timestamp or sequence is invalid.');
|
|
175
|
+
// Absent from Runtimes before 0.9; present, it orders events across reopens of one Runtime.
|
|
176
|
+
if (value.openSequence !== undefined) {
|
|
177
|
+
if (!Number.isSafeInteger(value.openSequence) || value.openSequence < 0)
|
|
178
|
+
deny(400, 'Event openSequence is invalid.');
|
|
179
|
+
event.openSequence = value.openSequence;
|
|
180
|
+
}
|
|
181
|
+
if (!isObject(value.data))
|
|
182
|
+
deny(400, 'Event data must be an object.');
|
|
183
|
+
for (const key of ['appName', 'turnId', 'operationId', 'callId'])
|
|
184
|
+
if (value[key] !== undefined)
|
|
185
|
+
event[key] = field(value[key], key, 200);
|
|
186
|
+
event.data = this.redact(value.data);
|
|
187
|
+
// Kept as sent, never inferred: an odd value is dropped, which reads as not public.
|
|
188
|
+
if (typeof value.visibility === 'string' && value.visibility.length <= 32)
|
|
189
|
+
event.visibility = value.visibility;
|
|
190
|
+
if (value.agentId === null)
|
|
191
|
+
event.agentId = null;
|
|
192
|
+
else if (value.agentId !== undefined)
|
|
193
|
+
event.agentId = field(value.agentId, 'agentId', 200);
|
|
194
|
+
if (Number.isSafeInteger(value.v) && value.v >= 1)
|
|
195
|
+
event.v = value.v;
|
|
196
|
+
// Own data properties, never assignment: a `__proto__` key is data, not the event's prototype (Atlas, #297).
|
|
197
|
+
for (const [key, entry] of Object.entries(value))
|
|
198
|
+
if (!KNOWN.has(key))
|
|
199
|
+
Object.defineProperty(event, key, { value: SECRET_FIELD.test(key) ? '[REDACTED]' : this.redact(entry), enumerable: true, writable: true, configurable: true });
|
|
200
|
+
for (const [path, form] of IDENTITIES[event.type] ?? []) {
|
|
201
|
+
const kept = path.reduce((at, key) => isObject(at) ? at[key] : undefined, value.data);
|
|
202
|
+
if (typeof kept !== 'string' || !form.test(kept) || kept.includes(this.token))
|
|
203
|
+
continue;
|
|
204
|
+
const parent = path.slice(0, -1).reduce((at, key) => isObject(at) ? at[key] : undefined, event.data);
|
|
205
|
+
if (isObject(parent))
|
|
206
|
+
parent[path[path.length - 1]] = kept;
|
|
207
|
+
}
|
|
208
|
+
return event;
|
|
209
|
+
}
|
|
210
|
+
publish() { this.revision++; for (const listener of this.listeners)
|
|
211
|
+
listener(); this.observe.wake(); }
|
|
212
|
+
/** Ends every Studio observation stream with `collector_stopping`. */
|
|
213
|
+
stop() { this.observe.end('collector_stopping'); }
|
|
214
|
+
snapshot() {
|
|
215
|
+
const runtimes = new Map();
|
|
216
|
+
for (const { event } of this.entries) {
|
|
217
|
+
const prior = runtimes.get(event.runtimeInstanceId);
|
|
218
|
+
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
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
revision: this.revision, paused: this.paused, limits: this.limits,
|
|
222
|
+
stats: { received: this.received, retained: this.entries.length, bytes: this.bytes, evicted: this.evicted, pausedDropped: this.pausedDropped, clientDropped: this.clientDropped },
|
|
223
|
+
runtimes: [...runtimes.values()].reverse(), events: this.entries.map(entry => entry.event), turns: summarizeTurns(this.entries.map(entry => entry.event)),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
async ingest(request) {
|
|
227
|
+
if (!this.bearer(request))
|
|
228
|
+
deny(401, 'A valid debugger pairing token is required.');
|
|
229
|
+
const body = await this.body(request);
|
|
230
|
+
if (!Array.isArray(body.events) || body.events.length > 100)
|
|
231
|
+
deny(400, 'Send at most 100 events per batch.');
|
|
232
|
+
const ack = { accepted: [], duplicate: [], rejected: [] };
|
|
233
|
+
for (const raw of body.events) {
|
|
234
|
+
let id = isObject(raw) && typeof raw.id === 'string' ? raw.id.slice(0, 200) : 'unknown';
|
|
235
|
+
try {
|
|
236
|
+
const event = this.validate(raw);
|
|
237
|
+
id = event.id;
|
|
238
|
+
const key = keyOf(event);
|
|
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);
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
ack.rejected.push({ id, reason: error instanceof HttpError ? error.message : 'Invalid event.' });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (isObject(body.dropped) && Number.isSafeInteger(body.dropped.events) && Number(body.dropped.events) > 0) {
|
|
269
|
+
const source = typeof body.dropped.sourceId === 'string' ? body.dropped.sourceId.slice(0, 200) : 'legacy';
|
|
270
|
+
const cumulative = Math.min(Number(body.dropped.events), Number.MAX_SAFE_INTEGER);
|
|
271
|
+
const previous = this.dropSources.get(source) ?? 0;
|
|
272
|
+
this.clientDropped += Math.max(0, cumulative - previous);
|
|
273
|
+
this.dropSources.set(source, Math.max(previous, cumulative));
|
|
274
|
+
if (this.dropSources.size > 256)
|
|
275
|
+
this.dropSources.delete(this.dropSources.keys().next().value);
|
|
276
|
+
}
|
|
277
|
+
this.publish();
|
|
278
|
+
return json(ack);
|
|
279
|
+
}
|
|
280
|
+
stream(request) {
|
|
281
|
+
if (this.listeners.size >= 16)
|
|
282
|
+
deny(429, 'Too many debugger streams.');
|
|
283
|
+
const encoder = new TextEncoder();
|
|
284
|
+
let cleanup = () => { };
|
|
285
|
+
const stream = new ReadableStream({
|
|
286
|
+
start: controller => {
|
|
287
|
+
// A slow browser gets the current revision when it catches up; notifications
|
|
288
|
+
// never create an unbounded second event buffer beside the capture store.
|
|
289
|
+
const send = () => { try {
|
|
290
|
+
if ((controller.desiredSize ?? 0) > 0)
|
|
291
|
+
controller.enqueue(encoder.encode(`event: change\ndata: ${this.revision}\n\n`));
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
cleanup();
|
|
295
|
+
} };
|
|
296
|
+
const timer = setInterval(send, 20000);
|
|
297
|
+
timer.unref();
|
|
298
|
+
cleanup = () => { clearInterval(timer); this.listeners.delete(send); request.signal.removeEventListener('abort', cleanup); try {
|
|
299
|
+
controller.close();
|
|
300
|
+
}
|
|
301
|
+
catch { } };
|
|
302
|
+
this.listeners.add(send);
|
|
303
|
+
request.signal.addEventListener('abort', cleanup, { once: true });
|
|
304
|
+
send();
|
|
305
|
+
}, cancel: () => cleanup(),
|
|
306
|
+
});
|
|
307
|
+
return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' } });
|
|
308
|
+
}
|
|
309
|
+
async handle(request) {
|
|
310
|
+
let response;
|
|
311
|
+
try {
|
|
312
|
+
this.trustedHost(request);
|
|
313
|
+
const path = new URL(request.url).pathname;
|
|
314
|
+
if (path === '/api/debug/pair' || path === '/api/debug/events') {
|
|
315
|
+
// Studio observation: the origin is checked first on every request, preflight included.
|
|
316
|
+
this.observe.origin(request);
|
|
317
|
+
if (request.method === 'OPTIONS')
|
|
318
|
+
response = new Response(null, { status: 204 });
|
|
319
|
+
else if (path === '/api/debug/pair' && request.method === 'POST')
|
|
320
|
+
response = json(this.observe.pair((await this.body(request, 1024)).code));
|
|
321
|
+
else if (path === '/api/debug/events' && request.method === 'GET')
|
|
322
|
+
response = this.observe.open(request);
|
|
323
|
+
else
|
|
324
|
+
throw new ObserveError(404, 'not_found', 'Endpoint not found.');
|
|
325
|
+
}
|
|
326
|
+
else if (path === '/api/debug/codes' && request.method === 'POST') {
|
|
327
|
+
// The CLI's fresh Studio link: the ingest pairing token, never from a page.
|
|
328
|
+
this.sameOrigin(request);
|
|
329
|
+
if (request.headers.has('Origin') || !this.bearer(request))
|
|
330
|
+
deny(401, 'A valid debugger pairing token is required.');
|
|
331
|
+
response = json(this.observe.issueCode());
|
|
332
|
+
}
|
|
333
|
+
else if (path === '/api/shutdown' && request.method === 'POST') {
|
|
334
|
+
// `croche debug stop`: the CLI's pairing token, never from a page.
|
|
335
|
+
this.sameOrigin(request);
|
|
336
|
+
if (request.headers.has('Origin') || !this.bearer(request))
|
|
337
|
+
deny(401, 'A valid debugger pairing token is required.');
|
|
338
|
+
const shutdown = this.onShutdown;
|
|
339
|
+
if (!shutdown)
|
|
340
|
+
deny(404, 'This debugger cannot be stopped over HTTP.');
|
|
341
|
+
setTimeout(() => shutdown(), 0);
|
|
342
|
+
response = json({ ok: true, stopping: true });
|
|
343
|
+
}
|
|
344
|
+
else if (path === '/api/events' && request.method === 'OPTIONS')
|
|
345
|
+
response = new Response(null, { status: 204 });
|
|
346
|
+
else if (path === '/api/events' && request.method === 'POST')
|
|
347
|
+
response = await this.ingest(request);
|
|
348
|
+
else if (['/api/state', '/api/probe'].includes(path) && request.method === 'OPTIONS') {
|
|
349
|
+
this.localAppOrigin(request);
|
|
350
|
+
response = new Response(null, { status: 204 });
|
|
351
|
+
}
|
|
352
|
+
else if (['/api/state', '/api/probe'].includes(path) && request.method === 'GET' && request.headers.has('Authorization')) {
|
|
353
|
+
this.localAppOrigin(request);
|
|
354
|
+
if (!this.bearer(request))
|
|
355
|
+
deny(401, 'A valid debugger pairing token is required.');
|
|
356
|
+
response = json(path === '/api/probe' ? { ok: true, paused: this.paused, limits: this.limits, ...(this.pid !== undefined ? { pid: this.pid } : {}) } : { ok: true, ...this.snapshot() });
|
|
357
|
+
}
|
|
358
|
+
else if (path === '/api/pair' && request.method === 'POST') {
|
|
359
|
+
this.sameOrigin(request);
|
|
360
|
+
if (!this.bearer(request))
|
|
361
|
+
deny(401, 'Pairing token is incorrect.');
|
|
362
|
+
for (const [token, expiry] of this.sessions)
|
|
363
|
+
if (expiry <= this.now())
|
|
364
|
+
this.sessions.delete(token);
|
|
365
|
+
if (this.sessions.size >= 32)
|
|
366
|
+
this.sessions.delete(this.sessions.keys().next().value);
|
|
367
|
+
const token = randomBytes(32).toString('hex');
|
|
368
|
+
this.sessions.set(token, this.now() + 6 * 3600000);
|
|
369
|
+
response = json({ ok: true }, 200, { 'Set-Cookie': `croche_debugger=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=21600` });
|
|
370
|
+
}
|
|
371
|
+
else {
|
|
372
|
+
this.localSession(request);
|
|
373
|
+
if (path === '/api/bootstrap' && request.method === 'GET')
|
|
374
|
+
response = json({ pairingToken: this.token, endpoint: `http://127.0.0.1:${this.port}/api/events`, ...this.snapshot() });
|
|
375
|
+
else if (path === '/api/state' && request.method === 'GET')
|
|
376
|
+
response = json(this.snapshot());
|
|
377
|
+
else if (path === '/api/stream' && request.method === 'GET')
|
|
378
|
+
response = this.stream(request);
|
|
379
|
+
else if (path === '/api/export' && request.method === 'GET')
|
|
380
|
+
response = json({ format: 'croche-debug-capture-v1', exportedAt: new Date(this.now()).toISOString(), ...this.snapshot() }, 200, { 'Content-Disposition': 'attachment; filename="croche-debug-capture.json"' });
|
|
381
|
+
else if (path === '/api/capture' && request.method === 'POST') {
|
|
382
|
+
const body = await this.body(request, 1024);
|
|
383
|
+
if (typeof body.paused !== 'boolean')
|
|
384
|
+
deny(400, 'paused must be boolean.');
|
|
385
|
+
this.paused = body.paused;
|
|
386
|
+
this.publish();
|
|
387
|
+
response = json(this.snapshot());
|
|
388
|
+
}
|
|
389
|
+
else if (path === '/api/clear' && request.method === 'POST') {
|
|
390
|
+
await this.body(request, 1024);
|
|
391
|
+
this.observe.end('cleared');
|
|
392
|
+
this.entries.length = 0;
|
|
393
|
+
this.seen.clear();
|
|
394
|
+
this.bytes = this.received = this.evicted = this.pausedDropped = this.clientDropped = 0;
|
|
395
|
+
this.publish();
|
|
396
|
+
response = json(this.snapshot());
|
|
397
|
+
}
|
|
398
|
+
else
|
|
399
|
+
response = json({ error: 'Endpoint not found.' }, 404);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
catch (error) {
|
|
403
|
+
if (new URL(request.url).pathname.startsWith('/api/debug/')) {
|
|
404
|
+
// The observation contract's error shape (§2a): a code the client can act on.
|
|
405
|
+
const known = error instanceof ObserveError ? error : error instanceof HttpError ? new ObserveError(error.status, error.status === 401 ? 'token_invalid' : error.status === 413 ? 'too_large' : 'bad_request', error.message) : new ObserveError(500, 'internal_error', 'The debugger could not process this request.');
|
|
406
|
+
response = json({ error: { code: known.code, message: known.message } }, known.status);
|
|
407
|
+
}
|
|
408
|
+
else
|
|
409
|
+
response = json({ error: error instanceof HttpError ? error.message : 'The debugger could not process this request.' }, error instanceof HttpError ? error.status : 500);
|
|
410
|
+
}
|
|
411
|
+
const headers = new Headers(response.headers);
|
|
412
|
+
headers.set('Cache-Control', 'no-store');
|
|
413
|
+
headers.set('X-Content-Type-Options', 'nosniff');
|
|
414
|
+
headers.set('Referrer-Policy', 'no-referrer');
|
|
415
|
+
if (new URL(request.url).pathname === '/api/events') {
|
|
416
|
+
headers.set('Access-Control-Allow-Origin', '*');
|
|
417
|
+
headers.set('Access-Control-Allow-Methods', 'POST, OPTIONS');
|
|
418
|
+
headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
419
|
+
headers.set('Access-Control-Max-Age', '600');
|
|
420
|
+
if (request.headers.get('Access-Control-Request-Private-Network') === 'true')
|
|
421
|
+
headers.set('Access-Control-Allow-Private-Network', 'true');
|
|
422
|
+
}
|
|
423
|
+
if (['/api/debug/pair', '/api/debug/events'].includes(new URL(request.url).pathname)) {
|
|
424
|
+
const origin = request.headers.get('Origin');
|
|
425
|
+
// Only a configured Studio origin is told it may read, or reach the private network.
|
|
426
|
+
if (origin && this.observe.origins.has(origin)) {
|
|
427
|
+
headers.set('Access-Control-Allow-Origin', origin);
|
|
428
|
+
headers.set('Vary', 'Origin');
|
|
429
|
+
if (request.method === 'OPTIONS') {
|
|
430
|
+
headers.set('Access-Control-Allow-Methods', 'GET, POST');
|
|
431
|
+
headers.set('Access-Control-Allow-Headers', 'Authorization, Content-Type');
|
|
432
|
+
headers.set('Access-Control-Max-Age', '600');
|
|
433
|
+
if (request.headers.get('Access-Control-Request-Private-Network') === 'true')
|
|
434
|
+
headers.set('Access-Control-Allow-Private-Network', 'true');
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (['/api/state', '/api/probe'].includes(new URL(request.url).pathname) && request.headers.get('Origin')) {
|
|
439
|
+
try {
|
|
440
|
+
const origin = this.localAppOrigin(request);
|
|
441
|
+
if (origin) {
|
|
442
|
+
headers.set('Access-Control-Allow-Origin', origin);
|
|
443
|
+
headers.set('Vary', 'Origin');
|
|
444
|
+
headers.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
|
|
445
|
+
headers.set('Access-Control-Allow-Headers', 'Authorization');
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
catch { }
|
|
449
|
+
}
|
|
450
|
+
return new Response(response.body, { status: response.status, headers });
|
|
451
|
+
}
|
|
452
|
+
/** Apply the same Host guard before serving non-sensitive static UI files. */
|
|
453
|
+
checkStaticRequest(request) { try {
|
|
454
|
+
this.trustedHost(request);
|
|
455
|
+
return true;
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
return false;
|
|
459
|
+
} }
|
|
460
|
+
}
|