thumbgate 1.38.0 → 1.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/bolt-forge-opt-in-not-clone/SKILL.md +72 -0
- package/.agents/skills/decisive-step-evaluator/SKILL.md +47 -0
- package/.agents/skills/fiddler-control-plane-honesty/SKILL.md +61 -0
- package/.agents/skills/harness-evolution-ceiling/SKILL.md +52 -0
- package/.agents/skills/omp-coordination-honesty-not-clone/SKILL.md +94 -0
- package/.agents/skills/saas-moat-honesty-not-clone/SKILL.md +22 -0
- package/.agents/skills/siren-mcp-governance/SKILL.md +50 -0
- package/.agents/skills/vs-coverage-gap-not-clone/SKILL.md +69 -0
- package/.agents/skills/wisdom-context-artifact-not-clone/SKILL.md +67 -0
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/adapters/claude/.mcp.json +2 -2
- package/adapters/forge/forge.yaml +3 -3
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/hotdata/hotdata-vector-store.js +575 -0
- package/adapters/mcp/server-stdio.js +1 -1
- package/adapters/opencode/opencode.json +1 -1
- package/adapters/strands/strands-box-diode.js +344 -0
- package/adapters/strands/strands-decider-adapter.js +445 -0
- package/bin/cli.js +472 -21
- package/config/gate-templates.json +37 -0
- package/config/gates/default.json +13 -0
- package/config/schemas/task-outcome-receipt.schema.json +12 -0
- package/package.json +102 -18
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +119 -0
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +141 -0
- package/public/connectors.html +329 -0
- package/public/enterprise-governance.html +311 -0
- package/public/gaming-playbook.html +732 -0
- package/public/index.html +77 -51
- package/public/install.html +7 -7
- package/public/learn.html +14 -0
- package/public/numbers.html +2 -2
- package/public/operator-framework.html +385 -0
- package/public/pricing.html +14 -10
- package/scripts/activesaddler-curriculum-doctor.js +357 -0
- package/scripts/agent-context-artifact.js +325 -0
- package/scripts/agent-egress-policy.js +2 -2
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-outcome-eval.js +1 -1
- package/scripts/agent-reliability-client.js +148 -0
- package/scripts/apple-minions-idle-compute-steal.js +428 -0
- package/scripts/billing.js +0 -1
- package/scripts/cli-demo.js +505 -1
- package/scripts/cli-schema.js +36 -0
- package/scripts/colab-compute-honesty.js +93 -0
- package/scripts/corporate-email-isolation-diode.js +299 -0
- package/scripts/coverage-gap.js +396 -0
- package/scripts/dashboard-chat.js +3 -3
- package/scripts/dashboard.js +2 -2
- package/scripts/decisive-step-doctor.js +256 -0
- package/scripts/decisive-step-evaluator.js +390 -0
- package/scripts/entitlement.js +18 -7
- package/scripts/feedback-loop.js +26 -3
- package/scripts/fiddler-control-plane-honesty.js +303 -0
- package/scripts/financial-control-plane.js +10 -2
- package/scripts/gates-engine.js +3 -1
- package/scripts/github-license-compliance-diode.js +378 -0
- package/scripts/harness-ceiling-doctor.js +326 -0
- package/scripts/hf-papers.js +1 -1
- package/scripts/human-escalation.js +7 -1
- package/scripts/hybrid-feedback-context.js +53 -7
- package/scripts/lesson-graph.js +785 -0
- package/scripts/lesson-inference.js +1 -1
- package/scripts/lesson-retrieval.js +26 -18
- package/scripts/license.js +122 -21
- package/scripts/llm-behavior-monitor.js +1 -1
- package/scripts/llm-obs-honesty.js +52 -0
- package/scripts/local-model-profile.js +11 -7
- package/scripts/mailer/resend-mailer.js +6 -3
- package/scripts/mcp-transport-strategy.js +1 -1
- package/scripts/migrate-lesson-graph.js +442 -0
- package/scripts/model-distress-doctor.js +168 -0
- package/scripts/multi-harness-invariants.js +305 -0
- package/scripts/omp-coordination-honesty.js +488 -0
- package/scripts/pro-local-dashboard.js +20 -3
- package/scripts/prompt-eval.js +1 -1
- package/scripts/prove-herdr-adapter.js +367 -3
- package/scripts/rag-embedding-identity.js +1 -1
- package/scripts/rrsi-regularizer.js +86 -0
- package/scripts/saas-moat-honesty.js +443 -0
- package/scripts/secret-redaction.js +58 -0
- package/scripts/session-export-gate.js +368 -0
- package/scripts/siren-mcp-governance.js +539 -0
- package/scripts/strands-box-doctor.js +130 -0
- package/scripts/stripe-revenue-catalog-audit.js +12 -0
- package/scripts/stripe-revenue-catalog.js +40 -0
- package/scripts/switchyard-router.js +153 -0
- package/scripts/task-outcomes.js +148 -3
- package/scripts/thumbgate-board-loop.js +4 -2
- package/scripts/thumbgate-daily-discoveries-publish.js +86 -38
- package/scripts/triage-savings-calculator.js +181 -0
- package/scripts/vector-store.js +41 -2
- package/scripts/vulnerability-pre-action-diode.js +319 -0
- package/scripts/windbg-evidence-diagnostics.js +241 -0
- package/scripts/workflow-intake-queue.js +1 -1
- package/scripts/workspace-agent-routines.js +534 -6
- package/server.json +2 -2
- package/skills/siren-mcp-governance/SKILL.md +50 -0
- package/src/api/server.js +158 -1
- package/src/mcp-writeguard.js +1 -1
- package/src/session-interactivity.js +284 -0
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* adapters/hotdata/hotdata-vector-store.js
|
|
6
|
+
*
|
|
7
|
+
* Drop-in Hotdata DB replacement for LanceDB in ThumbGate (`scripts/vector-store.js`).
|
|
8
|
+
*
|
|
9
|
+
* Built against the official Hotdata v1 API & HotSQL specification (https://www.hotdata.dev/llms.txt):
|
|
10
|
+
* - Addressing: `Authorization: Bearer <HOTDATA_API_KEY>`, `X-Workspace-Id: <work...>`, `X-Database-Id: <dbid...>`
|
|
11
|
+
* - Instant Database Provisioning: `POST /v1/databases`
|
|
12
|
+
* - Atomic Table Publishing: `POST /v1/databases/{db_id}/schemas/main/tables/{table}/loads`
|
|
13
|
+
* (`mode: "replace"` on first load, `mode: "upsert"` with `key: ["id"]` on incremental updates,
|
|
14
|
+
* with automatic fallback from inline CSV to `/v1/uploads` presigned PUT on 413 INLINE_DATA_TOO_LARGE)
|
|
15
|
+
* - Vector Indexing: `POST /v1/connections/{conn_id}/tables/main/{table}/indexes`
|
|
16
|
+
* (`index_type: "vector"`, `algorithm: "hnsw"`, `metric: "cosine"`, `vector_precision: "float32"`)
|
|
17
|
+
* - Nearest-Neighbor HotSQL Retrieval: `POST /v1/query` (`dialect: "hotsql"`)
|
|
18
|
+
* `SELECT id, text, signal, tags, timestamp, context, _distance
|
|
19
|
+
* FROM vector_search('default.main.thumbgate_memories', 'vector', '[...]', 50)
|
|
20
|
+
* ORDER BY _distance ASC LIMIT <k>`
|
|
21
|
+
* - Pre-Action Execution Diode (<0.1ms local CPU):
|
|
22
|
+
* Interdicts runaway identical HotSQL retry loops (`gate:hotdata:runaway_query_loop`) and
|
|
23
|
+
* unbounded destructive write-plane mutations (`gate:hotdata:destructive_write_boundary`).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const crypto = require('node:crypto');
|
|
27
|
+
const fs = require('node:fs');
|
|
28
|
+
const path = require('node:path');
|
|
29
|
+
|
|
30
|
+
const DEFAULT_API_BASE = 'https://api.hotdata.dev/v1';
|
|
31
|
+
const DEFAULT_SCHEMA = 'main';
|
|
32
|
+
const DEFAULT_CATALOG = 'default';
|
|
33
|
+
|
|
34
|
+
function getHotdataConfig(overrides = {}, env = process.env) {
|
|
35
|
+
const apiBaseUrl = String(overrides.apiBaseUrl || env.HOTDATA_API_URL || DEFAULT_API_BASE).replace(/\/+$/, '');
|
|
36
|
+
const apiKey = String(overrides.apiKey || env.HOTDATA_API_KEY || '').trim();
|
|
37
|
+
const workspaceId = String(overrides.workspaceId || env.HOTDATA_WORKSPACE_ID || '').trim();
|
|
38
|
+
const databaseId = String(overrides.databaseId || env.HOTDATA_DATABASE_ID || '').trim();
|
|
39
|
+
const connectionId = String(overrides.connectionId || env.HOTDATA_CONNECTION_ID || '').trim();
|
|
40
|
+
const schema = String(overrides.schema || env.HOTDATA_SCHEMA || DEFAULT_SCHEMA).toLowerCase();
|
|
41
|
+
const catalog = String(overrides.catalog || env.HOTDATA_CATALOG || DEFAULT_CATALOG).toLowerCase();
|
|
42
|
+
const vectorAlgorithm = String(overrides.vectorAlgorithm || env.HOTDATA_VECTOR_ALGORITHM || 'hnsw').toLowerCase();
|
|
43
|
+
const vectorPrecision = String(overrides.vectorPrecision || env.HOTDATA_VECTOR_PRECISION || 'float32').toLowerCase();
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
apiBaseUrl,
|
|
47
|
+
apiKey,
|
|
48
|
+
workspaceId,
|
|
49
|
+
databaseId,
|
|
50
|
+
connectionId,
|
|
51
|
+
schema,
|
|
52
|
+
catalog,
|
|
53
|
+
vectorAlgorithm,
|
|
54
|
+
vectorPrecision,
|
|
55
|
+
remoteEnabled: Boolean(apiKey && workspaceId),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Sub-0.1ms PreToolUse Diode for Hotdata + Write-Boundary Workflows.
|
|
61
|
+
*/
|
|
62
|
+
function evaluateHotdataPreToolGate({ toolName, sqlOrCommand, sessionHistory = [], maxIdenticalRetries = 4 } = {}) {
|
|
63
|
+
const startNs = process.hrtime.bigint();
|
|
64
|
+
const raw = String(sqlOrCommand || '').trim();
|
|
65
|
+
const sig = `${toolName || 'hotdata_query'}:${raw}`;
|
|
66
|
+
const priorRetries = sessionHistory.filter(entry => entry === sig).length;
|
|
67
|
+
sessionHistory.push(sig);
|
|
68
|
+
|
|
69
|
+
let decision = 'allow';
|
|
70
|
+
let gateId = 'gate:hotdata:pass';
|
|
71
|
+
let reason = 'Cleared by ThumbGate PreToolUse diode';
|
|
72
|
+
|
|
73
|
+
if (priorRetries >= maxIdenticalRetries) {
|
|
74
|
+
decision = 'block';
|
|
75
|
+
gateId = 'gate:hotdata:runaway_query_loop';
|
|
76
|
+
reason = `Runaway loop interdicted (${priorRetries + 1} identical HotSQL/tool attempts) — prevents ephemeral compute & token burn`;
|
|
77
|
+
} else if (/(?:\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b|\bTRUNCATE\s+TABLE\b|\bDELETE\s+FROM\s+\w+\s*(?:;|$))/i.test(raw)) {
|
|
78
|
+
decision = 'block';
|
|
79
|
+
gateId = 'gate:hotdata:destructive_write_boundary';
|
|
80
|
+
reason = 'Unbounded destructive SQL mutation blocked at Write Boundary before touching system of record';
|
|
81
|
+
} else if (/\b(?:sk-[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|ghp_[a-zA-Z0-9]{36})\b/.test(raw)) {
|
|
82
|
+
decision = 'block';
|
|
83
|
+
gateId = 'gate:hotdata:secret_exfiltration';
|
|
84
|
+
reason = 'Plaintext credential detected in query/tool arguments — blocked before egress';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const latencyMs = Number((Number(process.hrtime.bigint() - startNs) / 1e6).toFixed(3));
|
|
88
|
+
return {
|
|
89
|
+
decision,
|
|
90
|
+
allowed: decision === 'allow',
|
|
91
|
+
gateId,
|
|
92
|
+
latencyMs,
|
|
93
|
+
reason,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Escape a value for inline CSV publishing to `POST /v1/databases/{db}/schemas/{schema}/tables/{table}/loads`.
|
|
99
|
+
*/
|
|
100
|
+
function escapeCsvCell(value) {
|
|
101
|
+
if (value === null || value === undefined) return '';
|
|
102
|
+
const str = typeof value === 'object' ? JSON.stringify(value) : String(value);
|
|
103
|
+
if (/[",\n\r]/.test(str)) {
|
|
104
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
105
|
+
}
|
|
106
|
+
return str;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function serializeRecordsToCsv(records = []) {
|
|
110
|
+
const columns = ['id', 'text', 'vector', 'signal', 'tags', 'timestamp', 'context'];
|
|
111
|
+
const header = columns.join(',');
|
|
112
|
+
const rows = records.map(rec =>
|
|
113
|
+
columns.map(col => {
|
|
114
|
+
const val = col === 'timestamp' && rec[col] ? String(rec[col]).replace(/\.\d+Z$/, 'Z') : rec[col];
|
|
115
|
+
return escapeCsvCell(val);
|
|
116
|
+
}).join(',')
|
|
117
|
+
);
|
|
118
|
+
return [header, ...rows].join('\n');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function cosineDistance(vecA = [], vecB = []) {
|
|
122
|
+
if (!Array.isArray(vecA) || !Array.isArray(vecB) || vecA.length === 0 || vecA.length !== vecB.length) {
|
|
123
|
+
return 1.0;
|
|
124
|
+
}
|
|
125
|
+
let dot = 0;
|
|
126
|
+
let normA = 0;
|
|
127
|
+
let normB = 0;
|
|
128
|
+
for (let i = 0; i < vecA.length; i++) {
|
|
129
|
+
const a = Number(vecA[i]) || 0;
|
|
130
|
+
const b = Number(vecB[i]) || 0;
|
|
131
|
+
dot += a * b;
|
|
132
|
+
normA += a * a;
|
|
133
|
+
normB += b * b;
|
|
134
|
+
}
|
|
135
|
+
const denom = Math.sqrt(normA) * Math.sqrt(normB);
|
|
136
|
+
if (denom === 0) return 1.0;
|
|
137
|
+
return Number((1 - (dot / denom)).toFixed(6));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Build exact HotSQL `vector_search` query for nearest-neighbor retrieval.
|
|
142
|
+
*/
|
|
143
|
+
function buildHotSqlVectorSearchQuery({ catalog = 'default', schema = 'main', table = 'thumbgate_memories', vector = [], limit = 5, whereClause = '' } = {}) {
|
|
144
|
+
const qualified = `${catalog}.${schema}.${table}`.toLowerCase();
|
|
145
|
+
const k = Math.max(1, Number(limit) || 5);
|
|
146
|
+
const candidatePool = Math.max(k * 5, 50);
|
|
147
|
+
const vectorLiteral = JSON.stringify((vector || []).map(Number));
|
|
148
|
+
const filterSql = whereClause ? ` WHERE ${whereClause}` : '';
|
|
149
|
+
|
|
150
|
+
return (
|
|
151
|
+
`SELECT id, text, vector, signal, tags, timestamp, context, _distance ` +
|
|
152
|
+
`FROM vector_search('${qualified}', 'vector', '${vectorLiteral}', ${candidatePool})` +
|
|
153
|
+
`${filterSql} ` +
|
|
154
|
+
`ORDER BY _distance ASC LIMIT ${k}`
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Hotdata Table Handle implementing the LanceDB Table interface (`add`, `countRows`, `search`, `query`, `delete`, `schema`)
|
|
160
|
+
* while executing against Hotdata's `/v1` API (or local Hotdata snapshot store in offline/test mode).
|
|
161
|
+
*/
|
|
162
|
+
class HotdataTable {
|
|
163
|
+
constructor({ tableName, storeDir, config, httpClient }) {
|
|
164
|
+
this.tableName = String(tableName).toLowerCase();
|
|
165
|
+
this.storeDir = storeDir;
|
|
166
|
+
this.config = config;
|
|
167
|
+
this.httpClient = httpClient;
|
|
168
|
+
this.snapshotPath = path.join(storeDir, `${this.tableName}.hotdata.jsonl`);
|
|
169
|
+
this.metaPath = path.join(storeDir, `${this.tableName}.hotdata.meta.json`);
|
|
170
|
+
this.sessionHistory = [];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
_readLocalRows() {
|
|
174
|
+
if (!fs.existsSync(this.snapshotPath)) return [];
|
|
175
|
+
return fs.readFileSync(this.snapshotPath, 'utf8')
|
|
176
|
+
.trim()
|
|
177
|
+
.split('\n')
|
|
178
|
+
.filter(Boolean)
|
|
179
|
+
.map(line => {
|
|
180
|
+
try { return JSON.parse(line); } catch { return null; }
|
|
181
|
+
})
|
|
182
|
+
.filter(Boolean);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
_writeLocalRows(rows, loadMode = 'replace') {
|
|
186
|
+
fs.mkdirSync(this.storeDir, { recursive: true });
|
|
187
|
+
fs.writeFileSync(
|
|
188
|
+
this.snapshotPath,
|
|
189
|
+
rows.map(r => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : ''),
|
|
190
|
+
'utf8'
|
|
191
|
+
);
|
|
192
|
+
const dim = rows[0] && Array.isArray(rows[0].vector) ? rows[0].vector.length : 384;
|
|
193
|
+
fs.writeFileSync(
|
|
194
|
+
this.metaPath,
|
|
195
|
+
JSON.stringify({
|
|
196
|
+
schemaVersion: 'hotdata.table.v1',
|
|
197
|
+
catalog: this.config.catalog,
|
|
198
|
+
schema: this.config.schema,
|
|
199
|
+
table: this.tableName,
|
|
200
|
+
lastLoadMode: loadMode,
|
|
201
|
+
rowCount: rows.length,
|
|
202
|
+
vectorDimension: dim,
|
|
203
|
+
index: {
|
|
204
|
+
index_name: `${this.tableName}_vec_idx`,
|
|
205
|
+
index_type: 'vector',
|
|
206
|
+
algorithm: this.config.vectorAlgorithm,
|
|
207
|
+
metric: 'cosine',
|
|
208
|
+
vector_precision: this.config.vectorPrecision,
|
|
209
|
+
status: 'ready',
|
|
210
|
+
},
|
|
211
|
+
updatedAt: new Date().toISOString(),
|
|
212
|
+
}, null, 2),
|
|
213
|
+
'utf8'
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async add(records = [], options = {}) {
|
|
218
|
+
if (!Array.isArray(records) || records.length === 0) return { loaded: 0 };
|
|
219
|
+
|
|
220
|
+
const existing = this._readLocalRows();
|
|
221
|
+
const isFirstLoad = existing.length === 0;
|
|
222
|
+
const mode = options.mode || (isFirstLoad ? 'replace' : 'upsert');
|
|
223
|
+
|
|
224
|
+
// Enforce PreToolUse diode before publishing
|
|
225
|
+
const gate = evaluateHotdataPreToolGate({
|
|
226
|
+
toolName: 'hotdata_table_load',
|
|
227
|
+
sqlOrCommand: `LOAD ${this.config.catalog}.${this.config.schema}.${this.tableName} MODE ${mode} ROWS ${records.length}`,
|
|
228
|
+
sessionHistory: this.sessionHistory,
|
|
229
|
+
});
|
|
230
|
+
if (!gate.allowed) {
|
|
231
|
+
throw new Error(`ThumbGate PreToolUse Blocked Hotdata Load (${gate.gateId}): ${gate.reason}`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Remote Hotdata API execution when credentials are configured
|
|
235
|
+
if (this.config.remoteEnabled && this.httpClient) {
|
|
236
|
+
const csvData = serializeRecordsToCsv(records);
|
|
237
|
+
const contentHash = crypto.createHash('sha256').update(`${mode}::${csvData}`).digest('hex').slice(0, 32);
|
|
238
|
+
const loadBody = {
|
|
239
|
+
mode,
|
|
240
|
+
...(mode === 'upsert' ? { key: ['id'] } : {}),
|
|
241
|
+
data: csvData,
|
|
242
|
+
format: 'csv',
|
|
243
|
+
idempotency_key: `tg_${contentHash}`,
|
|
244
|
+
};
|
|
245
|
+
await this.httpClient.publishTableLoad({
|
|
246
|
+
table: this.tableName,
|
|
247
|
+
body: loadBody,
|
|
248
|
+
records,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Local Arrow/NDJSON mirror for instant zero-network fallback & deterministic tests
|
|
253
|
+
let merged;
|
|
254
|
+
if (mode === 'replace') {
|
|
255
|
+
merged = records.slice();
|
|
256
|
+
} else if (mode === 'upsert') {
|
|
257
|
+
const byId = new Map(existing.map(r => [r.id, r]));
|
|
258
|
+
for (const rec of records) {
|
|
259
|
+
byId.set(rec.id, rec);
|
|
260
|
+
}
|
|
261
|
+
merged = Array.from(byId.values());
|
|
262
|
+
} else {
|
|
263
|
+
merged = [...existing, ...records];
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
this._writeLocalRows(merged, mode);
|
|
267
|
+
return {
|
|
268
|
+
ok: true,
|
|
269
|
+
mode,
|
|
270
|
+
loaded: records.length,
|
|
271
|
+
totalRows: merged.length,
|
|
272
|
+
gateLatencyMs: gate.latencyMs,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async countRows() {
|
|
277
|
+
return this._readLocalRows().length;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async schema() {
|
|
281
|
+
const rows = this._readLocalRows();
|
|
282
|
+
const dim = rows[0] && Array.isArray(rows[0].vector) ? rows[0].vector.length : 384;
|
|
283
|
+
return {
|
|
284
|
+
fields: [
|
|
285
|
+
{ name: 'id', type: 'utf8' },
|
|
286
|
+
{ name: 'text', type: 'utf8' },
|
|
287
|
+
{ name: 'vector', type: { listSize: dim, valueType: 'float32' } },
|
|
288
|
+
{ name: 'signal', type: 'utf8' },
|
|
289
|
+
{ name: 'tags', type: 'utf8' },
|
|
290
|
+
{ name: 'timestamp', type: 'utf8' },
|
|
291
|
+
{ name: 'context', type: 'utf8' },
|
|
292
|
+
],
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
query() {
|
|
297
|
+
const self = this;
|
|
298
|
+
let _limit = 10;
|
|
299
|
+
return {
|
|
300
|
+
limit(n) {
|
|
301
|
+
_limit = n;
|
|
302
|
+
return this;
|
|
303
|
+
},
|
|
304
|
+
async toArray() {
|
|
305
|
+
return self._readLocalRows().slice(0, _limit);
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
search(queryVector) {
|
|
311
|
+
const self = this;
|
|
312
|
+
let _limit = 5;
|
|
313
|
+
let _where = '';
|
|
314
|
+
return {
|
|
315
|
+
where(clause) {
|
|
316
|
+
_where = clause;
|
|
317
|
+
return this;
|
|
318
|
+
},
|
|
319
|
+
limit(n) {
|
|
320
|
+
_limit = n;
|
|
321
|
+
return this;
|
|
322
|
+
},
|
|
323
|
+
async toArray() {
|
|
324
|
+
const sql = buildHotSqlVectorSearchQuery({
|
|
325
|
+
catalog: self.config.catalog,
|
|
326
|
+
schema: self.config.schema,
|
|
327
|
+
table: self.tableName,
|
|
328
|
+
vector: queryVector,
|
|
329
|
+
limit: _limit,
|
|
330
|
+
whereClause: _where,
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
const gate = evaluateHotdataPreToolGate({
|
|
334
|
+
toolName: 'hotdata_query',
|
|
335
|
+
sqlOrCommand: sql,
|
|
336
|
+
sessionHistory: self.sessionHistory,
|
|
337
|
+
});
|
|
338
|
+
if (!gate.allowed) {
|
|
339
|
+
throw new Error(`ThumbGate PreToolUse Blocked HotSQL Query (${gate.gateId}): ${gate.reason}`);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (self.config.remoteEnabled && self.httpClient) {
|
|
343
|
+
const remoteRows = await self.httpClient.executeHotSql(sql);
|
|
344
|
+
if (Array.isArray(remoteRows)) {
|
|
345
|
+
return remoteRows
|
|
346
|
+
.map(row => {
|
|
347
|
+
let parsedVec = row.vector;
|
|
348
|
+
if (typeof parsedVec === 'string') {
|
|
349
|
+
try { parsedVec = JSON.parse(parsedVec); } catch { parsedVec = null; }
|
|
350
|
+
}
|
|
351
|
+
const dist = Array.isArray(parsedVec) && parsedVec.length === queryVector.length
|
|
352
|
+
? cosineDistance(queryVector, parsedVec)
|
|
353
|
+
: Number(row._distance ?? 1.0);
|
|
354
|
+
return { ...row, ...(Array.isArray(parsedVec) ? { vector: parsedVec } : {}), _distance: dist };
|
|
355
|
+
})
|
|
356
|
+
.sort((a, b) => a._distance - b._distance)
|
|
357
|
+
.slice(0, _limit);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const rows = self._readLocalRows();
|
|
362
|
+
return rows
|
|
363
|
+
.map(row => ({
|
|
364
|
+
...row,
|
|
365
|
+
_distance: cosineDistance(queryVector, row.vector),
|
|
366
|
+
}))
|
|
367
|
+
.sort((a, b) => a._distance - b._distance)
|
|
368
|
+
.slice(0, _limit);
|
|
369
|
+
},
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async delete() {
|
|
374
|
+
this._writeLocalRows([], 'replace');
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Hotdata HTTP v1 API Client (`https://api.hotdata.dev/v1`).
|
|
380
|
+
*/
|
|
381
|
+
class HotdataHttpClient {
|
|
382
|
+
constructor(config, fetchImpl = globalThis.fetch) {
|
|
383
|
+
this.config = config;
|
|
384
|
+
this.fetchImpl = fetchImpl;
|
|
385
|
+
this.requestsLog = [];
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
_headers(extra = {}) {
|
|
389
|
+
return {
|
|
390
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
391
|
+
'X-Workspace-Id': this.config.workspaceId,
|
|
392
|
+
...(this.config.databaseId ? { 'X-Database-Id': this.config.databaseId } : {}),
|
|
393
|
+
'Content-Type': 'application/json',
|
|
394
|
+
...extra,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async publishTableLoad({ table, body, records }) {
|
|
399
|
+
const url = `${this.config.apiBaseUrl}/databases/${this.config.databaseId}/schemas/${this.config.schema}/tables/${table}/loads`;
|
|
400
|
+
this.requestsLog.push({ method: 'POST', url, mode: body.mode, rowCount: records.length });
|
|
401
|
+
if (!this.fetchImpl) return { status: 200 };
|
|
402
|
+
|
|
403
|
+
const res = await this.fetchImpl(url, {
|
|
404
|
+
method: 'POST',
|
|
405
|
+
headers: this._headers(),
|
|
406
|
+
body: JSON.stringify(body),
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
// Per Push Data spec: 413 INLINE_DATA_TOO_LARGE branches to /v1/uploads presigned PUT
|
|
410
|
+
if (res.status === 413) {
|
|
411
|
+
return this.uploadViaPresignedSession({ table, body, records });
|
|
412
|
+
}
|
|
413
|
+
if (!res.ok) {
|
|
414
|
+
const errText = await res.text().catch(() => '');
|
|
415
|
+
throw new Error(`Hotdata load failed (${res.status}): ${errText.slice(0, 200)}`);
|
|
416
|
+
}
|
|
417
|
+
return res.json().catch(() => ({ ok: true }));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async uploadViaPresignedSession({ table, body, records }) {
|
|
421
|
+
const ndjson = records.map(r => JSON.stringify(r)).join('\n');
|
|
422
|
+
const byteLength = Buffer.byteLength(ndjson, 'utf8');
|
|
423
|
+
|
|
424
|
+
// Step 1: Open upload session
|
|
425
|
+
const sessionUrl = `${this.config.apiBaseUrl}/uploads`;
|
|
426
|
+
this.requestsLog.push({ method: 'POST', url: sessionUrl, declared_size_bytes: byteLength });
|
|
427
|
+
const sessionRes = await this.fetchImpl(sessionUrl, {
|
|
428
|
+
method: 'POST',
|
|
429
|
+
headers: this._headers(),
|
|
430
|
+
body: JSON.stringify({
|
|
431
|
+
filename: `${table}.ndjson`,
|
|
432
|
+
declared_size_bytes: byteLength,
|
|
433
|
+
content_type: 'application/x-ndjson',
|
|
434
|
+
}),
|
|
435
|
+
});
|
|
436
|
+
const session = await sessionRes.json();
|
|
437
|
+
|
|
438
|
+
// Step 2: PUT bytes to presigned URL
|
|
439
|
+
const putUrl = session.url || (session.part_urls && session.part_urls[0]);
|
|
440
|
+
if (putUrl) {
|
|
441
|
+
await this.fetchImpl(putUrl, {
|
|
442
|
+
method: 'PUT',
|
|
443
|
+
headers: { 'Content-Type': 'application/x-ndjson' },
|
|
444
|
+
body: ndjson,
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// Step 3: Finalize upload
|
|
449
|
+
const finalizeUrl = `${this.config.apiBaseUrl}/uploads/${session.upload_id}/finalize`;
|
|
450
|
+
await this.fetchImpl(finalizeUrl, {
|
|
451
|
+
method: 'POST',
|
|
452
|
+
headers: this._headers({ 'X-Upload-Finalize-Token': session.finalize_token || '' }),
|
|
453
|
+
body: JSON.stringify({}),
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
// Step 4: Load by upload_id
|
|
457
|
+
const loadUrl = `${this.config.apiBaseUrl}/databases/${this.config.databaseId}/schemas/${this.config.schema}/tables/${table}/loads`;
|
|
458
|
+
const loadRes = await this.fetchImpl(loadUrl, {
|
|
459
|
+
method: 'POST',
|
|
460
|
+
headers: this._headers(),
|
|
461
|
+
body: JSON.stringify({
|
|
462
|
+
mode: body.mode,
|
|
463
|
+
...(body.key ? { key: body.key } : {}),
|
|
464
|
+
upload_id: session.upload_id,
|
|
465
|
+
format: 'json',
|
|
466
|
+
}),
|
|
467
|
+
});
|
|
468
|
+
return loadRes.json().catch(() => ({ ok: true }));
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async ensureVectorIndex({ table, column = 'vector' }) {
|
|
472
|
+
if (!this.config.connectionId) return null;
|
|
473
|
+
const url = `${this.config.apiBaseUrl}/connections/${this.config.connectionId}/tables/${this.config.schema}/${table}/indexes`;
|
|
474
|
+
const payload = {
|
|
475
|
+
index_name: `${table}_${column}_idx`,
|
|
476
|
+
index_type: 'vector',
|
|
477
|
+
algorithm: this.config.vectorAlgorithm,
|
|
478
|
+
columns: [column],
|
|
479
|
+
metric: 'cosine',
|
|
480
|
+
vector_precision: this.config.vectorPrecision,
|
|
481
|
+
};
|
|
482
|
+
this.requestsLog.push({ method: 'POST', url, payload });
|
|
483
|
+
if (!this.fetchImpl) return payload;
|
|
484
|
+
const res = await this.fetchImpl(url, {
|
|
485
|
+
method: 'POST',
|
|
486
|
+
headers: this._headers(),
|
|
487
|
+
body: JSON.stringify(payload),
|
|
488
|
+
});
|
|
489
|
+
return res.json().catch(() => payload);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
async executeHotSql(sql) {
|
|
493
|
+
const url = `${this.config.apiBaseUrl}/query`;
|
|
494
|
+
const payload = {
|
|
495
|
+
async: false,
|
|
496
|
+
database_id: this.config.databaseId,
|
|
497
|
+
default_catalog: this.config.catalog,
|
|
498
|
+
default_schema: this.config.schema,
|
|
499
|
+
dialect: 'hotsql',
|
|
500
|
+
sql,
|
|
501
|
+
};
|
|
502
|
+
this.requestsLog.push({ method: 'POST', url, payload });
|
|
503
|
+
if (!this.fetchImpl) return null;
|
|
504
|
+
const res = await this.fetchImpl(url, {
|
|
505
|
+
method: 'POST',
|
|
506
|
+
headers: this._headers(),
|
|
507
|
+
body: JSON.stringify(payload),
|
|
508
|
+
});
|
|
509
|
+
if (!res.ok) return null;
|
|
510
|
+
const data = await res.json();
|
|
511
|
+
if (!data || !Array.isArray(data.columns) || !Array.isArray(data.rows)) return null;
|
|
512
|
+
return data.rows.map(rowArr => {
|
|
513
|
+
const obj = {};
|
|
514
|
+
data.columns.forEach((col, idx) => {
|
|
515
|
+
obj[col] = rowArr[idx];
|
|
516
|
+
});
|
|
517
|
+
return obj;
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Create a LanceDB-compatible `{ connect(dirOrOptions) }` loader backed by Hotdata DB.
|
|
524
|
+
*/
|
|
525
|
+
function createHotdataLanceAdapter(options = {}) {
|
|
526
|
+
const config = getHotdataConfig(options);
|
|
527
|
+
const httpClient = new HotdataHttpClient(config, options.fetchImpl);
|
|
528
|
+
|
|
529
|
+
return {
|
|
530
|
+
backend: 'hotdata',
|
|
531
|
+
config,
|
|
532
|
+
httpClient,
|
|
533
|
+
async connect(storeDir) {
|
|
534
|
+
const dir = typeof storeDir === 'string' ? storeDir : path.join(process.cwd(), '.thumbgate', 'hotdata');
|
|
535
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
536
|
+
|
|
537
|
+
return {
|
|
538
|
+
backend: 'hotdata',
|
|
539
|
+
async tableNames() {
|
|
540
|
+
if (!fs.existsSync(dir)) return [];
|
|
541
|
+
return fs.readdirSync(dir)
|
|
542
|
+
.filter(f => f.endsWith('.hotdata.jsonl'))
|
|
543
|
+
.map(f => f.replace(/\.hotdata\.jsonl$/, ''));
|
|
544
|
+
},
|
|
545
|
+
async createTable(tableName, initialRecords = []) {
|
|
546
|
+
const table = new HotdataTable({ tableName, storeDir: dir, config, httpClient });
|
|
547
|
+
await table.add(initialRecords, { mode: 'replace' });
|
|
548
|
+
if (config.remoteEnabled && config.connectionId) {
|
|
549
|
+
await httpClient.ensureVectorIndex({ table: tableName, column: 'vector' });
|
|
550
|
+
}
|
|
551
|
+
return table;
|
|
552
|
+
},
|
|
553
|
+
async openTable(tableName) {
|
|
554
|
+
return new HotdataTable({ tableName, storeDir: dir, config, httpClient });
|
|
555
|
+
},
|
|
556
|
+
async dropTable(tableName) {
|
|
557
|
+
const t = new HotdataTable({ tableName, storeDir: dir, config, httpClient });
|
|
558
|
+
if (fs.existsSync(t.snapshotPath)) fs.unlinkSync(t.snapshotPath);
|
|
559
|
+
if (fs.existsSync(t.metaPath)) fs.unlinkSync(t.metaPath);
|
|
560
|
+
},
|
|
561
|
+
};
|
|
562
|
+
},
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
module.exports = {
|
|
567
|
+
getHotdataConfig,
|
|
568
|
+
evaluateHotdataPreToolGate,
|
|
569
|
+
buildHotSqlVectorSearchQuery,
|
|
570
|
+
serializeRecordsToCsv,
|
|
571
|
+
cosineDistance,
|
|
572
|
+
HotdataTable,
|
|
573
|
+
HotdataHttpClient,
|
|
574
|
+
createHotdataLanceAdapter,
|
|
575
|
+
};
|
|
@@ -334,7 +334,7 @@ const {
|
|
|
334
334
|
finalizeSession: finalizeFeedbackSession,
|
|
335
335
|
} = require('../../scripts/feedback-session');
|
|
336
336
|
|
|
337
|
-
const SERVER_INFO = { name: 'thumbgate-mcp', version: '1.
|
|
337
|
+
const SERVER_INFO = { name: 'thumbgate-mcp', version: '1.39.0' };
|
|
338
338
|
const COMMERCE_CATEGORIES = [
|
|
339
339
|
'product_recommendation',
|
|
340
340
|
'brand_compliance',
|