@sanctuary-framework/mcp-server 0.5.14 → 0.5.15

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/dist/index.cjs CHANGED
@@ -11,12 +11,15 @@ var os = require('os');
11
11
  var module$1 = require('module');
12
12
  var hashWasm = require('hash-wasm');
13
13
  var hkdf = require('@noble/hashes/hkdf');
14
- var index_js = require('@modelcontextprotocol/sdk/server/index.js');
14
+ var index_js$1 = require('@modelcontextprotocol/sdk/server/index.js');
15
15
  var types_js = require('@modelcontextprotocol/sdk/types.js');
16
16
  var http = require('http');
17
17
  var https = require('https');
18
18
  var fs = require('fs');
19
19
  var child_process = require('child_process');
20
+ var index_js = require('@modelcontextprotocol/sdk/client/index.js');
21
+ var stdio_js = require('@modelcontextprotocol/sdk/client/stdio.js');
22
+ var sse_js = require('@modelcontextprotocol/sdk/client/sse.js');
20
23
 
21
24
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
22
25
  var __defProp = Object.defineProperty;
@@ -1182,7 +1185,7 @@ function checkType(field, value, schema) {
1182
1185
  }
1183
1186
  function createServer(tools, options) {
1184
1187
  const gate = options?.gate;
1185
- const server = new index_js.Server(
1188
+ const server = new index_js$1.Server(
1186
1189
  {
1187
1190
  name: "sanctuary-mcp-server",
1188
1191
  version: PKG_VERSION2
@@ -3819,8 +3822,10 @@ var DEFAULT_POLICY = {
3819
3822
  "decommission_certificate",
3820
3823
  "reputation_publish",
3821
3824
  // SEC-039: Explicit Tier 1 — sends data to external API
3822
- "sovereignty_profile_update"
3825
+ "sovereignty_profile_update",
3823
3826
  // Changes enforcement behavior — always requires approval
3827
+ "governor_reset"
3828
+ // Clears all runtime governance state — always requires approval
3824
3829
  ],
3825
3830
  tier2_anomaly: DEFAULT_TIER2,
3826
3831
  tier3_always_allow: [
@@ -3876,11 +3881,16 @@ var DEFAULT_POLICY = {
3876
3881
  "dashboard_open",
3877
3882
  // SEC-039: Explicit Tier 3 — only generates a URL
3878
3883
  "sovereignty_profile_get",
3879
- "sovereignty_profile_generate_prompt"
3884
+ "sovereignty_profile_generate_prompt",
3885
+ // Agent needs its own config to generate system prompt
3886
+ "governor_status"
3880
3887
  ],
3881
3888
  approval_channel: DEFAULT_CHANNEL
3882
3889
  };
3883
3890
  function extractOperationName(toolName) {
3891
+ if (toolName.startsWith("proxy/")) {
3892
+ return toolName;
3893
+ }
3884
3894
  return toolName.startsWith("sanctuary/") ? toolName.slice("sanctuary/".length) : toolName;
3885
3895
  }
3886
3896
  function parsePolicy(content) {
@@ -3986,6 +3996,7 @@ tier1_always_approve:
3986
3996
  - bootstrap_provide_guarantee
3987
3997
  - reputation_publish
3988
3998
  - sovereignty_profile_update
3999
+ - governor_reset
3989
4000
 
3990
4001
  # \u2500\u2500\u2500 Tier 2: Behavioral Anomaly Detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
3991
4002
  # Triggers approval when agent behavior deviates from its baseline.
@@ -4050,7 +4061,7 @@ tier3_always_allow:
4050
4061
  - bridge_attest
4051
4062
  - dashboard_open
4052
4063
  - sovereignty_profile_get
4053
- - sovereignty_profile_generate_prompt
4064
+ - governor_status
4054
4065
 
4055
4066
  # \u2500\u2500\u2500 Approval Channel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
4056
4067
  # How Sanctuary reaches you when approval is needed.
@@ -5362,6 +5373,17 @@ function generateDashboardHTML(options) {
5362
5373
  display: flex;
5363
5374
  flex-direction: column;
5364
5375
  gap: 8px;
5376
+ transition: border-color 0.2s;
5377
+ }
5378
+
5379
+ .profile-card.active {
5380
+ border-color: var(--green);
5381
+ }
5382
+
5383
+ .profile-card-header {
5384
+ display: flex;
5385
+ justify-content: space-between;
5386
+ align-items: center;
5365
5387
  }
5366
5388
 
5367
5389
  .profile-card-name {
@@ -5376,6 +5398,53 @@ function generateDashboardHTML(options) {
5376
5398
  line-height: 1.4;
5377
5399
  }
5378
5400
 
5401
+ /* Toggle switch */
5402
+ .toggle-switch {
5403
+ position: relative;
5404
+ width: 36px;
5405
+ height: 20px;
5406
+ flex-shrink: 0;
5407
+ }
5408
+
5409
+ .toggle-switch input {
5410
+ opacity: 0;
5411
+ width: 0;
5412
+ height: 0;
5413
+ }
5414
+
5415
+ .toggle-slider {
5416
+ position: absolute;
5417
+ cursor: pointer;
5418
+ top: 0;
5419
+ left: 0;
5420
+ right: 0;
5421
+ bottom: 0;
5422
+ background-color: var(--border);
5423
+ border-radius: 10px;
5424
+ transition: background-color 0.2s;
5425
+ }
5426
+
5427
+ .toggle-slider::before {
5428
+ content: "";
5429
+ position: absolute;
5430
+ height: 14px;
5431
+ width: 14px;
5432
+ left: 3px;
5433
+ bottom: 3px;
5434
+ background-color: var(--text-secondary);
5435
+ border-radius: 50%;
5436
+ transition: transform 0.2s, background-color 0.2s;
5437
+ }
5438
+
5439
+ .toggle-switch input:checked + .toggle-slider {
5440
+ background-color: rgba(63, 185, 80, 0.3);
5441
+ }
5442
+
5443
+ .toggle-switch input:checked + .toggle-slider::before {
5444
+ transform: translateX(16px);
5445
+ background-color: var(--green);
5446
+ }
5447
+
5379
5448
  .profile-badge {
5380
5449
  display: inline-flex;
5381
5450
  align-items: center;
@@ -5397,22 +5466,159 @@ function generateDashboardHTML(options) {
5397
5466
  color: var(--text-secondary);
5398
5467
  }
5399
5468
 
5469
+ .profile-card-actions {
5470
+ display: flex;
5471
+ gap: 6px;
5472
+ margin-top: 4px;
5473
+ }
5474
+
5475
+ .config-btn {
5476
+ padding: 3px 8px;
5477
+ border: 1px solid var(--border);
5478
+ border-radius: 4px;
5479
+ background-color: transparent;
5480
+ color: var(--text-secondary);
5481
+ font-size: 10px;
5482
+ cursor: pointer;
5483
+ transition: color 0.2s, border-color 0.2s;
5484
+ }
5485
+
5486
+ .config-btn:hover {
5487
+ color: var(--blue);
5488
+ border-color: var(--blue);
5489
+ }
5490
+
5491
+ /* Configuration panels */
5492
+ .config-panel {
5493
+ display: none;
5494
+ margin-top: 8px;
5495
+ padding: 10px;
5496
+ background-color: var(--surface);
5497
+ border: 1px solid var(--border);
5498
+ border-radius: 4px;
5499
+ font-size: 11px;
5500
+ }
5501
+
5502
+ .config-panel.open {
5503
+ display: block;
5504
+ }
5505
+
5506
+ .config-panel-title {
5507
+ font-size: 11px;
5508
+ font-weight: 600;
5509
+ color: var(--text-primary);
5510
+ margin-bottom: 8px;
5511
+ }
5512
+
5513
+ .config-row {
5514
+ display: flex;
5515
+ align-items: center;
5516
+ gap: 8px;
5517
+ margin-bottom: 6px;
5518
+ }
5519
+
5520
+ .config-label {
5521
+ font-size: 11px;
5522
+ color: var(--text-secondary);
5523
+ min-width: 80px;
5524
+ }
5525
+
5526
+ .config-select, .config-input {
5527
+ background-color: var(--bg);
5528
+ border: 1px solid var(--border);
5529
+ border-radius: 4px;
5530
+ color: var(--text-primary);
5531
+ font-size: 11px;
5532
+ padding: 4px 8px;
5533
+ }
5534
+
5535
+ .config-info {
5536
+ font-size: 11px;
5537
+ color: var(--text-secondary);
5538
+ line-height: 1.5;
5539
+ }
5540
+
5541
+ .sensitivity-slider {
5542
+ display: flex;
5543
+ gap: 4px;
5544
+ }
5545
+
5546
+ .sensitivity-option {
5547
+ padding: 3px 10px;
5548
+ border: 1px solid var(--border);
5549
+ border-radius: 4px;
5550
+ background-color: transparent;
5551
+ color: var(--text-secondary);
5552
+ font-size: 10px;
5553
+ cursor: pointer;
5554
+ transition: all 0.2s;
5555
+ }
5556
+
5557
+ .sensitivity-option.selected {
5558
+ background-color: rgba(88, 166, 255, 0.15);
5559
+ color: var(--blue);
5560
+ border-color: var(--blue);
5561
+ }
5562
+
5563
+ .sensitivity-option:hover:not(.selected) {
5564
+ border-color: var(--text-secondary);
5565
+ }
5566
+
5567
+ /* Prompt section */
5400
5568
  .prompt-section {
5401
- margin-top: 12px;
5569
+ margin-top: 16px;
5402
5570
  }
5403
5571
 
5404
- .prompt-textarea {
5405
- width: 100%;
5406
- min-height: 120px;
5572
+ .prompt-display {
5573
+ position: relative;
5407
5574
  background-color: var(--bg);
5408
5575
  border: 1px solid var(--border);
5409
5576
  border-radius: 6px;
5577
+ margin-top: 8px;
5578
+ display: none;
5579
+ }
5580
+
5581
+ .prompt-display.visible {
5582
+ display: block;
5583
+ }
5584
+
5585
+ .prompt-display-header {
5586
+ display: flex;
5587
+ justify-content: space-between;
5588
+ align-items: center;
5589
+ padding: 8px 12px;
5590
+ border-bottom: 1px solid var(--border);
5591
+ }
5592
+
5593
+ .prompt-token-count {
5594
+ font-size: 11px;
5595
+ color: var(--text-secondary);
5596
+ }
5597
+
5598
+ .prompt-copy-btn {
5599
+ padding: 4px 10px;
5600
+ border: 1px solid var(--border);
5601
+ border-radius: 4px;
5602
+ background-color: var(--surface);
5410
5603
  color: var(--text-primary);
5604
+ font-size: 11px;
5605
+ cursor: pointer;
5606
+ transition: border-color 0.2s;
5607
+ }
5608
+
5609
+ .prompt-copy-btn:hover {
5610
+ border-color: var(--blue);
5611
+ }
5612
+
5613
+ .prompt-content {
5614
+ max-height: 300px;
5615
+ overflow-y: auto;
5616
+ padding: 12px;
5411
5617
  font-family: 'JetBrains Mono', monospace;
5412
5618
  font-size: 12px;
5413
- padding: 12px;
5414
- resize: vertical;
5415
- margin-top: 8px;
5619
+ line-height: 1.6;
5620
+ white-space: pre-wrap;
5621
+ color: var(--text-primary);
5416
5622
  }
5417
5623
 
5418
5624
  .prompt-actions {
@@ -5799,37 +6005,173 @@ function generateDashboardHTML(options) {
5799
6005
  </div>
5800
6006
  <div class="profile-cards" id="profile-cards">
5801
6007
  <div class="profile-card" data-feature="audit_logging">
5802
- <div class="profile-card-name">Audit Logging</div>
6008
+ <div class="profile-card-header">
6009
+ <div class="profile-card-name">Audit Logging</div>
6010
+ <label class="toggle-switch">
6011
+ <input type="checkbox" id="toggle-audit_logging" data-feature="audit_logging">
6012
+ <span class="toggle-slider"></span>
6013
+ </label>
6014
+ </div>
5803
6015
  <div class="profile-badge disabled" id="badge-audit_logging">OFF</div>
5804
6016
  <div class="profile-card-desc">Encrypted audit trail of all tool calls</div>
6017
+ <div class="profile-card-actions">
6018
+ <button class="config-btn" data-config="audit_logging">Configure</button>
6019
+ </div>
6020
+ <div class="config-panel" id="config-audit_logging">
6021
+ <div class="config-info">Audit logging is always-on when enabled. All tool calls, gate decisions, and profile changes are recorded to an encrypted audit trail. No additional configuration needed.</div>
6022
+ </div>
5805
6023
  </div>
5806
6024
  <div class="profile-card" data-feature="injection_detection">
5807
- <div class="profile-card-name">Injection Detection</div>
6025
+ <div class="profile-card-header">
6026
+ <div class="profile-card-name">Injection Detection</div>
6027
+ <label class="toggle-switch">
6028
+ <input type="checkbox" id="toggle-injection_detection" data-feature="injection_detection">
6029
+ <span class="toggle-slider"></span>
6030
+ </label>
6031
+ </div>
5808
6032
  <div class="profile-badge disabled" id="badge-injection_detection">OFF</div>
5809
6033
  <div class="profile-card-desc">Scans tool arguments for prompt injection</div>
6034
+ <div class="profile-card-actions">
6035
+ <button class="config-btn" data-config="injection_detection">Configure</button>
6036
+ </div>
6037
+ <div class="config-panel" id="config-injection_detection">
6038
+ <div class="config-panel-title">Sensitivity</div>
6039
+ <div class="sensitivity-slider">
6040
+ <button class="sensitivity-option" data-sensitivity="low">Low</button>
6041
+ <button class="sensitivity-option selected" data-sensitivity="medium">Medium</button>
6042
+ <button class="sensitivity-option" data-sensitivity="high">High</button>
6043
+ </div>
6044
+ </div>
5810
6045
  </div>
5811
6046
  <div class="profile-card" data-feature="context_gating">
5812
- <div class="profile-card-name">Context Gating</div>
6047
+ <div class="profile-card-header">
6048
+ <div class="profile-card-name">Context Gating</div>
6049
+ <label class="toggle-switch">
6050
+ <input type="checkbox" id="toggle-context_gating" data-feature="context_gating">
6051
+ <span class="toggle-slider"></span>
6052
+ </label>
6053
+ </div>
5813
6054
  <div class="profile-badge disabled" id="badge-context_gating">OFF</div>
5814
6055
  <div class="profile-card-desc">Controls context flow to remote providers</div>
6056
+ <div class="profile-card-actions">
6057
+ <button class="config-btn" data-config="context_gating">Configure</button>
6058
+ </div>
6059
+ <div class="config-panel" id="config-context_gating">
6060
+ <div class="config-panel-title">Active Policy</div>
6061
+ <div class="config-row">
6062
+ <span class="config-label">Policy ID:</span>
6063
+ <select class="config-select" id="config-context-policy">
6064
+ <option value="">None selected</option>
6065
+ </select>
6066
+ </div>
6067
+ <div class="config-info" style="margin-top: 6px;">Use MCP tool <code style="color: var(--blue);">sanctuary/context_gate_set_policy</code> or <code style="color: var(--blue);">sanctuary/context_gate_apply_template</code> to create policies.</div>
6068
+ </div>
5815
6069
  </div>
5816
6070
  <div class="profile-card" data-feature="approval_gate">
5817
- <div class="profile-card-name">Approval Gates</div>
6071
+ <div class="profile-card-header">
6072
+ <div class="profile-card-name">Approval Gates</div>
6073
+ <label class="toggle-switch">
6074
+ <input type="checkbox" id="toggle-approval_gate" data-feature="approval_gate">
6075
+ <span class="toggle-slider"></span>
6076
+ </label>
6077
+ </div>
5818
6078
  <div class="profile-badge disabled" id="badge-approval_gate">OFF</div>
5819
6079
  <div class="profile-card-desc">Human approval for high-risk operations</div>
6080
+ <div class="profile-card-actions">
6081
+ <button class="config-btn" data-config="approval_gate">Configure</button>
6082
+ </div>
6083
+ <div class="config-panel" id="config-approval_gate">
6084
+ <div class="config-panel-title">Tier Assignments</div>
6085
+ <div class="config-info">
6086
+ <strong style="color: var(--red);">Tier 1 (always approve):</strong> export, import, key rotation, deletion<br>
6087
+ <strong style="color: var(--amber);">Tier 2 (approve on anomaly):</strong> new namespaces, unfamiliar counterparties, frequency spikes<br>
6088
+ <strong style="color: var(--green);">Tier 3 (auto-allow):</strong> standard operations, queries, reads
6089
+ </div>
6090
+ </div>
5820
6091
  </div>
5821
6092
  <div class="profile-card" data-feature="zk_proofs">
5822
- <div class="profile-card-name">ZK Proofs</div>
6093
+ <div class="profile-card-header">
6094
+ <div class="profile-card-name">ZK Proofs</div>
6095
+ <label class="toggle-switch">
6096
+ <input type="checkbox" id="toggle-zk_proofs" data-feature="zk_proofs">
6097
+ <span class="toggle-slider"></span>
6098
+ </label>
6099
+ </div>
5823
6100
  <div class="profile-badge disabled" id="badge-zk_proofs">OFF</div>
5824
6101
  <div class="profile-card-desc">Prove claims without revealing data</div>
6102
+ <div class="profile-card-actions">
6103
+ <button class="config-btn" data-config="zk_proofs">Configure</button>
6104
+ </div>
6105
+ <div class="config-panel" id="config-zk_proofs">
6106
+ <div class="config-info">Zero-knowledge proofs use Pedersen commitments on Ristretto255 and Schnorr proofs. No additional configuration needed. Available tools: <code style="color: var(--blue);">sanctuary/zk_commit</code>, <code style="color: var(--blue);">sanctuary/zk_prove</code>, <code style="color: var(--blue);">sanctuary/zk_range_prove</code>.</div>
6107
+ </div>
5825
6108
  </div>
5826
6109
  </div>
5827
6110
  <div class="prompt-section">
5828
6111
  <div class="prompt-actions">
5829
6112
  <button class="prompt-btn primary" id="generate-prompt-btn">Generate System Prompt</button>
5830
- <button class="prompt-btn" id="copy-prompt-btn" style="display:none;">Copy</button>
5831
6113
  </div>
5832
- <textarea class="prompt-textarea" id="system-prompt-output" readonly style="display:none;" placeholder="Click 'Generate System Prompt' to create an agent instruction snippet..."></textarea>
6114
+ <div class="prompt-display" id="prompt-display">
6115
+ <div class="prompt-display-header">
6116
+ <span class="prompt-token-count" id="prompt-token-count"></span>
6117
+ <button class="prompt-copy-btn" id="copy-prompt-btn">Copy to Clipboard</button>
6118
+ </div>
6119
+ <div class="prompt-content" id="system-prompt-output"></div>
6120
+ </div>
6121
+ </div>
6122
+ </div>
6123
+
6124
+ <!-- Upstream Servers Panel -->
6125
+ <div class="profile-panel" id="proxy-servers-panel">
6126
+ <div class="panel-header">
6127
+ <div class="panel-title">Upstream Servers</div>
6128
+ <button class="panel-action" id="add-proxy-server-btn">+ Add Server</button>
6129
+ </div>
6130
+ <div id="proxy-servers-list">
6131
+ <div class="empty-state">No upstream servers configured</div>
6132
+ </div>
6133
+
6134
+ <!-- Add Server Form (hidden by default) -->
6135
+ <div id="add-server-form" style="display: none; padding: 16px; border-top: 1px solid var(--border);">
6136
+ <div style="margin-bottom: 12px;">
6137
+ <label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Server Name</label>
6138
+ <input type="text" id="new-server-name" placeholder="e.g., filesystem" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
6139
+ </div>
6140
+ <div style="margin-bottom: 12px;">
6141
+ <label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Transport Type</label>
6142
+ <select id="new-server-transport" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
6143
+ <option value="stdio">stdio</option>
6144
+ <option value="sse">SSE</option>
6145
+ </select>
6146
+ </div>
6147
+ <div id="stdio-fields">
6148
+ <div style="margin-bottom: 12px;">
6149
+ <label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Command</label>
6150
+ <input type="text" id="new-server-command" placeholder="e.g., npx -y @modelcontextprotocol/server-filesystem" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
6151
+ </div>
6152
+ <div style="margin-bottom: 12px;">
6153
+ <label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Arguments (comma-separated)</label>
6154
+ <input type="text" id="new-server-args" placeholder="e.g., /Users/me/allowed-dir" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
6155
+ </div>
6156
+ </div>
6157
+ <div id="sse-fields" style="display: none;">
6158
+ <div style="margin-bottom: 12px;">
6159
+ <label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Server URL</label>
6160
+ <input type="text" id="new-server-url" placeholder="e.g., http://localhost:3001/sse" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
6161
+ </div>
6162
+ </div>
6163
+ <div style="margin-bottom: 12px;">
6164
+ <label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Default Tier</label>
6165
+ <select id="new-server-tier" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
6166
+ <option value="1">Tier 1 (Always approve)</option>
6167
+ <option value="2" selected>Tier 2 (Anomaly detection)</option>
6168
+ <option value="3">Tier 3 (Always allow)</option>
6169
+ </select>
6170
+ </div>
6171
+ <div style="display: flex; gap: 8px;">
6172
+ <button id="save-server-btn" style="flex: 1; padding: 8px; background: var(--green); color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px;">Save</button>
6173
+ <button id="cancel-server-btn" style="flex: 1; padding: 8px; background: var(--surface); color: var(--text-secondary); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px;">Cancel</button>
6174
+ </div>
5833
6175
  </div>
5834
6176
  </div>
5835
6177
 
@@ -6320,8 +6662,34 @@ function generateDashboardHTML(options) {
6320
6662
  removePendingRequest(data.requestId);
6321
6663
  });
6322
6664
 
6323
- eventSource.addEventListener('sovereignty-profile-update', () => {
6324
- updateSovereigntyProfile();
6665
+ eventSource.addEventListener('sovereignty-profile-update', (e) => {
6666
+ try {
6667
+ const data = JSON.parse(e.data);
6668
+ if (data.profile) {
6669
+ applyProfileToUI(data.profile);
6670
+ }
6671
+ if (data.system_prompt) {
6672
+ apiState.systemPrompt = data.system_prompt;
6673
+ updatePromptDisplay(data.system_prompt);
6674
+ }
6675
+ } catch (err) {
6676
+ // Fallback to full refresh
6677
+ updateSovereigntyProfile();
6678
+ }
6679
+ });
6680
+
6681
+ eventSource.addEventListener('proxy-server-status', (e) => {
6682
+ try {
6683
+ const data = JSON.parse(e.data);
6684
+ updateProxyServerStatus(data.server, data.state, data.tool_count, data.error);
6685
+ } catch (err) {
6686
+ // Fallback to full refresh
6687
+ loadProxyServers();
6688
+ }
6689
+ });
6690
+
6691
+ eventSource.addEventListener('proxy-servers-update', () => {
6692
+ loadProxyServers();
6325
6693
  });
6326
6694
 
6327
6695
  eventSource.onerror = () => {
@@ -6339,7 +6707,7 @@ function generateDashboardHTML(options) {
6339
6707
 
6340
6708
  const feed = document.getElementById('activity-feed');
6341
6709
  const html = \`
6342
- <div class="activity-item \${item.type}">
6710
+ <div class="activity-item \${esc(item.type)}">
6343
6711
  <div class="activity-type">\${esc(item.title)}</div>
6344
6712
  <div class="activity-content">\${esc(item.content)}</div>
6345
6713
  <div class="activity-time">\${formatTime(item.timestamp)}</div>
@@ -6481,26 +6849,16 @@ function generateDashboardHTML(options) {
6481
6849
  });
6482
6850
 
6483
6851
  // Sovereignty Profile
6852
+ let profileToggleLock = false;
6853
+
6484
6854
  async function updateSovereigntyProfile() {
6485
6855
  try {
6486
6856
  const data = await fetchAPI('/api/sovereignty-profile');
6487
6857
  if (data && data.profile) {
6488
- const features = data.profile.features;
6489
- for (const [key, value] of Object.entries(features)) {
6490
- const badge = document.getElementById('badge-' + key);
6491
- if (badge) {
6492
- const enabled = value && value.enabled;
6493
- badge.textContent = enabled ? 'ON' : 'OFF';
6494
- badge.className = 'profile-badge ' + (enabled ? 'enabled' : 'disabled');
6495
- }
6496
- }
6497
- const updatedEl = document.getElementById('profile-updated-at');
6498
- if (updatedEl && data.profile.updated_at) {
6499
- updatedEl.textContent = 'Updated: ' + new Date(data.profile.updated_at).toLocaleString();
6500
- }
6501
- // Cache the prompt
6858
+ applyProfileToUI(data.profile);
6502
6859
  if (data.system_prompt) {
6503
6860
  apiState.systemPrompt = data.system_prompt;
6861
+ updatePromptDisplay(data.system_prompt);
6504
6862
  }
6505
6863
  }
6506
6864
  } catch (e) {
@@ -6508,94 +6866,518 @@ function generateDashboardHTML(options) {
6508
6866
  }
6509
6867
  }
6510
6868
 
6511
- document.getElementById('generate-prompt-btn').addEventListener('click', async () => {
6512
- const data = await fetchAPI('/api/sovereignty-profile');
6513
- if (data && data.system_prompt) {
6514
- const textarea = document.getElementById('system-prompt-output');
6515
- const copyBtn = document.getElementById('copy-prompt-btn');
6516
- textarea.value = data.system_prompt;
6517
- textarea.style.display = 'block';
6518
- copyBtn.style.display = 'inline-flex';
6519
- }
6520
- });
6869
+ function applyProfileToUI(profile) {
6870
+ const features = profile.features;
6871
+ for (const [key, value] of Object.entries(features)) {
6872
+ const enabled = value && value.enabled;
6521
6873
 
6522
- document.getElementById('copy-prompt-btn').addEventListener('click', async () => {
6523
- const textarea = document.getElementById('system-prompt-output');
6524
- try {
6525
- await navigator.clipboard.writeText(textarea.value);
6526
- const btn = document.getElementById('copy-prompt-btn');
6527
- const original = btn.textContent;
6528
- btn.textContent = 'Copied!';
6529
- setTimeout(() => { btn.textContent = original; }, 2000);
6530
- } catch (err) {
6531
- console.error('Copy failed:', err);
6532
- }
6533
- });
6874
+ // Update badge
6875
+ const badge = document.getElementById('badge-' + key);
6876
+ if (badge) {
6877
+ badge.textContent = enabled ? 'ON' : 'OFF';
6878
+ badge.className = 'profile-badge ' + (enabled ? 'enabled' : 'disabled');
6879
+ }
6534
6880
 
6535
- // Initialize
6536
- async function initialize() {
6537
- if (!AUTH_TOKEN) {
6538
- redirectToLogin();
6539
- return;
6881
+ // Update toggle (without triggering change event)
6882
+ const toggle = document.getElementById('toggle-' + key);
6883
+ if (toggle && toggle.checked !== enabled) {
6884
+ profileToggleLock = true;
6885
+ toggle.checked = enabled;
6886
+ profileToggleLock = false;
6887
+ }
6888
+
6889
+ // Update card active state
6890
+ const card = document.querySelector('[data-feature="' + key + '"]');
6891
+ if (card) {
6892
+ card.classList.toggle('active', enabled);
6893
+ }
6894
+
6895
+ // Feature-specific config UI updates
6896
+ if (key === 'injection_detection' && value.sensitivity) {
6897
+ document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(btn) {
6898
+ btn.classList.toggle('selected', btn.getAttribute('data-sensitivity') === value.sensitivity);
6899
+ });
6900
+ }
6901
+
6902
+ if (key === 'context_gating' && value.policy_id) {
6903
+ const sel = document.getElementById('config-context-policy');
6904
+ if (sel) {
6905
+ // Add the policy as an option if not present
6906
+ let found = false;
6907
+ for (let i = 0; i < sel.options.length; i++) {
6908
+ if (sel.options[i].value === value.policy_id) { found = true; break; }
6909
+ }
6910
+ if (!found) {
6911
+ const opt = document.createElement('option');
6912
+ opt.value = value.policy_id;
6913
+ opt.textContent = value.policy_id;
6914
+ sel.appendChild(opt);
6915
+ }
6916
+ sel.value = value.policy_id;
6917
+ }
6918
+ }
6540
6919
  }
6541
6920
 
6542
- // Initial data fetch
6543
- await Promise.all([
6544
- updateSovereignty(),
6545
- updateIdentity(),
6546
- updateHandshakes(),
6547
- updateSHR(),
6548
- updateStatus(),
6549
- updateSovereigntyProfile(),
6550
- ]);
6921
+ const updatedEl = document.getElementById('profile-updated-at');
6922
+ if (updatedEl && profile.updated_at) {
6923
+ updatedEl.textContent = 'Updated: ' + new Date(profile.updated_at).toLocaleString();
6924
+ }
6925
+ }
6551
6926
 
6552
- // Setup SSE for real-time updates
6553
- setupSSE();
6927
+ function updatePromptDisplay(promptText) {
6928
+ const display = document.getElementById('prompt-display');
6929
+ const content = document.getElementById('system-prompt-output');
6930
+ const tokenCount = document.getElementById('prompt-token-count');
6931
+ if (!display || !content) return;
6554
6932
 
6555
- // Refresh status periodically
6556
- setInterval(updateStatus, 30000);
6933
+ if (promptText) {
6934
+ content.textContent = promptText;
6935
+ // Rough token estimate: word count * 1.3
6936
+ const words = promptText.split(/\\s+/).filter(function(w) { return w.length > 0; }).length;
6937
+ const tokens = Math.round(words * 1.3);
6938
+ tokenCount.textContent = '~' + tokens + ' tokens';
6939
+ display.classList.add('visible');
6940
+ }
6557
6941
  }
6558
6942
 
6559
- // Start
6560
- initialize();
6561
- </script>
6562
- </body>
6563
- </html>`;
6564
- }
6943
+ // Toggle handlers
6944
+ async function handleToggle(feature, enabled) {
6945
+ if (profileToggleLock) return;
6946
+ const payload = {};
6947
+ payload[feature] = { enabled: enabled };
6565
6948
 
6566
- // src/system-prompt-generator.ts
6567
- var FEATURE_INFO = {
6568
- audit_logging: {
6569
- name: "Audit Logging",
6570
- activeDescription: "All your tool calls are logged to an encrypted audit trail. No action needed \u2014 this is automatic.",
6571
- disabledDescription: "audit logging (sanctuary/monitor_audit_log)"
6949
+ try {
6950
+ const response = await fetch(API_BASE + '/api/sovereignty-profile', {
6951
+ method: 'POST',
6952
+ headers: {
6953
+ 'Authorization': 'Bearer ' + AUTH_TOKEN,
6954
+ 'Content-Type': 'application/json',
6955
+ },
6956
+ body: JSON.stringify(payload),
6957
+ });
6958
+
6959
+ if (response.status === 401) {
6960
+ redirectToLogin();
6961
+ return;
6962
+ }
6963
+
6964
+ if (response.ok) {
6965
+ const data = await response.json();
6966
+ if (data.profile) {
6967
+ applyProfileToUI(data.profile);
6968
+ }
6969
+ if (data.system_prompt) {
6970
+ apiState.systemPrompt = data.system_prompt;
6971
+ updatePromptDisplay(data.system_prompt);
6972
+ }
6973
+ } else {
6974
+ // Revert toggle on failure
6975
+ const toggle = document.getElementById('toggle-' + feature);
6976
+ if (toggle) {
6977
+ profileToggleLock = true;
6978
+ toggle.checked = !enabled;
6979
+ profileToggleLock = false;
6980
+ }
6981
+ }
6982
+ } catch (err) {
6983
+ console.error('Toggle update failed:', err);
6984
+ // Revert toggle
6985
+ const toggle = document.getElementById('toggle-' + feature);
6986
+ if (toggle) {
6987
+ profileToggleLock = true;
6988
+ toggle.checked = !enabled;
6989
+ profileToggleLock = false;
6990
+ }
6991
+ }
6992
+ }
6993
+
6994
+ // Wire up toggle switches
6995
+ document.querySelectorAll('.toggle-switch input').forEach(function(toggle) {
6996
+ toggle.addEventListener('change', function() {
6997
+ const feature = this.getAttribute('data-feature');
6998
+ handleToggle(feature, this.checked);
6999
+ });
7000
+ });
7001
+
7002
+ // Wire up configure buttons
7003
+ document.querySelectorAll('.config-btn').forEach(function(btn) {
7004
+ btn.addEventListener('click', function() {
7005
+ const feature = this.getAttribute('data-config');
7006
+ const panel = document.getElementById('config-' + feature);
7007
+ if (panel) {
7008
+ panel.classList.toggle('open');
7009
+ this.textContent = panel.classList.contains('open') ? 'Close' : 'Configure';
7010
+ }
7011
+ });
7012
+ });
7013
+
7014
+ // Injection sensitivity handler
7015
+ document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(btn) {
7016
+ btn.addEventListener('click', async function() {
7017
+ const sensitivity = this.getAttribute('data-sensitivity');
7018
+ const response = await fetch(API_BASE + '/api/sovereignty-profile', {
7019
+ method: 'POST',
7020
+ headers: {
7021
+ 'Authorization': 'Bearer ' + AUTH_TOKEN,
7022
+ 'Content-Type': 'application/json',
7023
+ },
7024
+ body: JSON.stringify({ injection_detection: { sensitivity: sensitivity } }),
7025
+ });
7026
+ if (response.ok) {
7027
+ document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(b) {
7028
+ b.classList.toggle('selected', b.getAttribute('data-sensitivity') === sensitivity);
7029
+ });
7030
+ const data = await response.json();
7031
+ if (data.profile) applyProfileToUI(data.profile);
7032
+ if (data.system_prompt) {
7033
+ apiState.systemPrompt = data.system_prompt;
7034
+ updatePromptDisplay(data.system_prompt);
7035
+ }
7036
+ }
7037
+ });
7038
+ });
7039
+
7040
+ // Context gating policy selector handler
7041
+ document.getElementById('config-context-policy').addEventListener('change', async function() {
7042
+ const policyId = this.value;
7043
+ const response = await fetch(API_BASE + '/api/sovereignty-profile', {
7044
+ method: 'POST',
7045
+ headers: {
7046
+ 'Authorization': 'Bearer ' + AUTH_TOKEN,
7047
+ 'Content-Type': 'application/json',
7048
+ },
7049
+ body: JSON.stringify({ context_gating: { policy_id: policyId } }),
7050
+ });
7051
+ if (response.ok) {
7052
+ const data = await response.json();
7053
+ if (data.profile) applyProfileToUI(data.profile);
7054
+ if (data.system_prompt) {
7055
+ apiState.systemPrompt = data.system_prompt;
7056
+ updatePromptDisplay(data.system_prompt);
7057
+ }
7058
+ }
7059
+ });
7060
+
7061
+ // Generate prompt button
7062
+ document.getElementById('generate-prompt-btn').addEventListener('click', async () => {
7063
+ const data = await fetchAPI('/api/sovereignty-profile');
7064
+ if (data && data.system_prompt) {
7065
+ apiState.systemPrompt = data.system_prompt;
7066
+ updatePromptDisplay(data.system_prompt);
7067
+ }
7068
+ });
7069
+
7070
+ // Copy prompt button
7071
+ document.getElementById('copy-prompt-btn').addEventListener('click', async () => {
7072
+ const content = document.getElementById('system-prompt-output');
7073
+ if (!content || !content.textContent) return;
7074
+ try {
7075
+ await navigator.clipboard.writeText(content.textContent);
7076
+ const btn = document.getElementById('copy-prompt-btn');
7077
+ const original = btn.textContent;
7078
+ btn.textContent = 'Copied!';
7079
+ setTimeout(() => { btn.textContent = original; }, 2000);
7080
+ } catch (err) {
7081
+ console.error('Copy failed:', err);
7082
+ }
7083
+ });
7084
+
7085
+ // \u2500\u2500 Proxy Server Management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
7086
+
7087
+ let proxyServers = [];
7088
+
7089
+ async function loadProxyServers() {
7090
+ try {
7091
+ const resp = await fetch(API_BASE + '/api/proxy/servers', {
7092
+ headers: { 'Authorization': 'Bearer ' + AUTH_TOKEN },
7093
+ });
7094
+ if (!resp.ok) return;
7095
+ const data = await resp.json();
7096
+ proxyServers = data.servers || [];
7097
+ renderProxyServers();
7098
+ } catch (err) {
7099
+ // Proxy endpoint may not be available
7100
+ }
7101
+ }
7102
+
7103
+ function renderProxyServers() {
7104
+ const container = document.getElementById('proxy-servers-list');
7105
+ if (!container) return;
7106
+
7107
+ if (proxyServers.length === 0) {
7108
+ container.innerHTML = '<div class="empty-state">No upstream servers configured</div>';
7109
+ return;
7110
+ }
7111
+
7112
+ container.innerHTML = proxyServers.map(server => {
7113
+ const stateColor = server.state === 'connected' ? 'var(--green)' :
7114
+ server.state === 'connecting' ? 'var(--amber)' : 'var(--red)';
7115
+ const stateLabel = server.state || 'disconnected';
7116
+ const tierLabel = 'Tier ' + server.default_tier;
7117
+
7118
+ return \`
7119
+ <div class="proxy-server-card" data-server="\${esc(server.name)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border);">
7120
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;">
7121
+ <div style="display: flex; align-items: center; gap: 8px;">
7122
+ <span style="color: \${stateColor}; font-size: 10px;">\\u25CF</span>
7123
+ <span style="font-weight: 600; font-size: 14px;">\${esc(server.name)}</span>
7124
+ <span style="font-size: 11px; color: var(--text-secondary); background: var(--bg); padding: 2px 6px; border-radius: 3px;">\${esc(server.transport_type)}</span>
7125
+ </div>
7126
+ <div style="display: flex; align-items: center; gap: 8px;">
7127
+ <span style="font-size: 11px; color: var(--text-secondary);">\${server.tool_count} tools</span>
7128
+ <span style="font-size: 11px; color: var(--blue); background: rgba(88,166,255,0.1); padding: 2px 6px; border-radius: 3px;">\${tierLabel}</span>
7129
+ <button class="proxy-remove-btn" data-server="\${esc(server.name)}" style="background: none; border: none; color: var(--red); cursor: pointer; font-size: 14px; padding: 2px 6px;" title="Remove server">\\u00D7</button>
7130
+ </div>
7131
+ </div>
7132
+ <div style="font-size: 11px; color: var(--text-secondary);">
7133
+ Status: <span style="color: \${stateColor}">\${esc(stateLabel)}</span>
7134
+ \${server.error ? '<span style="color: var(--red);"> \u2014 ' + esc(server.error) + '</span>' : ''}
7135
+ </div>
7136
+ <div class="proxy-tools-expand" style="margin-top: 8px; display: none;">
7137
+ <div style="font-size: 11px; color: var(--text-secondary); margin-bottom: 4px;">Discovered Tools:</div>
7138
+ <div class="proxy-tools-list" style="font-size: 11px; font-family: monospace; color: var(--text-primary); max-height: 150px; overflow-y: auto;"></div>
7139
+ </div>
7140
+ </div>
7141
+ \`;
7142
+ }).join('');
7143
+
7144
+ // Attach remove handlers
7145
+ container.querySelectorAll('.proxy-remove-btn').forEach(btn => {
7146
+ btn.addEventListener('click', (e) => {
7147
+ const serverName = e.target.dataset.server;
7148
+ removeProxyServer(serverName);
7149
+ });
7150
+ });
7151
+
7152
+ // Attach expand/collapse on card click
7153
+ container.querySelectorAll('.proxy-server-card').forEach(card => {
7154
+ card.style.cursor = 'pointer';
7155
+ card.addEventListener('click', (e) => {
7156
+ if (e.target.classList.contains('proxy-remove-btn')) return;
7157
+ const expand = card.querySelector('.proxy-tools-expand');
7158
+ if (expand) {
7159
+ expand.style.display = expand.style.display === 'none' ? 'block' : 'none';
7160
+ }
7161
+ });
7162
+ });
7163
+ }
7164
+
7165
+ function updateProxyServerStatus(serverName, state, toolCount, error) {
7166
+ const server = proxyServers.find(s => s.name === serverName);
7167
+ if (server) {
7168
+ server.state = state;
7169
+ server.tool_count = toolCount;
7170
+ server.error = error;
7171
+ renderProxyServers();
7172
+ }
7173
+ }
7174
+
7175
+ async function addProxyServer(serverConfig) {
7176
+ const current = [...proxyServers];
7177
+ // Check for duplicate
7178
+ if (current.find(s => s.name === serverConfig.name)) {
7179
+ alert('A server with that name already exists');
7180
+ return;
7181
+ }
7182
+ current.push(serverConfig);
7183
+
7184
+ try {
7185
+ const resp = await fetch(API_BASE + '/api/proxy/servers', {
7186
+ method: 'POST',
7187
+ headers: {
7188
+ 'Authorization': 'Bearer ' + AUTH_TOKEN,
7189
+ 'Content-Type': 'application/json',
7190
+ },
7191
+ body: JSON.stringify({ upstream_servers: current }),
7192
+ });
7193
+ if (!resp.ok) {
7194
+ const err = await resp.json();
7195
+ alert('Failed to add server: ' + (err.error || 'Unknown error'));
7196
+ return;
7197
+ }
7198
+ await loadProxyServers();
7199
+ } catch (err) {
7200
+ alert('Failed to add server: ' + err.message);
7201
+ }
7202
+ }
7203
+
7204
+ async function removeProxyServer(serverName) {
7205
+ if (!confirm('Remove upstream server "' + serverName + '"?')) return;
7206
+
7207
+ const updated = proxyServers.filter(s => s.name !== serverName);
7208
+
7209
+ try {
7210
+ const resp = await fetch(API_BASE + '/api/proxy/servers', {
7211
+ method: 'POST',
7212
+ headers: {
7213
+ 'Authorization': 'Bearer ' + AUTH_TOKEN,
7214
+ 'Content-Type': 'application/json',
7215
+ },
7216
+ body: JSON.stringify({ upstream_servers: updated }),
7217
+ });
7218
+ if (!resp.ok) {
7219
+ const err = await resp.json();
7220
+ alert('Failed to remove server: ' + (err.error || 'Unknown error'));
7221
+ return;
7222
+ }
7223
+ await loadProxyServers();
7224
+ } catch (err) {
7225
+ alert('Failed to remove server: ' + err.message);
7226
+ }
7227
+ }
7228
+
7229
+ // Add Server form handlers
7230
+ (function setupProxyForm() {
7231
+ const addBtn = document.getElementById('add-proxy-server-btn');
7232
+ const form = document.getElementById('add-server-form');
7233
+ const saveBtn = document.getElementById('save-server-btn');
7234
+ const cancelBtn = document.getElementById('cancel-server-btn');
7235
+ const transportSelect = document.getElementById('new-server-transport');
7236
+ const stdioFields = document.getElementById('stdio-fields');
7237
+ const sseFields = document.getElementById('sse-fields');
7238
+
7239
+ if (!addBtn || !form) return;
7240
+
7241
+ addBtn.addEventListener('click', () => {
7242
+ form.style.display = form.style.display === 'none' ? 'block' : 'none';
7243
+ });
7244
+
7245
+ cancelBtn.addEventListener('click', () => {
7246
+ form.style.display = 'none';
7247
+ });
7248
+
7249
+ transportSelect.addEventListener('change', () => {
7250
+ if (transportSelect.value === 'stdio') {
7251
+ stdioFields.style.display = 'block';
7252
+ sseFields.style.display = 'none';
7253
+ } else {
7254
+ stdioFields.style.display = 'none';
7255
+ sseFields.style.display = 'block';
7256
+ }
7257
+ });
7258
+
7259
+ saveBtn.addEventListener('click', () => {
7260
+ const name = document.getElementById('new-server-name').value.trim();
7261
+ const type = transportSelect.value;
7262
+ const tier = parseInt(document.getElementById('new-server-tier').value, 10);
7263
+
7264
+ if (!name) { alert('Server name is required'); return; }
7265
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) { alert('Name must contain only letters, numbers, hyphens, and underscores'); return; }
7266
+
7267
+ const transport = { type };
7268
+ if (type === 'stdio') {
7269
+ const command = document.getElementById('new-server-command').value.trim();
7270
+ if (!command) { alert('Command is required for stdio transport'); return; }
7271
+ transport.command = command;
7272
+ const argsStr = document.getElementById('new-server-args').value.trim();
7273
+ if (argsStr) {
7274
+ transport.args = argsStr.split(',').map(s => s.trim()).filter(Boolean);
7275
+ }
7276
+ } else {
7277
+ const url = document.getElementById('new-server-url').value.trim();
7278
+ if (!url) { alert('URL is required for SSE transport'); return; }
7279
+ transport.url = url;
7280
+ }
7281
+
7282
+ addProxyServer({
7283
+ name,
7284
+ transport,
7285
+ enabled: true,
7286
+ default_tier: tier,
7287
+ });
7288
+
7289
+ // Reset form
7290
+ form.style.display = 'none';
7291
+ document.getElementById('new-server-name').value = '';
7292
+ document.getElementById('new-server-command').value = '';
7293
+ document.getElementById('new-server-args').value = '';
7294
+ document.getElementById('new-server-url').value = '';
7295
+ });
7296
+ })();
7297
+
7298
+ // Initialize
7299
+ async function initialize() {
7300
+ if (!AUTH_TOKEN) {
7301
+ redirectToLogin();
7302
+ return;
7303
+ }
7304
+
7305
+ // Initial data fetch
7306
+ await Promise.all([
7307
+ updateSovereignty(),
7308
+ updateIdentity(),
7309
+ updateHandshakes(),
7310
+ updateSHR(),
7311
+ updateStatus(),
7312
+ updateSovereigntyProfile(),
7313
+ loadProxyServers(),
7314
+ ]);
7315
+
7316
+ // Setup SSE for real-time updates
7317
+ setupSSE();
7318
+
7319
+ // Refresh status periodically
7320
+ setInterval(updateStatus, 30000);
7321
+ }
7322
+
7323
+ // Start
7324
+ initialize();
7325
+ </script>
7326
+ </body>
7327
+ </html>`;
7328
+ }
7329
+
7330
+ // src/system-prompt-generator.ts
7331
+ var FEATURE_INFO = {
7332
+ audit_logging: {
7333
+ name: "Audit Logging",
7334
+ activeDescription: "All your tool calls are logged to an encrypted audit trail. No action needed \u2014 this is automatic. You can query the log with sanctuary/monitor_audit_log if you need to review past activity.",
7335
+ toolNames: ["sanctuary/monitor_audit_log"],
7336
+ disabledDescription: "audit logging (sanctuary/monitor_audit_log)",
7337
+ usageExample: "Automatic \u2014 every tool call you make is recorded. No explicit action required."
6572
7338
  },
6573
7339
  injection_detection: {
6574
7340
  name: "Injection Detection",
6575
- activeDescription: "Your tool call arguments are scanned for prompt injection attempts. No action needed \u2014 this is automatic.",
6576
- disabledDescription: "injection detection"
7341
+ activeDescription: "Your tool call arguments are scanned for prompt injection attempts. This is automatic \u2014 no action needed. If injection is detected in your input, the call will be blocked and you will receive an error. Do not retry blocked calls with the same input.",
7342
+ disabledDescription: "injection detection",
7343
+ usageExample: "Automatic \u2014 if a tool call is blocked with an injection alert, do not retry with the same arguments."
6577
7344
  },
6578
7345
  context_gating: {
6579
7346
  name: "Context Gating",
6580
- activeDescription: "Before making outbound calls to remote providers, filter your context through sanctuary/context_gate_filter to ensure minimum-necessary disclosure.",
6581
- toolNames: ["sanctuary/context_gate_filter", "sanctuary/context_gate_set_policy"],
6582
- disabledDescription: "context gating (sanctuary/context_gate_filter)"
7347
+ activeDescription: "Before sending context to any external API (LLM inference, tool APIs, logging services), call sanctuary/context_gate_filter to strip sensitive fields. Use sanctuary/context_gate_set_policy to define filtering rules, or sanctuary/context_gate_apply_template for presets.",
7348
+ toolNames: [
7349
+ "sanctuary/context_gate_filter",
7350
+ "sanctuary/context_gate_set_policy",
7351
+ "sanctuary/context_gate_apply_template",
7352
+ "sanctuary/context_gate_recommend",
7353
+ "sanctuary/context_gate_list_policies"
7354
+ ],
7355
+ disabledDescription: "context gating (sanctuary/context_gate_filter)",
7356
+ usageExample: "Before calling an external API, run: sanctuary/context_gate_filter with your context object and policy_id to get a filtered version."
6583
7357
  },
6584
7358
  approval_gate: {
6585
7359
  name: "Approval Gates",
6586
- activeDescription: "High-risk operations require human approval before execution. Tier 1 operations always require approval; Tier 2 operations trigger approval on anomaly detection.",
6587
- disabledDescription: "approval gates"
7360
+ activeDescription: "High-risk operations require human approval before execution. Tier 1 operations (export, import, key rotation, deletion) always require approval. Tier 2 operations trigger approval when anomalous behavior is detected. When an operation is held for approval, you will receive an async response \u2014 wait for the human decision before proceeding.",
7361
+ disabledDescription: "approval gates",
7362
+ usageExample: "When you call a Tier 1 operation (e.g., state_export), expect an async hold. The human operator will approve or deny via the dashboard."
6588
7363
  },
6589
7364
  zk_proofs: {
6590
7365
  name: "Zero-Knowledge Proofs",
6591
- activeDescription: "You can prove claims about your data without revealing the underlying values. Use sanctuary/zk_commit to create commitments, sanctuary/zk_prove for proofs of knowledge, and sanctuary/zk_range_prove for range proofs.",
6592
- toolNames: ["sanctuary/zk_commit", "sanctuary/zk_prove", "sanctuary/zk_range_prove"],
6593
- disabledDescription: "zero-knowledge proofs (sanctuary/zk_commit, sanctuary/zk_prove)"
7366
+ activeDescription: "You can prove claims about your data without revealing the underlying values. Use sanctuary/zk_commit to create a Pedersen commitment, sanctuary/zk_prove (Schnorr proof) to prove you know a committed value, and sanctuary/zk_range_prove to prove a value falls within a range \u2014 all without disclosing the actual data. For simpler SHA-256 commitments, use sanctuary/proof_commitment.",
7367
+ toolNames: [
7368
+ "sanctuary/zk_commit",
7369
+ "sanctuary/zk_prove",
7370
+ "sanctuary/zk_range_prove",
7371
+ "sanctuary/proof_commitment"
7372
+ ],
7373
+ disabledDescription: "zero-knowledge proofs (sanctuary/zk_commit, sanctuary/zk_prove)",
7374
+ usageExample: "To prove a claim without revealing data: first sanctuary/zk_commit to commit, then sanctuary/zk_prove or sanctuary/zk_range_prove to generate a verifiable proof."
6594
7375
  }
6595
7376
  };
6596
7377
  function generateSystemPrompt(profile) {
6597
7378
  const activeFeatures = [];
6598
7379
  const inactiveFeatures = [];
7380
+ const activeKeys = [];
6599
7381
  const featureKeys = [
6600
7382
  "audit_logging",
6601
7383
  "injection_detection",
@@ -6607,6 +7389,7 @@ function generateSystemPrompt(profile) {
6607
7389
  const featureConfig = profile.features[key];
6608
7390
  const info = FEATURE_INFO[key];
6609
7391
  if (featureConfig.enabled) {
7392
+ activeKeys.push(key);
6610
7393
  let desc = `- ${info.name}: ${info.activeDescription}`;
6611
7394
  if (key === "injection_detection" && "sensitivity" in featureConfig && featureConfig.sensitivity) {
6612
7395
  desc += ` Sensitivity: ${featureConfig.sensitivity}.`;
@@ -6619,14 +7402,25 @@ function generateSystemPrompt(profile) {
6619
7402
  inactiveFeatures.push(info.disabledDescription);
6620
7403
  }
6621
7404
  }
6622
- const lines = [
6623
- "You are protected by Sanctuary sovereignty infrastructure. The following protections are active:",
6624
- ""
6625
- ];
7405
+ const lines = [];
7406
+ if (activeKeys.length > 0) {
7407
+ lines.push("QUICK START:");
7408
+ const quickStartItems = buildQuickStart(activeKeys);
7409
+ for (const item of quickStartItems) {
7410
+ lines.push(` ${item}`);
7411
+ }
7412
+ lines.push("");
7413
+ }
7414
+ lines.push(
7415
+ "You are protected by Sanctuary sovereignty infrastructure. The following protections are active:"
7416
+ );
7417
+ lines.push("");
6626
7418
  if (activeFeatures.length > 0) {
6627
7419
  lines.push(...activeFeatures);
6628
7420
  } else {
6629
- lines.push("- No features are currently enabled. Contact your operator to configure protections.");
7421
+ lines.push(
7422
+ "- No features are currently enabled. Contact your operator to configure protections."
7423
+ );
6630
7424
  }
6631
7425
  if (inactiveFeatures.length > 0) {
6632
7426
  lines.push("");
@@ -6636,6 +7430,35 @@ function generateSystemPrompt(profile) {
6636
7430
  }
6637
7431
  return lines.join("\n");
6638
7432
  }
7433
+ function buildQuickStart(activeKeys) {
7434
+ const items = [];
7435
+ if (activeKeys.includes("context_gating")) {
7436
+ items.push(
7437
+ "1. ALWAYS call sanctuary/context_gate_filter before sending context to external APIs."
7438
+ );
7439
+ }
7440
+ if (activeKeys.includes("zk_proofs")) {
7441
+ items.push(
7442
+ `${items.length + 1}. Use sanctuary/zk_commit to prove claims without revealing underlying data.`
7443
+ );
7444
+ }
7445
+ if (activeKeys.includes("approval_gate")) {
7446
+ items.push(
7447
+ `${items.length + 1}. High-risk operations will be held for human approval \u2014 expect async responses.`
7448
+ );
7449
+ }
7450
+ if (items.length === 0) {
7451
+ if (activeKeys.includes("audit_logging")) {
7452
+ items.push("1. All tool calls are automatically logged to an encrypted audit trail.");
7453
+ }
7454
+ if (activeKeys.includes("injection_detection")) {
7455
+ items.push(
7456
+ `${items.length + 1}. Tool arguments are scanned for injection \u2014 blocked calls should not be retried.`
7457
+ );
7458
+ }
7459
+ }
7460
+ return items;
7461
+ }
6639
7462
 
6640
7463
  // src/principal-policy/dashboard.ts
6641
7464
  var SESSION_TTL_REMOTE_MS = 5 * 60 * 1e3;
@@ -6658,6 +7481,7 @@ var DashboardApprovalChannel = class {
6658
7481
  shrOpts = null;
6659
7482
  _sanctuaryConfig = null;
6660
7483
  profileStore = null;
7484
+ clientManager = null;
6661
7485
  dashboardHTML;
6662
7486
  loginHTML;
6663
7487
  authToken;
@@ -6679,8 +7503,7 @@ var DashboardApprovalChannel = class {
6679
7503
  this.sessionTTLMs = isLocalhost ? SESSION_TTL_LOCAL_MS : SESSION_TTL_REMOTE_MS;
6680
7504
  this.dashboardHTML = generateDashboardHTML({
6681
7505
  timeoutSeconds: config.timeout_seconds,
6682
- serverVersion: SANCTUARY_VERSION,
6683
- authToken: this.authToken
7506
+ serverVersion: SANCTUARY_VERSION
6684
7507
  });
6685
7508
  this.loginHTML = generateLoginHTML({ serverVersion: SANCTUARY_VERSION });
6686
7509
  this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
@@ -6698,6 +7521,7 @@ var DashboardApprovalChannel = class {
6698
7521
  if (deps.shrOpts) this.shrOpts = deps.shrOpts;
6699
7522
  if (deps.sanctuaryConfig) this._sanctuaryConfig = deps.sanctuaryConfig;
6700
7523
  if (deps.profileStore) this.profileStore = deps.profileStore;
7524
+ if (deps.clientManager) this.clientManager = deps.clientManager;
6701
7525
  }
6702
7526
  /**
6703
7527
  * Mark this dashboard as running in standalone mode.
@@ -7049,6 +7873,10 @@ var DashboardApprovalChannel = class {
7049
7873
  this.handleSovereigntyProfileGet(res);
7050
7874
  } else if (method === "POST" && url.pathname === "/api/sovereignty-profile") {
7051
7875
  this.handleSovereigntyProfileUpdate(req, res);
7876
+ } else if (method === "GET" && url.pathname === "/api/proxy/servers") {
7877
+ this.handleProxyServers(res);
7878
+ } else if (method === "POST" && url.pathname === "/api/proxy/servers") {
7879
+ this.handleProxyServersUpdate(req, res);
7052
7880
  } else if (method === "POST" && url.pathname.startsWith("/api/approve/")) {
7053
7881
  if (!this.checkRateLimit(req, res, "decisions")) return;
7054
7882
  const id = url.pathname.slice("/api/approve/".length);
@@ -7395,6 +8223,85 @@ data: ${JSON.stringify(initData)}
7395
8223
  }
7396
8224
  });
7397
8225
  }
8226
+ // ── Proxy Server Handlers ───────────────────────────────────────────
8227
+ /**
8228
+ * GET /api/proxy/servers — list upstream proxy servers and their status.
8229
+ */
8230
+ handleProxyServers(res) {
8231
+ const profile = this.profileStore?.get();
8232
+ const upstreamServers = profile?.upstream_servers ?? [];
8233
+ const clientStatus = this.clientManager?.getStatus() ?? [];
8234
+ const servers = upstreamServers.map((server) => {
8235
+ const status = clientStatus.find((s) => s.name === server.name);
8236
+ return {
8237
+ name: server.name,
8238
+ transport_type: server.transport.type,
8239
+ enabled: server.enabled,
8240
+ default_tier: server.default_tier,
8241
+ state: status?.state ?? "disconnected",
8242
+ tool_count: status?.tool_count ?? 0,
8243
+ error: status?.error,
8244
+ tool_overrides: server.tool_overrides ?? {}
8245
+ };
8246
+ });
8247
+ res.writeHead(200, { "Content-Type": "application/json" });
8248
+ res.end(JSON.stringify({ servers }));
8249
+ }
8250
+ /**
8251
+ * POST /api/proxy/servers — update upstream server configuration.
8252
+ * This is a dashboard action (human-initiated), so it's allowed with audit logging
8253
+ * rather than requiring Tier 1 approval.
8254
+ */
8255
+ handleProxyServersUpdate(req, res) {
8256
+ if (!this.profileStore) {
8257
+ res.writeHead(500, { "Content-Type": "application/json" });
8258
+ res.end(JSON.stringify({ error: "Profile store not available" }));
8259
+ return;
8260
+ }
8261
+ let body = "";
8262
+ let destroyed = false;
8263
+ req.on("data", (chunk) => {
8264
+ body += chunk.toString();
8265
+ if (body.length > 16384) {
8266
+ destroyed = true;
8267
+ res.writeHead(413, { "Content-Type": "application/json" });
8268
+ res.end(JSON.stringify({ error: "Request body too large" }));
8269
+ req.destroy();
8270
+ }
8271
+ });
8272
+ req.on("end", async () => {
8273
+ if (destroyed) return;
8274
+ try {
8275
+ const { upstream_servers } = JSON.parse(body);
8276
+ const updated = await this.profileStore.update({ upstream_servers });
8277
+ if (this.auditLog) {
8278
+ this.auditLog.append("l2", "proxy_servers_update_dashboard", "dashboard", {
8279
+ server_count: upstream_servers.length,
8280
+ servers: upstream_servers.map((s) => ({
8281
+ name: s.name,
8282
+ type: s.transport.type,
8283
+ enabled: s.enabled,
8284
+ tier: s.default_tier
8285
+ }))
8286
+ });
8287
+ }
8288
+ if (this.clientManager && updated.upstream_servers) {
8289
+ this.clientManager.configure(updated.upstream_servers).catch(() => {
8290
+ });
8291
+ }
8292
+ this.broadcastSSE("proxy-servers-update", {
8293
+ servers: updated.upstream_servers ?? [],
8294
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
8295
+ });
8296
+ res.writeHead(200, { "Content-Type": "application/json" });
8297
+ res.end(JSON.stringify({ upstream_servers: updated.upstream_servers ?? [] }));
8298
+ } catch (err) {
8299
+ const message = err instanceof Error ? err.message : "Invalid request";
8300
+ res.writeHead(400, { "Content-Type": "application/json" });
8301
+ res.end(JSON.stringify({ error: message }));
8302
+ }
8303
+ });
8304
+ }
7398
8305
  // ── SSE Broadcasting ────────────────────────────────────────────────
7399
8306
  broadcastSSE(event, data) {
7400
8307
  const message = `event: ${event}
@@ -7751,6 +8658,70 @@ var TOOL_INVOCATION_PATTERNS = [
7751
8658
  ];
7752
8659
  var URL_PATTERN = /https?:\/\/[^\s"'<>]+/i;
7753
8660
  var EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
8661
+ var INVISIBLE_CHARS = [
8662
+ "\u200B",
8663
+ // Zero-width space
8664
+ "\u200C",
8665
+ // Zero-width non-joiner
8666
+ "\u200D",
8667
+ // Zero-width joiner
8668
+ "\uFEFF",
8669
+ // Zero-width no-break space (BOM)
8670
+ "\xAD",
8671
+ // Soft hyphen
8672
+ "\u200E",
8673
+ // Left-to-right mark
8674
+ "\u200F",
8675
+ // Right-to-left mark
8676
+ "\u2060",
8677
+ // Word joiner
8678
+ "\u2061",
8679
+ // Function application
8680
+ "\u2062",
8681
+ // Invisible times
8682
+ "\u2063",
8683
+ // Invisible separator
8684
+ "\u2064",
8685
+ // Invisible plus
8686
+ "\u180E",
8687
+ // Mongolian vowel separator
8688
+ "\u034F",
8689
+ // Combining grapheme joiner
8690
+ "\u061C",
8691
+ // Arabic letter mark
8692
+ "\u115F",
8693
+ // Hangul choseong filler
8694
+ "\u1160",
8695
+ // Hangul jungseong filler
8696
+ "\u17B4",
8697
+ // Khmer vowel inherent AQ
8698
+ "\u17B5",
8699
+ // Khmer vowel inherent AA
8700
+ "\u3164",
8701
+ // Hangul filler
8702
+ "\uFFA0",
8703
+ // Halfwidth hangul filler
8704
+ "\u202A",
8705
+ // Left-to-Right Embedding (LRE)
8706
+ "\u202B",
8707
+ // Right-to-Left Embedding (RLE)
8708
+ "\u202C",
8709
+ // Pop Directional Formatting (PDF)
8710
+ "\u202D",
8711
+ // Left-to-Right Override (LRO)
8712
+ "\u202E",
8713
+ // Right-to-Left Override (RLO)
8714
+ "\u2066",
8715
+ // Left-to-Right Isolate (LRI)
8716
+ "\u2067",
8717
+ // Right-to-Left Isolate (RLI)
8718
+ "\u2068",
8719
+ // First Strong Isolate (FSI)
8720
+ "\u2069"
8721
+ // Pop Directional Isolate (PDI)
8722
+ ];
8723
+ var VARIATION_SELECTOR_RANGE_START = 65024;
8724
+ var VARIATION_SELECTOR_RANGE_END = 65039;
7754
8725
  var ZERO_WIDTH_CHARS = [
7755
8726
  "\u200B",
7756
8727
  // Zero-width space
@@ -7761,6 +8732,66 @@ var ZERO_WIDTH_CHARS = [
7761
8732
  "\uFEFF"
7762
8733
  // Zero-width no-break space
7763
8734
  ];
8735
+ var BASE64_STANDARD_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
8736
+ var BASE64URL_PATTERN = /^[A-Za-z0-9_-]+={0,2}$/;
8737
+ var BASE64_BLOCK_PATTERN = /[A-Za-z0-9+/]{20,}={0,2}/g;
8738
+ var HEX_ENCODED_PATTERN = /(?:0x)?[0-9a-fA-F]{20,}/g;
8739
+ var HTML_ENTITY_PATTERN = /&#(?:x[0-9a-fA-F]{2,4}|[0-9]{2,5});/g;
8740
+ var URL_ENCODED_PATTERN = /(?:%[0-9a-fA-F]{2}){4,}/g;
8741
+ var SECRET_PATTERNS = [
8742
+ { pattern: /sk-[a-zA-Z0-9]{20,}/, name: "openai_api_key" },
8743
+ { pattern: /sk-ant-[a-zA-Z0-9_-]{20,}/, name: "anthropic_api_key" },
8744
+ { pattern: /ghp_[a-zA-Z0-9]{36,}/, name: "github_pat" },
8745
+ { pattern: /gho_[a-zA-Z0-9]{36,}/, name: "github_oauth" },
8746
+ { pattern: /ghs_[a-zA-Z0-9]{36,}/, name: "github_app" },
8747
+ { pattern: /github_pat_[a-zA-Z0-9_]{22,}/, name: "github_fine_grained_pat" },
8748
+ { pattern: /AKIA[0-9A-Z]{16}/, name: "aws_access_key" },
8749
+ { pattern: /xoxb-[0-9]{10,}-[a-zA-Z0-9-]+/, name: "slack_bot_token" },
8750
+ { pattern: /xoxp-[0-9]{10,}-[a-zA-Z0-9-]+/, name: "slack_user_token" },
8751
+ { pattern: /xapp-[0-9]-[A-Z0-9]+-[0-9]+-[a-z0-9]+/, name: "slack_app_token" },
8752
+ { pattern: /(?:Bearer|bearer)\s+[a-zA-Z0-9._~+/=-]{20,}/, name: "bearer_token" },
8753
+ { pattern: /glpat-[a-zA-Z0-9_-]{20,}/, name: "gitlab_pat" },
8754
+ { pattern: /npm_[a-zA-Z0-9]{36,}/, name: "npm_token" },
8755
+ { pattern: /pypi-[a-zA-Z0-9_-]{20,}/, name: "pypi_token" },
8756
+ { pattern: /AIza[a-zA-Z0-9_-]{35}/, name: "google_api_key" },
8757
+ { pattern: /SG\.[a-zA-Z0-9_-]{22}\.[a-zA-Z0-9_-]{43}/, name: "sendgrid_api_key" },
8758
+ { pattern: /sq0[a-z]{3}-[a-zA-Z0-9_-]{22,}/, name: "square_api_key" },
8759
+ { pattern: /sk_live_[a-zA-Z0-9]{24,}/, name: "stripe_secret_key" },
8760
+ { pattern: /rk_live_[a-zA-Z0-9]{24,}/, name: "stripe_restricted_key" },
8761
+ { pattern: /(?:-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----)/, name: "private_key_pem" }
8762
+ ];
8763
+ var MARKDOWN_IMAGE_EXFIL_PATTERN = /!\[[^\]]*\]\(https?:\/\/[^)]*[?&](?:data|secret|key|token|password|auth|session|cookie|api_key|access_token)=/i;
8764
+ var INTERNAL_PATH_PATTERNS = [
8765
+ /\/home\/[a-zA-Z0-9_.-]+\//,
8766
+ /\/Users\/[a-zA-Z0-9_.-]+\//,
8767
+ /[A-Z]:\\(?:Users|Documents|Program Files)\\/,
8768
+ /~\/\.(?:ssh|aws|config|gnupg|sanctuary)\//,
8769
+ /\/etc\/(?:passwd|shadow|hosts|ssh)/,
8770
+ /\/var\/(?:log|run|lib)\//
8771
+ ];
8772
+ var PRIVATE_NETWORK_PATTERNS = [
8773
+ /(?:^|\s|\/\/)(?:10\.\d{1,3}\.\d{1,3}\.\d{1,3})/,
8774
+ /(?:^|\s|\/\/)(?:172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})/,
8775
+ /(?:^|\s|\/\/)(?:192\.168\.\d{1,3}\.\d{1,3})/,
8776
+ /(?:^|\s|\/\/)localhost(?::\d+)?/,
8777
+ /(?:^|\s|\/\/)127\.0\.0\.1/,
8778
+ /(?:^|\s|\/\/)0\.0\.0\.0/,
8779
+ /(?:^|\s|\/\/)\[?::1\]?/
8780
+ ];
8781
+ var OUTPUT_ROLE_MARKER_PATTERNS = [
8782
+ /\bsystem\s*:/i,
8783
+ /\[INST\]/,
8784
+ /\[\/INST\]/,
8785
+ /<\|im_start\|>/,
8786
+ /<\|im_end\|>/,
8787
+ /<\|system\|>/,
8788
+ /<\|user\|>/,
8789
+ /<\|assistant\|>/,
8790
+ /<<\s*SYS\s*>>/,
8791
+ /<<\s*\/SYS\s*>>/,
8792
+ /\[SYSTEM\]/,
8793
+ /### (?:System|Human|Assistant):/
8794
+ ];
7764
8795
  var InjectionDetector = class {
7765
8796
  config;
7766
8797
  stats = {
@@ -7817,6 +8848,50 @@ var InjectionDetector = class {
7817
8848
  recommendation
7818
8849
  };
7819
8850
  }
8851
+ /**
8852
+ * SEC-035: Scan outbound content for secret leaks, data exfiltration,
8853
+ * internal path exposure, and injection artifact survival.
8854
+ *
8855
+ * @param content The outbound content string to scan
8856
+ * @returns DetectionResult with outbound-specific signal types
8857
+ */
8858
+ scanOutbound(content) {
8859
+ this.stats.total_scans++;
8860
+ if (!this.config.enabled) {
8861
+ return {
8862
+ flagged: false,
8863
+ confidence: 0,
8864
+ signals: [],
8865
+ recommendation: "allow"
8866
+ };
8867
+ }
8868
+ const signals = [];
8869
+ this.detectSecretPatterns(content, signals);
8870
+ this.detectOutboundExfiltration(content, signals);
8871
+ this.detectInternalPathLeaks(content, signals);
8872
+ this.detectPrivateNetworkLeaks(content, signals);
8873
+ this.detectOutputRoleMarkers(content, signals);
8874
+ const flagged = signals.length > 0;
8875
+ if (flagged) {
8876
+ this.stats.total_flags++;
8877
+ }
8878
+ for (const sig of signals) {
8879
+ this.stats.signals_by_type[sig.type] = (this.stats.signals_by_type[sig.type] ?? 0) + 1;
8880
+ }
8881
+ const recommendation = this.computeRecommendation(
8882
+ signals,
8883
+ this.config.sensitivity
8884
+ );
8885
+ if (recommendation === "block") {
8886
+ this.stats.total_blocks++;
8887
+ }
8888
+ return {
8889
+ flagged,
8890
+ confidence: this.computeConfidence(signals),
8891
+ signals,
8892
+ recommendation
8893
+ };
8894
+ }
7820
8895
  /**
7821
8896
  * Recursively scan a value and all nested values.
7822
8897
  */
@@ -7845,14 +8920,40 @@ var InjectionDetector = class {
7845
8920
  return;
7846
8921
  }
7847
8922
  const location = path || "root";
7848
- const normalized = this.normalizeConfusables(value.normalize("NFKC"));
7849
- if (normalized !== value) {
8923
+ const invisibleCount = this.countInvisibleChars(value);
8924
+ if (invisibleCount > 3) {
8925
+ signals.push({
8926
+ type: "unicode_smuggling",
8927
+ pattern: `invisible_chars_count_${invisibleCount}`,
8928
+ location,
8929
+ severity: "high"
8930
+ });
8931
+ }
8932
+ this.detectTokenBudgetAttack(value, location, signals);
8933
+ const stripped = this.stripInvisibleChars(value);
8934
+ const nfkcOnly = stripped.normalize("NFKC");
8935
+ const normalized = this.normalizeConfusables(nfkcOnly);
8936
+ if (nfkcOnly !== stripped) {
8937
+ signals.push({
8938
+ type: "encoding_evasion",
8939
+ pattern: "unicode_normalization_delta",
8940
+ location,
8941
+ severity: "medium"
8942
+ });
8943
+ }
8944
+ if (normalized !== nfkcOnly) {
7850
8945
  signals.push({
7851
8946
  type: "encoding_evasion",
7852
8947
  pattern: "unicode_normalization_delta",
7853
8948
  location,
7854
8949
  severity: "medium"
7855
8950
  });
8951
+ signals.push({
8952
+ type: "homoglyph_attack",
8953
+ pattern: "confusable_substitution",
8954
+ location,
8955
+ severity: "high"
8956
+ });
7856
8957
  }
7857
8958
  for (const pattern of ROLE_OVERRIDE_PATTERNS) {
7858
8959
  if (pattern.test(normalized)) {
@@ -7890,21 +8991,363 @@ var InjectionDetector = class {
7890
8991
  }
7891
8992
  }
7892
8993
  this.detectEncodingEvasion(value, location, signals);
8994
+ this.detectEncodedPayloads(value, location, signals);
7893
8995
  this.detectDataExfiltration(value, location, signals);
7894
8996
  this.detectPromptStuffing(value, location, signals);
7895
8997
  }
8998
+ // ═══════════════════════════════════════════════════════════════════════════
8999
+ // SEC-034: Unicode sanitization helpers
9000
+ // ═══════════════════════════════════════════════════════════════════════════
7896
9001
  /**
7897
- * Detect base64 strings and zero-width character evasion.
9002
+ * Count invisible Unicode characters in a string.
9003
+ * Includes zero-width chars, soft hyphens, directional marks,
9004
+ * variation selectors, and other invisible categories.
7898
9005
  */
7899
- detectEncodingEvasion(value, path, signals) {
7900
- if (value.length > 50 && /^[A-Za-z0-9+/]+={0,2}$/.test(value.trim())) {
9006
+ countInvisibleChars(value) {
9007
+ let count = 0;
9008
+ for (const ch of value) {
9009
+ const cp = ch.codePointAt(0);
9010
+ if (cp === void 0) continue;
9011
+ if (INVISIBLE_CHARS.includes(ch)) {
9012
+ count++;
9013
+ continue;
9014
+ }
9015
+ if (cp >= VARIATION_SELECTOR_RANGE_START && cp <= VARIATION_SELECTOR_RANGE_END) {
9016
+ count++;
9017
+ continue;
9018
+ }
9019
+ if (cp >= 917760 && cp <= 917999) {
9020
+ count++;
9021
+ continue;
9022
+ }
9023
+ if (cp >= 917505 && cp <= 917631) {
9024
+ count++;
9025
+ continue;
9026
+ }
9027
+ if (cp >= 65529 && cp <= 65531) {
9028
+ count++;
9029
+ continue;
9030
+ }
9031
+ }
9032
+ return count;
9033
+ }
9034
+ /**
9035
+ * Strip invisible characters from a string for clean pattern matching.
9036
+ * Returns a new string with all invisible chars removed.
9037
+ */
9038
+ stripInvisibleChars(value) {
9039
+ const chars = [];
9040
+ for (const ch of value) {
9041
+ const cp = ch.codePointAt(0);
9042
+ if (cp === void 0) continue;
9043
+ if (INVISIBLE_CHARS.includes(ch)) continue;
9044
+ if (cp >= VARIATION_SELECTOR_RANGE_START && cp <= VARIATION_SELECTOR_RANGE_END) continue;
9045
+ if (cp >= 917760 && cp <= 917999) continue;
9046
+ if (cp >= 917505 && cp <= 917631) continue;
9047
+ if (cp >= 65529 && cp <= 65531) continue;
9048
+ chars.push(ch);
9049
+ }
9050
+ return chars.join("");
9051
+ }
9052
+ /**
9053
+ * SEC-034: Token budget attack detection.
9054
+ * Some Unicode sequences expand dramatically during tokenization (e.g., CJK
9055
+ * ideographs, combining characters, emoji sequences). If the estimated token
9056
+ * cost per character is anomalously high, this may be a wallet-drain payload.
9057
+ *
9058
+ * Heuristic: count chars that typically tokenize into multiple tokens.
9059
+ * If the ratio of estimated tokens to char count exceeds 3x, flag it.
9060
+ */
9061
+ detectTokenBudgetAttack(value, path, signals) {
9062
+ if (value.length < 20) return;
9063
+ const MAX_ANALYSIS_LENGTH = 1e6;
9064
+ if (value.length > MAX_ANALYSIS_LENGTH) {
9065
+ value = value.substring(0, MAX_ANALYSIS_LENGTH);
9066
+ }
9067
+ let estimatedTokens = 0;
9068
+ for (const ch of value) {
9069
+ const cp = ch.codePointAt(0);
9070
+ if (cp === void 0) continue;
9071
+ if (cp <= 127) {
9072
+ estimatedTokens += 0.25;
9073
+ } else if (cp <= 2047) {
9074
+ estimatedTokens += 0.5;
9075
+ } else if (cp <= 65535) {
9076
+ estimatedTokens += 1.5;
9077
+ } else {
9078
+ estimatedTokens += 2.5;
9079
+ }
9080
+ }
9081
+ let charCount = 0;
9082
+ for (const _ch of value) {
9083
+ charCount++;
9084
+ }
9085
+ const ratio = estimatedTokens / charCount;
9086
+ if (ratio > 3) {
7901
9087
  signals.push({
7902
- type: "encoding_evasion",
7903
- pattern: "base64_string",
7904
- location: path || "root",
9088
+ type: "token_budget_attack",
9089
+ pattern: `token_char_ratio_${ratio.toFixed(2)}`,
9090
+ location: path,
7905
9091
  severity: "medium"
7906
9092
  });
7907
9093
  }
9094
+ }
9095
+ // ═══════════════════════════════════════════════════════════════════════════
9096
+ // SEC-034: Encoded payload detection and re-scanning
9097
+ // ═══════════════════════════════════════════════════════════════════════════
9098
+ /**
9099
+ * Detect encoded content (base64, hex, HTML entities, URL encoding),
9100
+ * decode it, and re-scan the decoded content through injection patterns.
9101
+ * If the decoded content contains injection patterns, flag as encoding_evasion.
9102
+ */
9103
+ detectEncodedPayloads(value, path, signals) {
9104
+ const decodedParts = [];
9105
+ const base64Matches = value.match(BASE64_BLOCK_PATTERN);
9106
+ if (base64Matches) {
9107
+ for (const match of base64Matches) {
9108
+ const decoded = this.safeBase64Decode(match);
9109
+ if (decoded !== null) {
9110
+ decodedParts.push(decoded);
9111
+ }
9112
+ }
9113
+ }
9114
+ const hexMatches = value.match(HEX_ENCODED_PATTERN);
9115
+ if (hexMatches) {
9116
+ for (const match of hexMatches) {
9117
+ const decoded = this.safeHexDecode(match);
9118
+ if (decoded !== null) {
9119
+ decodedParts.push(decoded);
9120
+ }
9121
+ }
9122
+ }
9123
+ if (HTML_ENTITY_PATTERN.test(value)) {
9124
+ const decoded = this.decodeHtmlEntities(value);
9125
+ if (decoded !== value) {
9126
+ decodedParts.push(decoded);
9127
+ }
9128
+ }
9129
+ const urlMatches = value.match(URL_ENCODED_PATTERN);
9130
+ if (urlMatches) {
9131
+ for (const match of urlMatches) {
9132
+ const decoded = this.safeUrlDecode(match);
9133
+ if (decoded !== null && decoded !== match) {
9134
+ decodedParts.push(decoded);
9135
+ }
9136
+ }
9137
+ }
9138
+ for (const decoded of decodedParts) {
9139
+ if (this.containsInjectionPatterns(decoded)) {
9140
+ signals.push({
9141
+ type: "encoding_evasion",
9142
+ pattern: "encoded_injection_payload",
9143
+ location: path,
9144
+ severity: "high"
9145
+ });
9146
+ return;
9147
+ }
9148
+ }
9149
+ }
9150
+ /**
9151
+ * Check if a string contains any injection patterns (role override or security bypass).
9152
+ */
9153
+ containsInjectionPatterns(value) {
9154
+ const normalized = this.normalizeConfusables(value.normalize("NFKC"));
9155
+ for (const pattern of ROLE_OVERRIDE_PATTERNS) {
9156
+ if (pattern.test(normalized)) return true;
9157
+ }
9158
+ for (const pattern of SECURITY_BYPASS_PATTERNS) {
9159
+ if (pattern.test(normalized)) return true;
9160
+ }
9161
+ return false;
9162
+ }
9163
+ /**
9164
+ * Safely decode a base64 string. Returns null if it's not valid base64
9165
+ * or doesn't decode to a meaningful string.
9166
+ */
9167
+ safeBase64Decode(value) {
9168
+ try {
9169
+ const cleaned = value.replace(/-/g, "+").replace(/_/g, "/");
9170
+ const padded = cleaned + "=".repeat((4 - cleaned.length % 4) % 4);
9171
+ if (!BASE64_STANDARD_PATTERN.test(padded)) return null;
9172
+ const decoded = Buffer.from(padded, "base64").toString("utf-8");
9173
+ if (this.looksLikeText(decoded)) {
9174
+ return decoded;
9175
+ }
9176
+ return null;
9177
+ } catch {
9178
+ return null;
9179
+ }
9180
+ }
9181
+ /**
9182
+ * Safely decode a hex string. Returns null on failure.
9183
+ */
9184
+ safeHexDecode(value) {
9185
+ try {
9186
+ const hex = value.startsWith("0x") ? value.slice(2) : value;
9187
+ if (hex.length % 2 !== 0) return null;
9188
+ const decoded = Buffer.from(hex, "hex").toString("utf-8");
9189
+ if (this.looksLikeText(decoded)) {
9190
+ return decoded;
9191
+ }
9192
+ return null;
9193
+ } catch {
9194
+ return null;
9195
+ }
9196
+ }
9197
+ /**
9198
+ * Decode HTML numeric entities (&#xHH; and &#DDD;) in a string.
9199
+ */
9200
+ decodeHtmlEntities(value) {
9201
+ return value.replace(/&#x([0-9a-fA-F]{2,4});/g, (_match, hex) => {
9202
+ try {
9203
+ return String.fromCodePoint(parseInt(hex, 16));
9204
+ } catch {
9205
+ return _match;
9206
+ }
9207
+ }).replace(/&#([0-9]{2,5});/g, (_match, dec) => {
9208
+ try {
9209
+ const cp = parseInt(dec, 10);
9210
+ if (cp > 1114111) return _match;
9211
+ return String.fromCodePoint(cp);
9212
+ } catch {
9213
+ return _match;
9214
+ }
9215
+ });
9216
+ }
9217
+ /**
9218
+ * Safely decode a URL-encoded string. Returns null on failure.
9219
+ */
9220
+ safeUrlDecode(value) {
9221
+ try {
9222
+ return decodeURIComponent(value);
9223
+ } catch {
9224
+ return null;
9225
+ }
9226
+ }
9227
+ /**
9228
+ * Heuristic: does this look like readable text (vs. binary garbage)?
9229
+ * Checks that most characters are printable ASCII or common Unicode.
9230
+ */
9231
+ looksLikeText(value) {
9232
+ if (value.length === 0) return false;
9233
+ let printable = 0;
9234
+ for (let i = 0; i < value.length; i++) {
9235
+ const code = value.charCodeAt(i);
9236
+ if (code >= 32 && code <= 126 || code === 10 || code === 13 || code === 9) {
9237
+ printable++;
9238
+ } else if (code >= 128) {
9239
+ if (code < 160) continue;
9240
+ printable++;
9241
+ }
9242
+ }
9243
+ return printable / value.length > 0.7;
9244
+ }
9245
+ // ═══════════════════════════════════════════════════════════════════════════
9246
+ // SEC-035: Outbound content scanning helpers
9247
+ // ═══════════════════════════════════════════════════════════════════════════
9248
+ /**
9249
+ * Detect API keys and secrets in outbound content.
9250
+ */
9251
+ detectSecretPatterns(content, signals) {
9252
+ for (const { pattern, name } of SECRET_PATTERNS) {
9253
+ if (pattern.test(content)) {
9254
+ signals.push({
9255
+ type: "secret_leak",
9256
+ pattern: name,
9257
+ location: "outbound",
9258
+ severity: "high"
9259
+ });
9260
+ }
9261
+ }
9262
+ }
9263
+ /**
9264
+ * Detect data exfiltration via markdown images with data-carrying query params.
9265
+ */
9266
+ detectOutboundExfiltration(content, signals) {
9267
+ if (MARKDOWN_IMAGE_EXFIL_PATTERN.test(content)) {
9268
+ signals.push({
9269
+ type: "data_exfiltration",
9270
+ pattern: "markdown_image_exfil",
9271
+ location: "outbound",
9272
+ severity: "high"
9273
+ });
9274
+ }
9275
+ }
9276
+ /**
9277
+ * Detect internal filesystem path leaks in outbound content.
9278
+ */
9279
+ detectInternalPathLeaks(content, signals) {
9280
+ for (const pattern of INTERNAL_PATH_PATTERNS) {
9281
+ if (pattern.test(content)) {
9282
+ signals.push({
9283
+ type: "internal_path_leak",
9284
+ pattern: pattern.source,
9285
+ location: "outbound",
9286
+ severity: "medium"
9287
+ });
9288
+ return;
9289
+ }
9290
+ }
9291
+ }
9292
+ /**
9293
+ * Detect private IP addresses and localhost references in outbound content.
9294
+ */
9295
+ detectPrivateNetworkLeaks(content, signals) {
9296
+ for (const pattern of PRIVATE_NETWORK_PATTERNS) {
9297
+ if (pattern.test(content)) {
9298
+ signals.push({
9299
+ type: "private_network_leak",
9300
+ pattern: pattern.source,
9301
+ location: "outbound",
9302
+ severity: "medium"
9303
+ });
9304
+ return;
9305
+ }
9306
+ }
9307
+ }
9308
+ /**
9309
+ * Detect role markers / prompt template artifacts in outbound content.
9310
+ * These should never appear in agent output — their presence indicates
9311
+ * injection artifact survival.
9312
+ */
9313
+ detectOutputRoleMarkers(content, signals) {
9314
+ for (const pattern of OUTPUT_ROLE_MARKER_PATTERNS) {
9315
+ if (pattern.test(content)) {
9316
+ signals.push({
9317
+ type: "injection_artifact",
9318
+ pattern: pattern.source,
9319
+ location: "outbound",
9320
+ severity: "high"
9321
+ });
9322
+ return;
9323
+ }
9324
+ }
9325
+ }
9326
+ // ═══════════════════════════════════════════════════════════════════════════
9327
+ // Existing detection methods (enhanced)
9328
+ // ═══════════════════════════════════════════════════════════════════════════
9329
+ /**
9330
+ * Detect base64 strings, base64url, and zero-width character evasion.
9331
+ */
9332
+ detectEncodingEvasion(value, path, signals) {
9333
+ const trimmed = value.trim();
9334
+ if (value.length > 50) {
9335
+ if (BASE64_STANDARD_PATTERN.test(trimmed)) {
9336
+ signals.push({
9337
+ type: "encoding_evasion",
9338
+ pattern: "base64_string",
9339
+ location: path || "root",
9340
+ severity: "medium"
9341
+ });
9342
+ } else if (BASE64URL_PATTERN.test(trimmed) && /[_-]/.test(trimmed)) {
9343
+ signals.push({
9344
+ type: "encoding_evasion",
9345
+ pattern: "base64url_string",
9346
+ location: path || "root",
9347
+ severity: "medium"
9348
+ });
9349
+ }
9350
+ }
7908
9351
  let zeroWidthCount = 0;
7909
9352
  for (const char of ZERO_WIDTH_CHARS) {
7910
9353
  zeroWidthCount += (value.match(new RegExp(char, "g")) || []).length;
@@ -8083,62 +9526,89 @@ var InjectionDetector = class {
8083
9526
  return structuredFields.some((p) => p.test(path));
8084
9527
  }
8085
9528
  /**
8086
- * SEC-032: Map common cross-script confusable characters to their Latin equivalents.
8087
- * NFKC normalization handles fullwidth and compatibility forms, but does NOT map
8088
- * Cyrillic/Greek lookalikes to Latin (they're distinct codepoints by design).
8089
- * This covers the most common confusables used in injection evasion.
9529
+ * SEC-032/SEC-034: Map common cross-script confusable characters to their
9530
+ * Latin equivalents. NFKC normalization handles fullwidth and compatibility
9531
+ * forms, but does NOT map Cyrillic/Greek/Armenian/Georgian lookalikes to
9532
+ * Latin (they're distinct codepoints by design).
9533
+ *
9534
+ * Extended to 50+ confusable pairs covering Cyrillic, Greek, Armenian,
9535
+ * Georgian, Cherokee, and mathematical/symbol lookalikes.
8090
9536
  */
8091
9537
  normalizeConfusables(value) {
8092
9538
  const confusables = {
8093
- // Cyrillic → Latin
9539
+ // ── Cyrillic → Latin ──────────────────────────────────────────────
8094
9540
  "\u0410": "A",
8095
9541
  "\u0430": "a",
8096
9542
  // А а
8097
9543
  "\u0412": "B",
8098
9544
  "\u0432": "b",
8099
- // В (not exact) в (not exact)
9545
+ // В в (visual approximation)
8100
9546
  "\u0421": "C",
8101
9547
  "\u0441": "c",
8102
9548
  // С с
9549
+ "\u0414": "D",
9550
+ // Д (visual approximation)
8103
9551
  "\u0415": "E",
8104
9552
  "\u0435": "e",
8105
9553
  // Е е
8106
9554
  "\u041D": "H",
8107
9555
  "\u043D": "h",
8108
- // Н (not exact) н (not exact)
9556
+ // Н н (visual approximation)
9557
+ "\u0406": "I",
9558
+ "\u0456": "i",
9559
+ // І і (Ukrainian I)
9560
+ "\u0408": "J",
9561
+ // Ј (Serbian Je)
8109
9562
  "\u041A": "K",
8110
9563
  "\u043A": "k",
8111
- // К к (not exact)
9564
+ // К к (visual approximation)
8112
9565
  "\u041C": "M",
8113
9566
  "\u043C": "m",
8114
- // М (not exact) м (not exact)
9567
+ // М м (visual approximation)
8115
9568
  "\u041E": "O",
8116
9569
  "\u043E": "o",
8117
9570
  // О о
8118
9571
  "\u0420": "P",
8119
9572
  "\u0440": "p",
8120
9573
  // Р р
9574
+ "\u0405": "S",
9575
+ "\u0455": "s",
9576
+ // Ѕ ѕ (Macedonian S)
8121
9577
  "\u0422": "T",
8122
9578
  "\u0442": "t",
8123
- // Т (not exact) т (not exact)
9579
+ // Т т (visual approximation)
8124
9580
  "\u0425": "X",
8125
9581
  "\u0445": "x",
8126
9582
  // Х х
8127
9583
  "\u0423": "Y",
8128
9584
  "\u0443": "y",
8129
- // У (not exact) у
8130
- // Greek → Latin
9585
+ // У у (visual approximation)
9586
+ "\u0417": "3",
9587
+ // З (looks like 3)
9588
+ "\u04BB": "h",
9589
+ // һ (Shha)
9590
+ "\u04C0": "I",
9591
+ // Ӏ (Palochka)
9592
+ "\u04CF": "l",
9593
+ // ӏ (Palochka small)
9594
+ // ── Greek → Latin ─────────────────────────────────────────────────
8131
9595
  "\u0391": "A",
8132
9596
  "\u03B1": "a",
8133
- // Α α (not exact)
9597
+ // Α α (alpha not exact)
8134
9598
  "\u0392": "B",
8135
9599
  "\u03B2": "b",
8136
9600
  // Β β (not exact)
9601
+ "\u0393": "G",
9602
+ // Γ (visual approximation)
8137
9603
  "\u0395": "E",
8138
9604
  "\u03B5": "e",
8139
9605
  // Ε ε (not exact)
9606
+ "\u0396": "Z",
9607
+ "\u03B6": "z",
9608
+ // Ζ ζ (not exact)
8140
9609
  "\u0397": "H",
8141
- // Η
9610
+ "\u03B7": "n",
9611
+ // Η η (not exact)
8142
9612
  "\u0399": "I",
8143
9613
  "\u03B9": "i",
8144
9614
  // Ι ι
@@ -8162,8 +9632,78 @@ var InjectionDetector = class {
8162
9632
  "\u03C5": "y",
8163
9633
  // Υ υ (not exact)
8164
9634
  "\u03A7": "X",
8165
- "\u03C7": "x"
9635
+ "\u03C7": "x",
8166
9636
  // Χ χ (not exact)
9637
+ "\u03C9": "w",
9638
+ // ω (omega, visual approximation)
9639
+ // ── Armenian → Latin ──────────────────────────────────────────────
9640
+ "\u0555": "O",
9641
+ // Օ
9642
+ "\u0585": "o",
9643
+ // օ
9644
+ "\u054D": "S",
9645
+ // Ս
9646
+ "\u057D": "s",
9647
+ // ս
9648
+ "\u054C": "L",
9649
+ // Լ (visual approximation)
9650
+ "\u0570": "h",
9651
+ // հ
9652
+ // ── Cherokee → Latin ──────────────────────────────────────────────
9653
+ "\u13A0": "D",
9654
+ // Ꭰ
9655
+ "\u13B3": "W",
9656
+ // Ꮃ
9657
+ "\u13A1": "R",
9658
+ // Ꭱ
9659
+ "\u13AA": "G",
9660
+ // Ꭺ (looks like A but maps to G sound)
9661
+ "\u13D2": "V",
9662
+ // Ꮢ (visual approximation)
9663
+ // ── Georgian → Latin ──────────────────────────────────────────────
9664
+ "\u10D5": "v",
9665
+ // ვ (Georgian letter vin)
9666
+ "\u10D3": "d",
9667
+ // დ (Georgian letter don)
9668
+ "\u10DA": "l",
9669
+ // ლ (Georgian letter las)
9670
+ // ── Latin special → Latin ────────────────────────────────────────
9671
+ "\u0131": "i",
9672
+ // ı (Latin small letter dotless i)
9673
+ // ── Symbols / Mathematical → Latin ────────────────────────────────
9674
+ // Note: NFKC normalization handles mathematical alphanumerics (U+1D400–U+1D7FF)
9675
+ "\u2160": "I",
9676
+ // Ⅰ (Roman numeral one)
9677
+ "\u2164": "V",
9678
+ // Ⅴ (Roman numeral five)
9679
+ "\u2169": "X",
9680
+ // Ⅹ (Roman numeral ten)
9681
+ "\u216C": "L",
9682
+ // Ⅼ (Roman numeral fifty)
9683
+ "\u216D": "C",
9684
+ // Ⅽ (Roman numeral one hundred)
9685
+ "\u216E": "D",
9686
+ // Ⅾ (Roman numeral five hundred)
9687
+ "\u216F": "M",
9688
+ // Ⅿ (Roman numeral one thousand)
9689
+ "\u2170": "i",
9690
+ // ⅰ (small Roman numeral one)
9691
+ "\u2174": "v",
9692
+ // ⅴ (small Roman numeral five)
9693
+ "\u2179": "x",
9694
+ // ⅹ (small Roman numeral ten)
9695
+ "\u217C": "l",
9696
+ // ⅼ (small Roman numeral fifty)
9697
+ "\u217D": "c",
9698
+ // ⅽ (small Roman numeral one hundred)
9699
+ "\u217E": "d",
9700
+ // ⅾ (small Roman numeral five hundred)
9701
+ "\u217F": "m",
9702
+ // ⅿ (small Roman numeral one thousand)
9703
+ "\u0251": "a",
9704
+ // ɑ (Latin alpha — looks like 'a')
9705
+ "\u0261": "g"
9706
+ // ɡ (Latin small letter script G)
8167
9707
  };
8168
9708
  let result = value;
8169
9709
  if (/[^\x00-\x7F]/.test(value)) {
@@ -8253,6 +9793,7 @@ var ApprovalGate = class {
8253
9793
  auditLog;
8254
9794
  injectionDetector;
8255
9795
  onInjectionAlert;
9796
+ proxyTierResolver;
8256
9797
  constructor(policy, baseline, channel, auditLog, injectionDetector, onInjectionAlert) {
8257
9798
  this.policy = policy;
8258
9799
  this.baseline = baseline;
@@ -8261,6 +9802,12 @@ var ApprovalGate = class {
8261
9802
  this.injectionDetector = injectionDetector ?? new InjectionDetector();
8262
9803
  this.onInjectionAlert = onInjectionAlert;
8263
9804
  }
9805
+ /**
9806
+ * Set the proxy tier resolver. Called after the proxy router is initialized.
9807
+ */
9808
+ setProxyTierResolver(resolver) {
9809
+ this.proxyTierResolver = resolver;
9810
+ }
8264
9811
  /**
8265
9812
  * Evaluate a tool call against the Principal Policy.
8266
9813
  *
@@ -8313,6 +9860,38 @@ var ApprovalGate = class {
8313
9860
  );
8314
9861
  }
8315
9862
  }
9863
+ if (toolName.startsWith("proxy/") && this.proxyTierResolver) {
9864
+ const proxyTier = this.proxyTierResolver(toolName);
9865
+ if (proxyTier !== null) {
9866
+ if (proxyTier === 1) {
9867
+ return this.requestApproval(operation, 1, `Proxy tool "${toolName}" is configured as Tier 1 (always requires approval)`, {
9868
+ operation: toolName,
9869
+ proxy: true,
9870
+ args_summary: this.summarizeArgs(args)
9871
+ });
9872
+ }
9873
+ if (proxyTier === 2) {
9874
+ const anomaly2 = this.detectAnomaly(operation, args);
9875
+ if (anomaly2) {
9876
+ return this.requestApproval(operation, 2, `Proxy: ${anomaly2.reason}`, {
9877
+ ...anomaly2.context,
9878
+ proxy: true
9879
+ });
9880
+ }
9881
+ }
9882
+ this.auditLog.append("l2", `gate_allow_proxy:${toolName}`, "system", {
9883
+ tier: proxyTier,
9884
+ operation: toolName,
9885
+ proxy: true
9886
+ });
9887
+ return {
9888
+ allowed: true,
9889
+ tier: proxyTier,
9890
+ reason: `Proxy operation allowed (Tier ${proxyTier})`,
9891
+ approval_required: false
9892
+ };
9893
+ }
9894
+ }
8316
9895
  if (this.policy.tier1_always_approve.includes(operation)) {
8317
9896
  return this.requestApproval(operation, 1, `"${operation}" is a Tier 1 operation (always requires approval)`, {
8318
9897
  operation,
@@ -9990,7 +11569,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
9990
11569
  const now = (/* @__PURE__ */ new Date()).toISOString();
9991
11570
  const canonicalBytes = canonicalize(outcome);
9992
11571
  const canonicalString = new TextDecoder().decode(canonicalBytes);
9993
- const sha2564 = createCommitment(canonicalString);
11572
+ const sha2565 = createCommitment(canonicalString);
9994
11573
  let pedersenData;
9995
11574
  if (includePedersen && Number.isInteger(outcome.rounds) && outcome.rounds >= 0) {
9996
11575
  const pedersen = createPedersenCommitment(outcome.rounds);
@@ -10002,7 +11581,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
10002
11581
  const commitmentPayload = {
10003
11582
  bridge_commitment_id: commitmentId,
10004
11583
  session_id: outcome.session_id,
10005
- sha256_commitment: sha2564.commitment,
11584
+ sha256_commitment: sha2565.commitment,
10006
11585
  terms_hash: outcome.terms_hash,
10007
11586
  committer_did: identity.did,
10008
11587
  committed_at: now,
@@ -10013,8 +11592,8 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
10013
11592
  return {
10014
11593
  bridge_commitment_id: commitmentId,
10015
11594
  session_id: outcome.session_id,
10016
- sha256_commitment: sha2564.commitment,
10017
- blinding_factor: sha2564.blinding_factor,
11595
+ sha256_commitment: sha2565.commitment,
11596
+ blinding_factor: sha2565.blinding_factor,
10018
11597
  committer_did: identity.did,
10019
11598
  signature: toBase64url(signature),
10020
11599
  pedersen_commitment: pedersenData,
@@ -13090,7 +14669,8 @@ function createDefaultProfile() {
13090
14669
  audit_logging: { enabled: true },
13091
14670
  injection_detection: { enabled: true },
13092
14671
  context_gating: { enabled: false },
13093
- approval_gate: { enabled: false },
14672
+ approval_gate: { enabled: true },
14673
+ // SEC-057: always enabled — core enforcement
13094
14674
  zk_proofs: { enabled: false }
13095
14675
  },
13096
14676
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
@@ -13141,6 +14721,9 @@ var SovereigntyProfileStore = class {
13141
14721
  if (!this.profile) {
13142
14722
  await this.load();
13143
14723
  }
14724
+ if (updates.approval_gate && updates.approval_gate.enabled === false) {
14725
+ throw new Error("approval_gate cannot be disabled \u2014 it is a core enforcement feature");
14726
+ }
13144
14727
  const features = this.profile.features;
13145
14728
  if (updates.audit_logging !== void 0) {
13146
14729
  if (updates.audit_logging.enabled !== void 0) {
@@ -13195,6 +14778,48 @@ var SovereigntyProfileStore = class {
13195
14778
  features.zk_proofs.enabled = updates.zk_proofs.enabled;
13196
14779
  }
13197
14780
  }
14781
+ if (updates.upstream_servers !== void 0) {
14782
+ if (!Array.isArray(updates.upstream_servers)) {
14783
+ throw new Error("upstream_servers must be an array");
14784
+ }
14785
+ for (const server of updates.upstream_servers) {
14786
+ if (!server.name || typeof server.name !== "string") {
14787
+ throw new Error("Each upstream server must have a name");
14788
+ }
14789
+ if (server.name.length > 128) {
14790
+ throw new Error("Upstream server name must be 128 characters or fewer");
14791
+ }
14792
+ if (!/^[a-zA-Z0-9_-]+$/.test(server.name)) {
14793
+ throw new Error("Upstream server name must contain only alphanumeric characters, hyphens, and underscores");
14794
+ }
14795
+ if (!server.transport || typeof server.transport !== "object") {
14796
+ throw new Error("Each upstream server must have a transport configuration");
14797
+ }
14798
+ if (server.transport.type !== "stdio" && server.transport.type !== "sse") {
14799
+ throw new Error("Transport type must be 'stdio' or 'sse'");
14800
+ }
14801
+ if (server.transport.type === "stdio" && !server.transport.command) {
14802
+ throw new Error("stdio transport requires a command");
14803
+ }
14804
+ if (server.transport.type === "sse" && !server.transport.url) {
14805
+ throw new Error("sse transport requires a url");
14806
+ }
14807
+ if (typeof server.enabled !== "boolean") {
14808
+ throw new Error("Each upstream server must have enabled as a boolean");
14809
+ }
14810
+ if (![1, 2, 3].includes(server.default_tier)) {
14811
+ throw new Error("default_tier must be 1, 2, or 3");
14812
+ }
14813
+ if (server.tool_overrides) {
14814
+ for (const [, override] of Object.entries(server.tool_overrides)) {
14815
+ if (![1, 2, 3].includes(override.tier)) {
14816
+ throw new Error("tool_overrides tier must be 1, 2, or 3");
14817
+ }
14818
+ }
14819
+ }
14820
+ }
14821
+ this.profile.upstream_servers = updates.upstream_servers;
14822
+ }
13198
14823
  this.profile.updated_at = (/* @__PURE__ */ new Date()).toISOString();
13199
14824
  await this.persist();
13200
14825
  return this.profile;
@@ -13340,21 +14965,855 @@ function createSovereigntyProfileTools(profileStore, auditLog) {
13340
14965
  ];
13341
14966
  return { tools };
13342
14967
  }
13343
-
13344
- // src/index.ts
13345
- init_random();
13346
- init_encoding();
13347
-
13348
- // src/l2-operational/model-provenance.ts
13349
- var InMemoryModelProvenanceStore = class {
13350
- models = /* @__PURE__ */ new Map();
13351
- primaryModelId = null;
13352
- declare(provenance) {
13353
- if (!provenance.model_id) {
13354
- throw new Error("ModelProvenance requires a model_id");
13355
- }
13356
- if (!provenance.model_name) {
13357
- throw new Error("ModelProvenance requires a model_name");
14968
+ var MAX_RETRIES = 5;
14969
+ var BASE_BACKOFF_MS = 1e3;
14970
+ var MAX_BACKOFF_MS = 3e4;
14971
+ var MAX_UPSTREAM_SERVERS = 20;
14972
+ var ClientManager = class {
14973
+ connections = /* @__PURE__ */ new Map();
14974
+ onStateChange;
14975
+ shutdownRequested = false;
14976
+ constructor(options) {
14977
+ this.onStateChange = options?.onStateChange;
14978
+ }
14979
+ /**
14980
+ * Configure upstream servers. Disconnects removed servers, connects new ones.
14981
+ * Non-blocking — connection failures are handled asynchronously.
14982
+ */
14983
+ async configure(servers) {
14984
+ if (servers.length > MAX_UPSTREAM_SERVERS) {
14985
+ throw new Error(`Maximum ${MAX_UPSTREAM_SERVERS} upstream servers allowed`);
14986
+ }
14987
+ const SAFE_SERVER_NAME = /^[a-zA-Z0-9_\-]+$/;
14988
+ const newNames = new Set(servers.filter((s) => {
14989
+ if (!SAFE_SERVER_NAME.test(s.name)) {
14990
+ return false;
14991
+ }
14992
+ return s.enabled;
14993
+ }).map((s) => s.name));
14994
+ for (const [name] of this.connections) {
14995
+ if (!newNames.has(name)) {
14996
+ await this.disconnectServer(name);
14997
+ }
14998
+ }
14999
+ for (const server of servers) {
15000
+ if (!SAFE_SERVER_NAME.test(server.name)) {
15001
+ continue;
15002
+ }
15003
+ if (!server.enabled) {
15004
+ if (this.connections.has(server.name)) {
15005
+ await this.disconnectServer(server.name);
15006
+ }
15007
+ continue;
15008
+ }
15009
+ const existing = this.connections.get(server.name);
15010
+ if (existing && existing.state === "connected") {
15011
+ existing.server = server;
15012
+ continue;
15013
+ }
15014
+ this.connectServer(server);
15015
+ }
15016
+ }
15017
+ /**
15018
+ * Get all discovered tools across all connected upstream servers.
15019
+ */
15020
+ getAllTools() {
15021
+ const result = /* @__PURE__ */ new Map();
15022
+ for (const [name, conn] of this.connections) {
15023
+ if (conn.state === "connected" && conn.tools.length > 0) {
15024
+ result.set(name, conn.tools);
15025
+ }
15026
+ }
15027
+ return result;
15028
+ }
15029
+ /**
15030
+ * Get connection status for all configured servers.
15031
+ */
15032
+ getStatus() {
15033
+ return Array.from(this.connections.values()).map((conn) => ({
15034
+ name: conn.server.name,
15035
+ state: conn.state,
15036
+ transport_type: conn.server.transport.type,
15037
+ tool_count: conn.tools.length,
15038
+ error: conn.error
15039
+ }));
15040
+ }
15041
+ /**
15042
+ * Get the upstream server config by name.
15043
+ */
15044
+ getServerConfig(name) {
15045
+ return this.connections.get(name)?.server;
15046
+ }
15047
+ /**
15048
+ * Call a tool on an upstream server.
15049
+ */
15050
+ async callTool(serverName, toolName, args) {
15051
+ const conn = this.connections.get(serverName);
15052
+ if (!conn) {
15053
+ throw new Error(`Upstream server "${serverName}" is not configured`);
15054
+ }
15055
+ if (conn.state !== "connected" || !conn.client) {
15056
+ throw new Error(`Upstream server "${serverName}" is not connected (state: ${conn.state})`);
15057
+ }
15058
+ const result = await conn.client.callTool({
15059
+ name: toolName,
15060
+ arguments: args
15061
+ });
15062
+ return result;
15063
+ }
15064
+ /**
15065
+ * Shut down all connections cleanly.
15066
+ */
15067
+ async shutdown() {
15068
+ this.shutdownRequested = true;
15069
+ for (const conn of this.connections.values()) {
15070
+ if (conn.retryTimer) {
15071
+ clearTimeout(conn.retryTimer);
15072
+ conn.retryTimer = void 0;
15073
+ }
15074
+ }
15075
+ const disconnects = Array.from(this.connections.keys()).map(
15076
+ (name) => this.disconnectServer(name)
15077
+ );
15078
+ await Promise.allSettled(disconnects);
15079
+ }
15080
+ // ── Private ───────────────────────────────────────────────────────────
15081
+ /**
15082
+ * Connect to an upstream server (non-blocking).
15083
+ * Spawns connection attempt in background — does not throw.
15084
+ */
15085
+ connectServer(server) {
15086
+ const conn = {
15087
+ server,
15088
+ client: null,
15089
+ transport: null,
15090
+ state: "connecting",
15091
+ tools: [],
15092
+ retryCount: 0
15093
+ };
15094
+ this.connections.set(server.name, conn);
15095
+ this.notifyStateChange(conn);
15096
+ this.doConnect(conn).catch(() => {
15097
+ });
15098
+ }
15099
+ /**
15100
+ * Perform the actual connection to an upstream server.
15101
+ */
15102
+ async doConnect(conn) {
15103
+ try {
15104
+ conn.state = "connecting";
15105
+ this.notifyStateChange(conn);
15106
+ let transport;
15107
+ if (conn.server.transport.type === "stdio") {
15108
+ if (!conn.server.transport.command) {
15109
+ throw new Error("stdio transport requires a command");
15110
+ }
15111
+ if (conn.server.transport.args) {
15112
+ const SAFE_ARG_PATTERN = /^[a-zA-Z0-9._\-\/=:@]+$/;
15113
+ for (const arg of conn.server.transport.args) {
15114
+ if (!SAFE_ARG_PATTERN.test(arg)) {
15115
+ throw new Error(`Unsafe argument rejected: contains disallowed characters`);
15116
+ }
15117
+ }
15118
+ }
15119
+ const ENV_BLOCKLIST = /* @__PURE__ */ new Set([
15120
+ "PATH",
15121
+ "HOME",
15122
+ "USER",
15123
+ "SHELL",
15124
+ "NODE_OPTIONS",
15125
+ "NODE_PATH",
15126
+ "LD_PRELOAD",
15127
+ "LD_LIBRARY_PATH",
15128
+ "DYLD_INSERT_LIBRARIES",
15129
+ "PYTHONPATH",
15130
+ "RUBYLIB",
15131
+ "PERL5LIB",
15132
+ "HTTP_PROXY",
15133
+ "HTTPS_PROXY",
15134
+ "NO_PROXY",
15135
+ "http_proxy",
15136
+ "https_proxy",
15137
+ "no_proxy"
15138
+ ]);
15139
+ let transportEnv;
15140
+ if (conn.server.transport.env) {
15141
+ const safeEnv = { ...process.env };
15142
+ for (const [key, value] of Object.entries(conn.server.transport.env)) {
15143
+ if (!ENV_BLOCKLIST.has(key)) {
15144
+ safeEnv[key] = value;
15145
+ }
15146
+ }
15147
+ transportEnv = safeEnv;
15148
+ }
15149
+ transport = new stdio_js.StdioClientTransport({
15150
+ command: conn.server.transport.command,
15151
+ args: conn.server.transport.args,
15152
+ env: transportEnv
15153
+ });
15154
+ } else {
15155
+ if (!conn.server.transport.url) {
15156
+ throw new Error("sse transport requires a url");
15157
+ }
15158
+ const ssrfUrl = new URL(conn.server.transport.url);
15159
+ if (ssrfUrl.protocol !== "http:" && ssrfUrl.protocol !== "https:") {
15160
+ throw new Error("SSE transport URL must use http or https scheme");
15161
+ }
15162
+ transport = new sse_js.SSEClientTransport(ssrfUrl);
15163
+ }
15164
+ const client = new index_js.Client(
15165
+ { name: `sanctuary-proxy/${conn.server.name}`, version: "1.0.0" },
15166
+ { capabilities: {} }
15167
+ );
15168
+ await client.connect(transport);
15169
+ conn.client = client;
15170
+ conn.transport = transport;
15171
+ conn.state = "connected";
15172
+ conn.error = void 0;
15173
+ conn.retryCount = 0;
15174
+ await this.discoverTools(conn);
15175
+ this.notifyStateChange(conn);
15176
+ } catch (err) {
15177
+ const message = err instanceof Error ? err.message : "Unknown connection error";
15178
+ conn.state = "error";
15179
+ conn.error = message;
15180
+ conn.client = null;
15181
+ conn.transport = null;
15182
+ this.notifyStateChange(conn);
15183
+ this.scheduleRetry(conn);
15184
+ }
15185
+ }
15186
+ /**
15187
+ * Discover tools from a connected upstream server.
15188
+ */
15189
+ async discoverTools(conn) {
15190
+ if (!conn.client || conn.state !== "connected") return;
15191
+ try {
15192
+ const result = await conn.client.listTools();
15193
+ conn.tools = (result.tools ?? []).map((t) => ({
15194
+ name: t.name,
15195
+ description: t.description ?? "",
15196
+ inputSchema: t.inputSchema ?? { type: "object", properties: {} }
15197
+ }));
15198
+ } catch {
15199
+ conn.tools = [];
15200
+ }
15201
+ }
15202
+ /**
15203
+ * Schedule a reconnection attempt with exponential backoff.
15204
+ */
15205
+ scheduleRetry(conn) {
15206
+ if (this.shutdownRequested) return;
15207
+ if (conn.retryCount >= MAX_RETRIES) {
15208
+ conn.error = `Max retries (${MAX_RETRIES}) exceeded. Last error: ${conn.error}`;
15209
+ this.notifyStateChange(conn);
15210
+ return;
15211
+ }
15212
+ const delay = Math.min(
15213
+ BASE_BACKOFF_MS * Math.pow(2, conn.retryCount),
15214
+ MAX_BACKOFF_MS
15215
+ );
15216
+ conn.retryCount++;
15217
+ conn.retryTimer = setTimeout(() => {
15218
+ if (this.shutdownRequested) return;
15219
+ conn.retryTimer = void 0;
15220
+ this.doConnect(conn).catch(() => {
15221
+ });
15222
+ }, delay);
15223
+ }
15224
+ /**
15225
+ * Disconnect a specific upstream server.
15226
+ */
15227
+ async disconnectServer(name) {
15228
+ const conn = this.connections.get(name);
15229
+ if (!conn) return;
15230
+ if (conn.retryTimer) {
15231
+ clearTimeout(conn.retryTimer);
15232
+ conn.retryTimer = void 0;
15233
+ }
15234
+ if (conn.client) {
15235
+ try {
15236
+ await conn.client.close();
15237
+ } catch {
15238
+ }
15239
+ }
15240
+ if (conn.transport) {
15241
+ try {
15242
+ await conn.transport.close();
15243
+ } catch {
15244
+ }
15245
+ }
15246
+ this.connections.delete(name);
15247
+ }
15248
+ /**
15249
+ * Notify listener of state change.
15250
+ */
15251
+ notifyStateChange(conn) {
15252
+ if (this.onStateChange) {
15253
+ try {
15254
+ this.onStateChange(conn.server.name, conn.state, conn.tools.length, conn.error);
15255
+ } catch {
15256
+ }
15257
+ }
15258
+ }
15259
+ };
15260
+
15261
+ // src/proxy/proxy-router.ts
15262
+ var UPSTREAM_CALL_TIMEOUT_MS = 3e4;
15263
+ var ProxyRouter = class {
15264
+ clientManager;
15265
+ injectionDetector;
15266
+ auditLog;
15267
+ options;
15268
+ constructor(clientManager, injectionDetector, auditLog, options) {
15269
+ this.clientManager = clientManager;
15270
+ this.injectionDetector = injectionDetector;
15271
+ this.auditLog = auditLog;
15272
+ this.options = options ?? {};
15273
+ }
15274
+ /**
15275
+ * Convert all discovered upstream tools to Sanctuary ToolDefinitions.
15276
+ * Each tool is registered as `proxy/{server_name}/{tool_name}`.
15277
+ */
15278
+ getProxiedTools() {
15279
+ const tools = [];
15280
+ const allUpstreamTools = this.clientManager.getAllTools();
15281
+ for (const [serverName, serverTools] of allUpstreamTools) {
15282
+ for (const upstreamTool of serverTools) {
15283
+ const proxyName = `proxy/${serverName}/${upstreamTool.name}`;
15284
+ tools.push({
15285
+ name: proxyName,
15286
+ description: `[via ${serverName}] ${upstreamTool.description}`,
15287
+ inputSchema: upstreamTool.inputSchema,
15288
+ handler: this.createHandler(serverName, upstreamTool.name)
15289
+ });
15290
+ }
15291
+ }
15292
+ return tools;
15293
+ }
15294
+ /**
15295
+ * Determine the tier for a proxied tool call.
15296
+ * Checks tool_overrides first, then falls back to default_tier.
15297
+ */
15298
+ getTierForTool(serverName, toolName) {
15299
+ const serverConfig = this.clientManager.getServerConfig(serverName);
15300
+ if (!serverConfig) return 2;
15301
+ if (serverConfig.tool_overrides?.[toolName]) {
15302
+ return serverConfig.tool_overrides[toolName].tier;
15303
+ }
15304
+ return serverConfig.default_tier;
15305
+ }
15306
+ /**
15307
+ * Parse a proxy tool name into server name and tool name.
15308
+ * Returns null if the name doesn't match the proxy namespace.
15309
+ */
15310
+ static parseProxyToolName(fullName) {
15311
+ if (!fullName.startsWith("proxy/")) return null;
15312
+ const rest = fullName.slice("proxy/".length);
15313
+ const slashIdx = rest.indexOf("/");
15314
+ if (slashIdx === -1) return null;
15315
+ return {
15316
+ serverName: rest.slice(0, slashIdx),
15317
+ toolName: rest.slice(slashIdx + 1)
15318
+ };
15319
+ }
15320
+ // ── Private ───────────────────────────────────────────────────────────
15321
+ /**
15322
+ * Create a handler for a specific proxied tool.
15323
+ * The handler runs the full enforcement chain before forwarding.
15324
+ */
15325
+ createHandler(serverName, toolName) {
15326
+ return async (args) => {
15327
+ const proxyName = `proxy/${serverName}/${toolName}`;
15328
+ const start = Date.now();
15329
+ const tier = this.getTierForTool(serverName, toolName);
15330
+ try {
15331
+ const injectionResult = this.injectionDetector.scan(proxyName, args);
15332
+ if (injectionResult.flagged && injectionResult.recommendation === "block") {
15333
+ this.auditLog.append("l2", `proxy_injection_blocked:${proxyName}`, "system", {
15334
+ server: serverName,
15335
+ tool: toolName,
15336
+ tier,
15337
+ confidence: injectionResult.confidence,
15338
+ latency_ms: Date.now() - start
15339
+ }, "failure");
15340
+ return toolResult({
15341
+ error: "Operation not permitted",
15342
+ proxy: true
15343
+ });
15344
+ }
15345
+ if (injectionResult.flagged && injectionResult.recommendation === "escalate") {
15346
+ this.auditLog.append("l2", `proxy_injection_escalated:${proxyName}`, "system", {
15347
+ server: serverName,
15348
+ tool: toolName,
15349
+ tier,
15350
+ confidence: injectionResult.confidence
15351
+ });
15352
+ }
15353
+ let filteredArgs = args;
15354
+ if (this.options.contextGateFilter) {
15355
+ try {
15356
+ filteredArgs = await this.options.contextGateFilter(proxyName, args);
15357
+ } catch {
15358
+ }
15359
+ }
15360
+ if (this.options.governor) {
15361
+ const govResult = this.options.governor.check(serverName, toolName, filteredArgs);
15362
+ if (!govResult.allowed) {
15363
+ this.auditLog.append("l2", `proxy_governor_blocked:${proxyName}`, "system", {
15364
+ server: serverName,
15365
+ tool: toolName,
15366
+ tier,
15367
+ reason: govResult.reason,
15368
+ latency_ms: Date.now() - start
15369
+ }, "failure");
15370
+ return toolResult({
15371
+ error: "Operation not permitted",
15372
+ proxy: true,
15373
+ governor_reason: govResult.reason
15374
+ });
15375
+ }
15376
+ if (govResult.reason === "duplicate_cached" && govResult.cached_result !== void 0) {
15377
+ this.auditLog.append("l2", `proxy_governor_cached:${proxyName}`, "system", {
15378
+ server: serverName,
15379
+ tool: toolName,
15380
+ tier,
15381
+ cached: true,
15382
+ latency_ms: Date.now() - start
15383
+ });
15384
+ return toolResult(govResult.cached_result ?? {});
15385
+ }
15386
+ }
15387
+ const result = await this.callWithTimeout(
15388
+ serverName,
15389
+ toolName,
15390
+ filteredArgs,
15391
+ UPSTREAM_CALL_TIMEOUT_MS
15392
+ );
15393
+ const latencyMs = Date.now() - start;
15394
+ if (this.options.governor) {
15395
+ this.options.governor.recordResult(serverName, toolName, filteredArgs, result);
15396
+ }
15397
+ this.auditLog.append("l2", `proxy_call:${proxyName}`, "system", {
15398
+ server: serverName,
15399
+ tool: toolName,
15400
+ tier,
15401
+ decision: "allowed",
15402
+ latency_ms: latencyMs
15403
+ });
15404
+ return this.normalizeResponse(result);
15405
+ } catch (err) {
15406
+ const latencyMs = Date.now() - start;
15407
+ const rawErrorMessage = err instanceof Error ? err.message : "Unknown upstream error";
15408
+ const sanitizeError = (msg) => {
15409
+ let safe = msg.substring(0, 200);
15410
+ safe = safe.replace(/\/[^\s]+/g, "[path-redacted]");
15411
+ safe = safe.replace(/(?:mongodb|postgres|mysql|redis):\/\/[^\s]+/g, "[connection-redacted]");
15412
+ return safe;
15413
+ };
15414
+ const errorMessage = sanitizeError(rawErrorMessage);
15415
+ this.auditLog.append("l2", `proxy_call:${proxyName}`, "system", {
15416
+ server: serverName,
15417
+ tool: toolName,
15418
+ tier,
15419
+ decision: "error",
15420
+ error: errorMessage,
15421
+ latency_ms: latencyMs
15422
+ }, "failure");
15423
+ return {
15424
+ content: [{
15425
+ type: "text",
15426
+ text: JSON.stringify({
15427
+ error: errorMessage,
15428
+ proxy: true,
15429
+ server: serverName,
15430
+ tool: toolName
15431
+ })
15432
+ }]
15433
+ };
15434
+ }
15435
+ };
15436
+ }
15437
+ /**
15438
+ * Call an upstream tool with a timeout.
15439
+ */
15440
+ async callWithTimeout(serverName, toolName, args, timeoutMs) {
15441
+ return new Promise((resolve, reject) => {
15442
+ const timer = setTimeout(() => {
15443
+ reject(new Error(`Upstream tool call timed out after ${timeoutMs}ms`));
15444
+ }, timeoutMs);
15445
+ this.clientManager.callTool(serverName, toolName, args).then((result) => {
15446
+ clearTimeout(timer);
15447
+ resolve(result);
15448
+ }).catch((err) => {
15449
+ clearTimeout(timer);
15450
+ reject(err);
15451
+ });
15452
+ });
15453
+ }
15454
+ /**
15455
+ * Normalize an upstream response to the standard Sanctuary response format.
15456
+ */
15457
+ normalizeResponse(result) {
15458
+ const MAX_RESPONSE_SIZE = 1e6;
15459
+ const MAX_TEXT_BLOCK_SIZE = 1e5;
15460
+ const responseStr = JSON.stringify(result);
15461
+ if (responseStr.length > MAX_RESPONSE_SIZE) {
15462
+ return toolResult({
15463
+ error: "upstream_response_too_large",
15464
+ max_bytes: MAX_RESPONSE_SIZE
15465
+ });
15466
+ }
15467
+ if (!result.content || !Array.isArray(result.content)) {
15468
+ return toolResult({ upstream_response: result });
15469
+ }
15470
+ const textContent = result.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => {
15471
+ const text = c.text;
15472
+ if (text.length > MAX_TEXT_BLOCK_SIZE) {
15473
+ return {
15474
+ type: "text",
15475
+ text: text.substring(0, MAX_TEXT_BLOCK_SIZE) + "\n[response truncated]"
15476
+ };
15477
+ }
15478
+ return { type: "text", text };
15479
+ });
15480
+ if (textContent.length > 0) {
15481
+ return { content: textContent };
15482
+ }
15483
+ return toolResult({ upstream_response: result.content });
15484
+ }
15485
+ };
15486
+ function strToBytes(s) {
15487
+ return new TextEncoder().encode(s);
15488
+ }
15489
+ function bytesToHex(bytes) {
15490
+ let hex = "";
15491
+ for (let i = 0; i < bytes.length; i++) {
15492
+ hex += bytes[i].toString(16).padStart(2, "0");
15493
+ }
15494
+ return hex;
15495
+ }
15496
+ function sha256Hex(input) {
15497
+ return bytesToHex(sha256.sha256(strToBytes(input)));
15498
+ }
15499
+ var DEFAULT_CONFIG = {
15500
+ volume_limit: 200,
15501
+ volume_window_ms: 6e5,
15502
+ // 10 minutes
15503
+ rate_limit: 20,
15504
+ rate_window_ms: 6e4,
15505
+ // 1 minute
15506
+ duplicate_ttl_ms: 6e4,
15507
+ // 1 minute
15508
+ lifetime_limit: 1e3
15509
+ };
15510
+ var CallGovernor = class {
15511
+ config;
15512
+ /** Sliding window of all call timestamps for volume tracking */
15513
+ volumeWindow = [];
15514
+ /** Per-tool sliding window of call timestamps for rate tracking */
15515
+ rateWindows = /* @__PURE__ */ new Map();
15516
+ /** Duplicate cache: SHA-256(server+tool+args) -> cached result + expiry */
15517
+ duplicateCache = /* @__PURE__ */ new Map();
15518
+ /** Total calls this session */
15519
+ lifetimeCount = 0;
15520
+ /** Hard stop flag — set when lifetime limit is reached */
15521
+ hardStopped = false;
15522
+ constructor(config) {
15523
+ this.config = { ...DEFAULT_CONFIG, ...config };
15524
+ }
15525
+ /**
15526
+ * Check if a call is allowed and apply governance.
15527
+ *
15528
+ * Evaluation order:
15529
+ * 1. Lifetime limit (hard stop — not recoverable without reset)
15530
+ * 2. Volume limit (sliding window)
15531
+ * 3. Rate limit per tool (escalates to Tier 2)
15532
+ * 4. Duplicate detection (returns cached result)
15533
+ */
15534
+ check(serverName, toolName, args) {
15535
+ const now = Date.now();
15536
+ const effectiveConfig = this.getEffectiveConfig(serverName);
15537
+ if (this.hardStopped) {
15538
+ return {
15539
+ allowed: false,
15540
+ reason: "lifetime_exceeded"
15541
+ };
15542
+ }
15543
+ if (this.lifetimeCount >= effectiveConfig.lifetime_limit) {
15544
+ this.hardStopped = true;
15545
+ return {
15546
+ allowed: false,
15547
+ reason: "lifetime_exceeded"
15548
+ };
15549
+ }
15550
+ this.pruneVolumeWindow(now, effectiveConfig.volume_window_ms);
15551
+ if (this.volumeWindow.length >= effectiveConfig.volume_limit) {
15552
+ return {
15553
+ allowed: false,
15554
+ reason: "volume_exceeded"
15555
+ };
15556
+ }
15557
+ const toolKey = `${serverName}::${toolName}`;
15558
+ this.pruneRateWindow(toolKey, now, effectiveConfig.rate_window_ms);
15559
+ const rateWindow = this.rateWindows.get(toolKey);
15560
+ const currentRate = rateWindow ? rateWindow.length : 0;
15561
+ if (currentRate >= effectiveConfig.rate_limit) {
15562
+ return {
15563
+ allowed: false,
15564
+ reason: "rate_exceeded",
15565
+ escalate: true
15566
+ };
15567
+ }
15568
+ const callHash = this.computeCallHash(serverName, toolName, args);
15569
+ this.pruneDuplicateCache(now);
15570
+ const cached = this.duplicateCache.get(callHash);
15571
+ if (cached && cached.expires_at > now) {
15572
+ return {
15573
+ allowed: true,
15574
+ reason: "duplicate_cached",
15575
+ cached_result: cached.result
15576
+ };
15577
+ }
15578
+ this.volumeWindow.push(now);
15579
+ if (!this.rateWindows.has(toolKey)) {
15580
+ this.rateWindows.set(toolKey, []);
15581
+ }
15582
+ this.rateWindows.get(toolKey).push(now);
15583
+ this.lifetimeCount++;
15584
+ return { allowed: true };
15585
+ }
15586
+ /**
15587
+ * Record a successful call result for duplicate caching.
15588
+ */
15589
+ recordResult(serverName, toolName, args, result) {
15590
+ const callHash = this.computeCallHash(serverName, toolName, args);
15591
+ const effectiveConfig = this.getEffectiveConfig(serverName);
15592
+ this.duplicateCache.set(callHash, {
15593
+ result,
15594
+ expires_at: Date.now() + effectiveConfig.duplicate_ttl_ms
15595
+ });
15596
+ }
15597
+ /**
15598
+ * Get current governor status for dashboard display.
15599
+ */
15600
+ getStatus() {
15601
+ const now = Date.now();
15602
+ this.pruneVolumeWindow(now, this.config.volume_window_ms);
15603
+ this.pruneDuplicateCache(now);
15604
+ const rateByTool = {};
15605
+ for (const [toolKey, timestamps] of this.rateWindows.entries()) {
15606
+ const cutoff = now - this.config.rate_window_ms;
15607
+ const activeCount = timestamps.filter((t) => t >= cutoff).length;
15608
+ if (activeCount > 0) {
15609
+ rateByTool[toolKey] = activeCount;
15610
+ }
15611
+ }
15612
+ return {
15613
+ volume_current: this.volumeWindow.length,
15614
+ volume_limit: this.config.volume_limit,
15615
+ lifetime_current: this.lifetimeCount,
15616
+ lifetime_limit: this.config.lifetime_limit,
15617
+ rate_by_tool: rateByTool,
15618
+ duplicate_cache_size: this.duplicateCache.size,
15619
+ hard_stopped: this.hardStopped
15620
+ };
15621
+ }
15622
+ /**
15623
+ * Reset all counters (Tier 1 — requires approval).
15624
+ * Clears volume window, rate windows, duplicate cache,
15625
+ * lifetime counter, and hard stop flag.
15626
+ */
15627
+ reset() {
15628
+ this.volumeWindow = [];
15629
+ this.rateWindows.clear();
15630
+ this.duplicateCache.clear();
15631
+ this.lifetimeCount = 0;
15632
+ this.hardStopped = false;
15633
+ }
15634
+ /**
15635
+ * Get the effective config for a given server, merging per-server overrides.
15636
+ */
15637
+ getEffectiveConfig(serverName) {
15638
+ const override = this.config.per_server_overrides?.[serverName];
15639
+ if (!override) return this.config;
15640
+ return { ...this.config, ...override };
15641
+ }
15642
+ /**
15643
+ * Compute a SHA-256 hash of server + tool + canonical args.
15644
+ * Used for duplicate detection.
15645
+ */
15646
+ computeCallHash(serverName, toolName, args) {
15647
+ const stableArgs = this.stableStringify(args);
15648
+ const input = `${serverName}\0${toolName}\0${stableArgs}`;
15649
+ return sha256Hex(input);
15650
+ }
15651
+ /**
15652
+ * Deterministic JSON serialization with sorted keys.
15653
+ */
15654
+ stableStringify(obj) {
15655
+ if (obj === null || obj === void 0) return "null";
15656
+ if (typeof obj !== "object") return JSON.stringify(obj);
15657
+ if (Array.isArray(obj)) {
15658
+ return "[" + obj.map((item) => this.stableStringify(item)).join(",") + "]";
15659
+ }
15660
+ const sortedKeys = Object.keys(obj).sort();
15661
+ const pairs = sortedKeys.map(
15662
+ (key) => JSON.stringify(key) + ":" + this.stableStringify(obj[key])
15663
+ );
15664
+ return "{" + pairs.join(",") + "}";
15665
+ }
15666
+ /**
15667
+ * Prune volume window entries older than the window size.
15668
+ * Uses shift() from the front — timestamps are appended in order.
15669
+ */
15670
+ pruneVolumeWindow(now, windowMs) {
15671
+ const cutoff = now - windowMs;
15672
+ while (this.volumeWindow.length > 0 && this.volumeWindow[0] < cutoff) {
15673
+ this.volumeWindow.shift();
15674
+ }
15675
+ }
15676
+ /**
15677
+ * Prune a per-tool rate window.
15678
+ */
15679
+ pruneRateWindow(toolKey, now, windowMs) {
15680
+ const window = this.rateWindows.get(toolKey);
15681
+ if (!window) return;
15682
+ const cutoff = now - windowMs;
15683
+ while (window.length > 0 && window[0] < cutoff) {
15684
+ window.shift();
15685
+ }
15686
+ if (window.length === 0) {
15687
+ this.rateWindows.delete(toolKey);
15688
+ }
15689
+ }
15690
+ /**
15691
+ * Prune expired entries from the duplicate cache.
15692
+ * Amortized O(1) — only prunes when cache exceeds a size threshold.
15693
+ */
15694
+ pruneDuplicateCache(now) {
15695
+ if (this.duplicateCache.size < 100) return;
15696
+ for (const [key, entry] of this.duplicateCache) {
15697
+ if (entry.expires_at <= now) {
15698
+ this.duplicateCache.delete(key);
15699
+ }
15700
+ }
15701
+ }
15702
+ };
15703
+
15704
+ // src/l2-operational/governor-tools.ts
15705
+ function createGovernorTools(governor, auditLog) {
15706
+ const tools = [
15707
+ // ── Governor Status ─────────────────────────────────────────────
15708
+ {
15709
+ name: "sanctuary/governor_status",
15710
+ description: "View the current Call Governor status including volume counters, per-tool rate counts, duplicate cache size, and lifetime counter. Use this to monitor tool call consumption, detect potential loops, and check how close you are to governance limits. The governor protects against runaway tool calls by enforcing volume limits, rate limits, duplicate detection, and a session lifetime cap.",
15711
+ inputSchema: {
15712
+ type: "object",
15713
+ properties: {}
15714
+ },
15715
+ handler: async () => {
15716
+ const status = governor.getStatus();
15717
+ auditLog.append("l2", "governor_status", "system", {
15718
+ volume_current: status.volume_current,
15719
+ volume_limit: status.volume_limit,
15720
+ lifetime_current: status.lifetime_current,
15721
+ lifetime_limit: status.lifetime_limit,
15722
+ duplicate_cache_size: status.duplicate_cache_size,
15723
+ hard_stopped: status.hard_stopped
15724
+ });
15725
+ const volumePercent = status.volume_limit > 0 ? Math.round(status.volume_current / status.volume_limit * 100) : 0;
15726
+ const lifetimePercent = status.lifetime_limit > 0 ? Math.round(status.lifetime_current / status.lifetime_limit * 100) : 0;
15727
+ const toolRateEntries = Object.entries(status.rate_by_tool);
15728
+ const highRateTools = toolRateEntries.filter(([, count]) => count > 10).map(([tool, count]) => `${tool} (${count} calls/min)`);
15729
+ return toolResult({
15730
+ governor_status: status,
15731
+ summary: {
15732
+ volume_usage: `${status.volume_current}/${status.volume_limit} (${volumePercent}%)`,
15733
+ lifetime_usage: `${status.lifetime_current}/${status.lifetime_limit} (${lifetimePercent}%)`,
15734
+ active_tools: toolRateEntries.length,
15735
+ cached_duplicates: status.duplicate_cache_size
15736
+ },
15737
+ warnings: [
15738
+ ...status.hard_stopped ? ["HARD STOP: Lifetime limit reached. Use sanctuary/governor_reset to continue."] : [],
15739
+ ...volumePercent > 80 ? [`Volume usage at ${volumePercent}% \u2014 approaching limit.`] : [],
15740
+ ...lifetimePercent > 80 ? [`Lifetime usage at ${lifetimePercent}% \u2014 approaching hard stop.`] : [],
15741
+ ...highRateTools.length > 0 ? [`High-rate tools detected: ${highRateTools.join(", ")}`] : []
15742
+ ],
15743
+ guidance: status.hard_stopped ? "The governor has stopped all proxied tool calls because the session lifetime limit was reached. Use sanctuary/governor_reset (requires human approval) to reset counters and resume." : "The governor is monitoring all proxied tool calls. Counters reset automatically on server restart."
15744
+ });
15745
+ }
15746
+ },
15747
+ // ── Governor Reset ──────────────────────────────────────────────
15748
+ {
15749
+ name: "sanctuary/governor_reset",
15750
+ description: "Reset all Call Governor counters: volume window, per-tool rate windows, duplicate cache, and lifetime counter. This clears the hard stop if the lifetime limit was reached. This is a Tier 1 operation \u2014 requires human approval because it removes all runtime governance state and could allow previously blocked behavior to resume.",
15751
+ inputSchema: {
15752
+ type: "object",
15753
+ properties: {
15754
+ confirm: {
15755
+ type: "boolean",
15756
+ description: "Must be true to confirm the reset. This clears all governor state including the lifetime counter."
15757
+ }
15758
+ },
15759
+ required: ["confirm"]
15760
+ },
15761
+ handler: async (args) => {
15762
+ const confirm = args.confirm;
15763
+ if (!confirm) {
15764
+ return toolResult({
15765
+ error: "confirmation_required",
15766
+ message: "Set confirm: true to reset all governor counters. This will clear volume limits, rate tracking, duplicate cache, and the lifetime counter."
15767
+ });
15768
+ }
15769
+ const preResetStatus = governor.getStatus();
15770
+ governor.reset();
15771
+ const postResetStatus = governor.getStatus();
15772
+ auditLog.append("l2", "governor_reset", "system", {
15773
+ pre_reset: {
15774
+ volume_current: preResetStatus.volume_current,
15775
+ lifetime_current: preResetStatus.lifetime_current,
15776
+ duplicate_cache_size: preResetStatus.duplicate_cache_size,
15777
+ hard_stopped: preResetStatus.hard_stopped
15778
+ },
15779
+ post_reset: {
15780
+ volume_current: postResetStatus.volume_current,
15781
+ lifetime_current: postResetStatus.lifetime_current,
15782
+ duplicate_cache_size: postResetStatus.duplicate_cache_size,
15783
+ hard_stopped: postResetStatus.hard_stopped
15784
+ }
15785
+ });
15786
+ return toolResult({
15787
+ reset: true,
15788
+ previous_state: {
15789
+ lifetime_calls: preResetStatus.lifetime_current,
15790
+ was_hard_stopped: preResetStatus.hard_stopped,
15791
+ volume_at_reset: preResetStatus.volume_current,
15792
+ cached_duplicates_cleared: preResetStatus.duplicate_cache_size
15793
+ },
15794
+ current_state: postResetStatus,
15795
+ message: "All governor counters have been reset. " + (preResetStatus.hard_stopped ? "Hard stop has been cleared \u2014 proxied tool calls will resume." : "Volume, rate, duplicate, and lifetime counters are now at zero.")
15796
+ });
15797
+ }
15798
+ }
15799
+ ];
15800
+ return { tools };
15801
+ }
15802
+
15803
+ // src/index.ts
15804
+ init_random();
15805
+ init_encoding();
15806
+
15807
+ // src/l2-operational/model-provenance.ts
15808
+ var InMemoryModelProvenanceStore = class {
15809
+ models = /* @__PURE__ */ new Map();
15810
+ primaryModelId = null;
15811
+ declare(provenance) {
15812
+ if (!provenance.model_id) {
15813
+ throw new Error("ModelProvenance requires a model_id");
15814
+ }
15815
+ if (!provenance.model_name) {
15816
+ throw new Error("ModelProvenance requires a model_name");
13358
15817
  }
13359
15818
  if (!provenance.provider) {
13360
15819
  throw new Error("ModelProvenance requires a provider");
@@ -13961,18 +16420,89 @@ async function createSanctuaryServer(options) {
13961
16420
  ...dashboardTools,
13962
16421
  manifestTool
13963
16422
  ];
16423
+ let clientManager;
16424
+ let proxyRouter;
16425
+ const governor = new CallGovernor();
16426
+ const { tools: governorTools } = createGovernorTools(governor, auditLog);
16427
+ allTools.push(...governorTools);
16428
+ const profile = profileStore.get();
16429
+ if (profile.upstream_servers && profile.upstream_servers.length > 0) {
16430
+ const enabledServers = profile.upstream_servers.filter((s) => s.enabled);
16431
+ if (enabledServers.length > 0) {
16432
+ clientManager = new ClientManager({
16433
+ onStateChange: (serverName, state, toolCount, error) => {
16434
+ if (dashboard) {
16435
+ dashboard.broadcastSSE("proxy-server-status", {
16436
+ server: serverName,
16437
+ state,
16438
+ tool_count: toolCount,
16439
+ error,
16440
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
16441
+ });
16442
+ }
16443
+ auditLog.append("l2", `proxy_server_${state}`, "system", {
16444
+ server: serverName,
16445
+ tool_count: toolCount,
16446
+ error
16447
+ });
16448
+ }
16449
+ });
16450
+ proxyRouter = new ProxyRouter(
16451
+ clientManager,
16452
+ injectionDetector,
16453
+ auditLog,
16454
+ {
16455
+ contextGateFilter: async (_toolName, args) => {
16456
+ const activeProfile = profileStore.get();
16457
+ if (activeProfile.features.context_gating.enabled) {
16458
+ return args;
16459
+ }
16460
+ return args;
16461
+ },
16462
+ governor
16463
+ }
16464
+ );
16465
+ clientManager.configure(enabledServers).catch((err) => {
16466
+ console.error(`[Sanctuary] Failed to configure upstream servers: ${err instanceof Error ? err.message : "unknown error"}`);
16467
+ });
16468
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
16469
+ const proxiedTools = proxyRouter.getProxiedTools();
16470
+ if (proxiedTools.length > 0) {
16471
+ allTools.push(...proxiedTools);
16472
+ }
16473
+ if (dashboard) {
16474
+ dashboard.setDependencies({
16475
+ policy,
16476
+ baseline,
16477
+ auditLog,
16478
+ clientManager
16479
+ });
16480
+ }
16481
+ }
16482
+ }
13964
16483
  allTools = allTools.map((tool) => ({
13965
16484
  ...tool,
13966
16485
  handler: contextGateEnforcer.wrapHandler(tool.name, tool.handler)
13967
16486
  }));
16487
+ if (proxyRouter) {
16488
+ gate.setProxyTierResolver((toolName) => {
16489
+ const parsed = ProxyRouter.parseProxyToolName(toolName);
16490
+ if (!parsed) return null;
16491
+ return proxyRouter.getTierForTool(parsed.serverName, parsed.toolName);
16492
+ });
16493
+ }
13968
16494
  const server = createServer(allTools, { gate });
13969
16495
  await saveConfig(config);
13970
- const saveBaseline = () => {
16496
+ const cleanup = () => {
13971
16497
  baseline.save().catch(() => {
13972
16498
  });
16499
+ if (clientManager) {
16500
+ clientManager.shutdown().catch(() => {
16501
+ });
16502
+ }
13973
16503
  };
13974
- process.on("SIGINT", saveBaseline);
13975
- process.on("SIGTERM", saveBaseline);
16504
+ process.on("SIGINT", cleanup);
16505
+ process.on("SIGTERM", cleanup);
13976
16506
  if (recoveryKey) {
13977
16507
  console.error(
13978
16508
  `\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
@@ -13995,6 +16525,7 @@ exports.AutoApproveChannel = AutoApproveChannel;
13995
16525
  exports.BaselineTracker = BaselineTracker;
13996
16526
  exports.CONTEXT_GATE_TEMPLATES = TEMPLATES;
13997
16527
  exports.CallbackApprovalChannel = CallbackApprovalChannel;
16528
+ exports.ClientManager = ClientManager;
13998
16529
  exports.CommitmentStore = CommitmentStore;
13999
16530
  exports.ContextGateEnforcer = ContextGateEnforcer;
14000
16531
  exports.ContextGatePolicyStore = ContextGatePolicyStore;
@@ -14006,6 +16537,7 @@ exports.InjectionDetector = InjectionDetector;
14006
16537
  exports.MODEL_PRESETS = MODEL_PRESETS;
14007
16538
  exports.MemoryStorage = MemoryStorage;
14008
16539
  exports.PolicyStore = PolicyStore;
16540
+ exports.ProxyRouter = ProxyRouter;
14009
16541
  exports.ReputationStore = ReputationStore;
14010
16542
  exports.SovereigntyProfileStore = SovereigntyProfileStore;
14011
16543
  exports.StateStore = StateStore;