phewsh 0.5.3 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/phewsh.js +2 -0
- package/commands/ai.js +18 -8
- package/commands/style.js +320 -0
- package/lib/supabase.js +46 -1
- package/package.json +1 -1
package/bin/phewsh.js
CHANGED
|
@@ -44,6 +44,7 @@ const COMMANDS = {
|
|
|
44
44
|
link: () => require('../commands/link'),
|
|
45
45
|
login: () => require('../commands/login'),
|
|
46
46
|
ai: () => require('../commands/ai'),
|
|
47
|
+
style: () => require('../commands/style'),
|
|
47
48
|
music: () => require('../commands/music'),
|
|
48
49
|
sap: () => require('../commands/sap'),
|
|
49
50
|
help: showHelp,
|
|
@@ -67,6 +68,7 @@ function showHelp() {
|
|
|
67
68
|
console.log(` ${w('ai')} Run context-aware AI prompts (reads .intent/)`);
|
|
68
69
|
console.log(` ${w('login')} Set up identity, API key, and cloud sync`);
|
|
69
70
|
console.log(` ${w('sap')} Sustainable AI Protocol — usage and accountability`);
|
|
71
|
+
console.log(` ${w('style')} Build your style identity — ingest, profile, sync`);
|
|
70
72
|
console.log(` ${w('music')} MBHD music engine`);
|
|
71
73
|
console.log('');
|
|
72
74
|
console.log(` ${b('Quick start')}`);
|
package/commands/ai.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const fs = require('fs');
|
|
2
2
|
const path = require('path');
|
|
3
3
|
const os = require('os');
|
|
4
|
+
const { trackSap } = require('../lib/supabase');
|
|
4
5
|
|
|
5
6
|
const CONFIG_PATH = path.join(os.homedir(), '.phewsh', 'config.json');
|
|
6
7
|
const INTENT_DIR = path.join(process.cwd(), '.intent');
|
|
@@ -35,14 +36,10 @@ function buildSystemPrompt(intentFiles) {
|
|
|
35
36
|
return `You are a focused execution assistant. The user has structured intent artifacts that define what they are building. Use these as your primary context for every response — stay aligned with their vision, plan, and next actions.\n\n${sections}`;
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
async function streamResponse(apiKey, systemPrompt, userPrompt) {
|
|
39
|
+
async function streamResponse(apiKey, systemPrompt, userPrompt, userId, accessToken) {
|
|
40
|
+
const model = 'claude-sonnet-4-6';
|
|
39
41
|
const messages = [{ role: 'user', content: userPrompt }];
|
|
40
|
-
const body = {
|
|
41
|
-
model: 'claude-sonnet-4-6',
|
|
42
|
-
max_tokens: 1024,
|
|
43
|
-
messages,
|
|
44
|
-
stream: true,
|
|
45
|
-
};
|
|
42
|
+
const body = { model, max_tokens: 1024, messages, stream: true };
|
|
46
43
|
if (systemPrompt) body.system = systemPrompt;
|
|
47
44
|
|
|
48
45
|
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
|
@@ -62,6 +59,9 @@ async function streamResponse(apiKey, systemPrompt, userPrompt) {
|
|
|
62
59
|
|
|
63
60
|
process.stdout.write('\n');
|
|
64
61
|
|
|
62
|
+
let promptTokens = null;
|
|
63
|
+
let completionTokens = null;
|
|
64
|
+
|
|
65
65
|
for await (const chunk of response.body) {
|
|
66
66
|
const text = Buffer.from(chunk).toString('utf-8');
|
|
67
67
|
const lines = text.split('\n').filter(l => l.startsWith('data: '));
|
|
@@ -73,11 +73,21 @@ async function streamResponse(apiKey, systemPrompt, userPrompt) {
|
|
|
73
73
|
if (parsed.type === 'content_block_delta' && parsed.delta?.text) {
|
|
74
74
|
process.stdout.write(parsed.delta.text);
|
|
75
75
|
}
|
|
76
|
+
// Capture token counts from Anthropic stream
|
|
77
|
+
if (parsed.type === 'message_start' && parsed.message?.usage) {
|
|
78
|
+
promptTokens = parsed.message.usage.input_tokens;
|
|
79
|
+
}
|
|
80
|
+
if (parsed.type === 'message_delta' && parsed.usage) {
|
|
81
|
+
completionTokens = parsed.usage.output_tokens;
|
|
82
|
+
}
|
|
76
83
|
} catch { /* skip malformed chunks */ }
|
|
77
84
|
}
|
|
78
85
|
}
|
|
79
86
|
|
|
80
87
|
process.stdout.write('\n\n');
|
|
88
|
+
|
|
89
|
+
// SAP: fire-and-forget after stream completes
|
|
90
|
+
trackSap({ userId, source: 'cli', model, promptTokens, completionTokens, accessToken });
|
|
81
91
|
}
|
|
82
92
|
|
|
83
93
|
async function main() {
|
|
@@ -135,7 +145,7 @@ async function main() {
|
|
|
135
145
|
console.log('\n No .intent/ found — running without project context');
|
|
136
146
|
}
|
|
137
147
|
|
|
138
|
-
await streamResponse(config.apiKey, systemPrompt, prompt);
|
|
148
|
+
await streamResponse(config.apiKey, systemPrompt, prompt, config.supabaseUserId, config.supabaseAccessToken);
|
|
139
149
|
return;
|
|
140
150
|
}
|
|
141
151
|
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// phewsh style — build and manage your StyleTree identity
|
|
2
|
+
// Pipeline: ingest → extract features → rebuild profile → display
|
|
3
|
+
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const os = require('os');
|
|
7
|
+
const readline = require('readline');
|
|
8
|
+
const { select, upsert, SUPABASE_URL, SUPABASE_ANON_KEY } = require('../lib/supabase');
|
|
9
|
+
|
|
10
|
+
const CONFIG_PATH = path.join(os.homedir(), '.phewsh', 'config.json');
|
|
11
|
+
const STYLE_CACHE_DIR = path.join(os.homedir(), '.phewsh', 'styletree');
|
|
12
|
+
|
|
13
|
+
// ── ANSI
|
|
14
|
+
const b = (s) => `\x1b[1m${s}\x1b[0m`;
|
|
15
|
+
const d = (s) => `\x1b[2m${s}\x1b[0m`;
|
|
16
|
+
const g = (s) => `\x1b[90m${s}\x1b[0m`;
|
|
17
|
+
const c = (s) => `\x1b[36m${s}\x1b[0m`;
|
|
18
|
+
const y = (s) => `\x1b[33m${s}\x1b[0m`;
|
|
19
|
+
|
|
20
|
+
function loadConfig() {
|
|
21
|
+
try { return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8')); } catch { return null; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function ask(rl, q) {
|
|
25
|
+
return new Promise((resolve) => rl.question(q, (a) => resolve(a.trim())));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function ensureCacheDir() {
|
|
29
|
+
fs.mkdirSync(STYLE_CACHE_DIR, { recursive: true });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ── Basic audio metadata via Node (no heavy deps — just file info for MVP)
|
|
33
|
+
function extractBasicFileInfo(filePath) {
|
|
34
|
+
try {
|
|
35
|
+
const stat = fs.statSync(filePath);
|
|
36
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
37
|
+
const mediumMap = {
|
|
38
|
+
'.mp3': 'audio', '.wav': 'audio', '.flac': 'audio', '.aac': 'audio',
|
|
39
|
+
'.ogg': 'audio', '.m4a': 'audio', '.aiff': 'audio',
|
|
40
|
+
'.mid': 'midi', '.midi': 'midi',
|
|
41
|
+
'.txt': 'text', '.md': 'text',
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
file_size_bytes: stat.size,
|
|
45
|
+
mime_type: ext,
|
|
46
|
+
medium: mediumMap[ext] || 'other',
|
|
47
|
+
};
|
|
48
|
+
} catch {
|
|
49
|
+
return { medium: 'other' };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ── Save artifact + features locally (Tier 0)
|
|
54
|
+
function saveLocally(artifact, features) {
|
|
55
|
+
ensureCacheDir();
|
|
56
|
+
const localPath = path.join(STYLE_CACHE_DIR, 'artifacts.json');
|
|
57
|
+
let existing = [];
|
|
58
|
+
try { existing = JSON.parse(fs.readFileSync(localPath, 'utf-8')); } catch { /* empty */ }
|
|
59
|
+
existing.push({ artifact, features, savedAt: new Date().toISOString() });
|
|
60
|
+
fs.writeFileSync(localPath, JSON.stringify(existing, null, 2));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ── Load local artifact cache
|
|
64
|
+
function loadLocal() {
|
|
65
|
+
try {
|
|
66
|
+
const localPath = path.join(STYLE_CACHE_DIR, 'artifacts.json');
|
|
67
|
+
return JSON.parse(fs.readFileSync(localPath, 'utf-8'));
|
|
68
|
+
} catch { return []; }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ── Rebuild profile from local cache
|
|
72
|
+
function buildLocalProfile(entries) {
|
|
73
|
+
const tempos = entries.map(e => e.features?.tempo_bpm).filter(Boolean);
|
|
74
|
+
const keys = entries.map(e => e.features?.key_signature).filter(Boolean);
|
|
75
|
+
const vibes = entries.flatMap(e => e.features?.vibe || []).filter(Boolean);
|
|
76
|
+
const instruments = entries.flatMap(e => e.features?.instruments || []).filter(Boolean);
|
|
77
|
+
const energies = entries.map(e => e.features?.energy).filter(Boolean);
|
|
78
|
+
|
|
79
|
+
const freq = (arr) => {
|
|
80
|
+
const counts = {};
|
|
81
|
+
arr.forEach(v => counts[v] = (counts[v] || 0) + 1);
|
|
82
|
+
return Object.entries(counts).sort((a, b) => b[1] - a[1]).map(([k]) => k);
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
artifact_count: entries.length,
|
|
87
|
+
tempo_range: tempos.length ? [Math.min(...tempos), Math.max(...tempos)] : null,
|
|
88
|
+
dominant_keys: [...new Set(keys)].slice(0, 3),
|
|
89
|
+
vibe_signature: freq(vibes).slice(0, 5),
|
|
90
|
+
instrument_palette: freq(instruments).slice(0, 6),
|
|
91
|
+
energy_avg: energies.length ? energies.reduce((a, b) => a + b, 0) / energies.length : null,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ── Print style profile
|
|
96
|
+
function printProfile(profile, email) {
|
|
97
|
+
console.log('');
|
|
98
|
+
console.log(` ${b('your style')} ${g(email ? `· ${email}` : '')}`);
|
|
99
|
+
console.log(` ${d('─────────────────────────────')}`);
|
|
100
|
+
|
|
101
|
+
if (profile.artifact_count === 0) {
|
|
102
|
+
console.log(` ${g('no artifacts yet — run: phewsh style --ingest <file>')}`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
console.log(` ${g('sessions ')}${profile.artifact_count}`);
|
|
107
|
+
|
|
108
|
+
if (profile.tempo_range) {
|
|
109
|
+
const [lo, hi] = profile.tempo_range;
|
|
110
|
+
const label = lo === hi ? `${lo} BPM` : `${Math.round(lo)}–${Math.round(hi)} BPM`;
|
|
111
|
+
console.log(` ${g('tempo ')}${label}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (profile.dominant_keys?.length) {
|
|
115
|
+
console.log(` ${g('keys ')}${profile.dominant_keys.join(', ')}`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (profile.vibe_signature?.length) {
|
|
119
|
+
console.log(` ${g('vibe ')}${profile.vibe_signature.join(' · ')}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (profile.instrument_palette?.length) {
|
|
123
|
+
console.log(` ${g('instruments ')}${profile.instrument_palette.join(', ')}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (profile.energy_avg !== null && profile.energy_avg !== undefined) {
|
|
127
|
+
const energyLabel = profile.energy_avg > 0.7 ? 'high' : profile.energy_avg > 0.4 ? 'mid' : 'soft';
|
|
128
|
+
console.log(` ${g('dynamics ')}${energyLabel}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
console.log('');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ── Sync artifact + features to Supabase
|
|
135
|
+
async function syncToCloud(config, artifact, features) {
|
|
136
|
+
if (!config?.supabaseAccessToken) return null;
|
|
137
|
+
|
|
138
|
+
const headers = {
|
|
139
|
+
'Content-Type': 'application/json',
|
|
140
|
+
'apikey': SUPABASE_ANON_KEY,
|
|
141
|
+
'Authorization': `Bearer ${config.supabaseAccessToken}`,
|
|
142
|
+
'Prefer': 'resolution=merge-duplicates,return=representation',
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// Insert artifact
|
|
146
|
+
const artifactRes = await fetch(`${SUPABASE_URL}/rest/v1/styletree_artifacts`, {
|
|
147
|
+
method: 'POST',
|
|
148
|
+
headers,
|
|
149
|
+
body: JSON.stringify({ ...artifact, user_id: config.supabaseUserId }),
|
|
150
|
+
});
|
|
151
|
+
if (!artifactRes.ok) return null;
|
|
152
|
+
const [savedArtifact] = await artifactRes.json();
|
|
153
|
+
|
|
154
|
+
// Insert features
|
|
155
|
+
await fetch(`${SUPABASE_URL}/rest/v1/styletree_features`, {
|
|
156
|
+
method: 'POST',
|
|
157
|
+
headers,
|
|
158
|
+
body: JSON.stringify({ ...features, artifact_id: savedArtifact.id, user_id: config.supabaseUserId }),
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// Trigger profile rebuild via RPC
|
|
162
|
+
await fetch(`${SUPABASE_URL}/rest/v1/rpc/rebuild_styletree_profile`, {
|
|
163
|
+
method: 'POST',
|
|
164
|
+
headers,
|
|
165
|
+
body: JSON.stringify({ p_user_id: config.supabaseUserId }),
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
return savedArtifact.id;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ── Main
|
|
172
|
+
async function main() {
|
|
173
|
+
const args = process.argv.slice(3);
|
|
174
|
+
const config = loadConfig();
|
|
175
|
+
|
|
176
|
+
// --status
|
|
177
|
+
if (args.includes('--status') || args.length === 0) {
|
|
178
|
+
const entries = loadLocal();
|
|
179
|
+
const profile = buildLocalProfile(entries);
|
|
180
|
+
printProfile(profile, config?.email);
|
|
181
|
+
if (!config?.supabaseUserId) {
|
|
182
|
+
console.log(` ${g('tip: run phewsh login to sync your style to the cloud')}`);
|
|
183
|
+
console.log('');
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// --ingest <file>
|
|
189
|
+
if (args.includes('--ingest')) {
|
|
190
|
+
const fileIdx = args.indexOf('--ingest');
|
|
191
|
+
const filePath = args[fileIdx + 1];
|
|
192
|
+
|
|
193
|
+
if (!filePath) {
|
|
194
|
+
console.error(`\n Usage: phewsh style --ingest <file>\n`);
|
|
195
|
+
process.exit(1);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const absPath = path.resolve(filePath);
|
|
199
|
+
if (!fs.existsSync(absPath)) {
|
|
200
|
+
console.error(`\n File not found: ${absPath}\n`);
|
|
201
|
+
process.exit(1);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const fileInfo = extractBasicFileInfo(absPath);
|
|
205
|
+
const fileName = path.basename(absPath);
|
|
206
|
+
|
|
207
|
+
console.log('');
|
|
208
|
+
console.log(` ${b('😮\u200d💨 ingesting')} ${c(fileName)}`);
|
|
209
|
+
console.log(` ${g('medium: ' + fileInfo.medium + ' · size: ' + (fileInfo.file_size_bytes ? Math.round(fileInfo.file_size_bytes / 1024) + 'kb' : 'unknown'))}`);
|
|
210
|
+
console.log('');
|
|
211
|
+
|
|
212
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
213
|
+
|
|
214
|
+
const title = await ask(rl, ` ${g('title')} (or enter to use filename)\n > `);
|
|
215
|
+
const tempoInput = await ask(rl, ` ${g('tempo')} BPM (leave blank if unknown)\n > `);
|
|
216
|
+
const keyInput = await ask(rl, ` ${g('key')} (e.g. C minor, F# major — blank to skip)\n > `);
|
|
217
|
+
const vibeInput = await ask(rl, ` ${g('vibe')} (e.g. dark chill driving — space-separated)\n > `);
|
|
218
|
+
const instrumentInput = await ask(rl, ` ${g('instruments')} (e.g. piano bass drums — space-separated)\n > `);
|
|
219
|
+
|
|
220
|
+
rl.close();
|
|
221
|
+
console.log('');
|
|
222
|
+
|
|
223
|
+
const artifact = {
|
|
224
|
+
title: title || fileName,
|
|
225
|
+
medium: fileInfo.medium,
|
|
226
|
+
file_path: absPath,
|
|
227
|
+
file_size_bytes: fileInfo.file_size_bytes || null,
|
|
228
|
+
mime_type: fileInfo.mime_type || null,
|
|
229
|
+
sync_tier: 0,
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const features = {
|
|
233
|
+
tempo_bpm: tempoInput ? parseFloat(tempoInput) : null,
|
|
234
|
+
key_signature: keyInput || null,
|
|
235
|
+
mode: keyInput?.toLowerCase().includes('minor') ? 'minor'
|
|
236
|
+
: keyInput?.toLowerCase().includes('major') ? 'major'
|
|
237
|
+
: 'unknown',
|
|
238
|
+
vibe: vibeInput ? vibeInput.split(/\s+/).filter(Boolean) : [],
|
|
239
|
+
instruments: instrumentInput ? instrumentInput.split(/\s+/).filter(Boolean) : [],
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
// Always save locally first
|
|
243
|
+
saveLocally(artifact, features);
|
|
244
|
+
console.log(` ${c('✓')} saved locally`);
|
|
245
|
+
|
|
246
|
+
// Sync to cloud if logged in
|
|
247
|
+
if (config?.supabaseAccessToken) {
|
|
248
|
+
process.stdout.write(` ${g('syncing to cloud...')}`);
|
|
249
|
+
try {
|
|
250
|
+
const id = await syncToCloud(config, artifact, features);
|
|
251
|
+
if (id) {
|
|
252
|
+
process.stdout.write(`\r ${c('✓')} synced to cloud\n`);
|
|
253
|
+
} else {
|
|
254
|
+
process.stdout.write(`\r ${g('⚠ cloud sync skipped (run phewsh login --refresh)')}\n`);
|
|
255
|
+
}
|
|
256
|
+
} catch {
|
|
257
|
+
process.stdout.write(`\r ${g('⚠ cloud sync failed — local copy saved')}\n`);
|
|
258
|
+
}
|
|
259
|
+
} else {
|
|
260
|
+
console.log(` ${g('tip: run phewsh login to enable cloud sync')}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Print updated profile
|
|
264
|
+
const entries = loadLocal();
|
|
265
|
+
const profile = buildLocalProfile(entries);
|
|
266
|
+
printProfile(profile, config?.email);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// --sync
|
|
271
|
+
if (args.includes('--sync')) {
|
|
272
|
+
if (!config?.supabaseAccessToken) {
|
|
273
|
+
console.error(`\n Not logged in. Run: phewsh login\n`);
|
|
274
|
+
process.exit(1);
|
|
275
|
+
}
|
|
276
|
+
const entries = loadLocal();
|
|
277
|
+
if (!entries.length) {
|
|
278
|
+
console.log(`\n Nothing to sync. Run: phewsh style --ingest <file>\n`);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
console.log(`\n Syncing ${entries.length} artifact(s) to cloud...\n`);
|
|
282
|
+
let synced = 0;
|
|
283
|
+
for (const { artifact, features } of entries) {
|
|
284
|
+
try {
|
|
285
|
+
const id = await syncToCloud(config, artifact, features);
|
|
286
|
+
if (id) synced++;
|
|
287
|
+
} catch { /* skip */ }
|
|
288
|
+
}
|
|
289
|
+
console.log(` ${c('✓')} ${synced}/${entries.length} synced\n`);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// --link-intent: mark that style should influence intent generation
|
|
294
|
+
if (args.includes('--link-intent')) {
|
|
295
|
+
const intentDir = path.join(process.cwd(), '.intent');
|
|
296
|
+
if (!fs.existsSync(intentDir)) {
|
|
297
|
+
console.error(`\n No .intent/ found here. Run: phewsh intent --init\n`);
|
|
298
|
+
process.exit(1);
|
|
299
|
+
}
|
|
300
|
+
const entries = loadLocal();
|
|
301
|
+
const profile = buildLocalProfile(entries);
|
|
302
|
+
const linkPath = path.join(intentDir, 'style.json');
|
|
303
|
+
fs.writeFileSync(linkPath, JSON.stringify(profile, null, 2));
|
|
304
|
+
console.log(`\n ${c('✓')} style profile linked to .intent/style.json`);
|
|
305
|
+
console.log(` ${g('phewsh ai will now include your style context automatically')}\n`);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
console.error(`\n Unknown style command. Try:\n`);
|
|
310
|
+
console.error(` phewsh style --ingest <file> ingest a new artifact`);
|
|
311
|
+
console.error(` phewsh style --status view your style profile`);
|
|
312
|
+
console.error(` phewsh style --sync push to cloud`);
|
|
313
|
+
console.error(` phewsh style --link-intent link style to current project\n`);
|
|
314
|
+
process.exit(1);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
main().catch(err => {
|
|
318
|
+
console.error('\n Error:', err.message);
|
|
319
|
+
process.exit(1);
|
|
320
|
+
});
|
package/lib/supabase.js
CHANGED
|
@@ -77,4 +77,49 @@ async function upsert(table, data, accessToken) {
|
|
|
77
77
|
return res.json();
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
|
|
80
|
+
// SAP: fire-and-forget per-inference tracking
|
|
81
|
+
// kWh estimates by model family (conservative)
|
|
82
|
+
const MODEL_KWH = {
|
|
83
|
+
'claude-haiku': 0.00025,
|
|
84
|
+
'claude-sonnet': 0.00060,
|
|
85
|
+
'claude-opus': 0.00200,
|
|
86
|
+
'gemini-flash': 0.00020,
|
|
87
|
+
'deepseek': 0.00030,
|
|
88
|
+
'kimi': 0.00040,
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
function estimateKwh(model, totalTokens) {
|
|
92
|
+
let base = 0.0004;
|
|
93
|
+
if (model) {
|
|
94
|
+
const lower = model.toLowerCase();
|
|
95
|
+
for (const [key, val] of Object.entries(MODEL_KWH)) {
|
|
96
|
+
if (lower.includes(key)) { base = val; break; }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const scale = Math.max(0.5, Math.min(4, (totalTokens || 1000) / 1000));
|
|
100
|
+
return base * scale;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function trackSap({ userId, source = 'cli', model, promptTokens, completionTokens, accessToken } = {}) {
|
|
104
|
+
const totalTokens = (promptTokens || 0) + (completionTokens || 0);
|
|
105
|
+
const kwh = estimateKwh(model, totalTokens);
|
|
106
|
+
const co2_g = kwh * 500; // US grid avg gCO2/kWh
|
|
107
|
+
const water_ml = kwh * 1800;
|
|
108
|
+
|
|
109
|
+
req('/rest/v1/rpc/track_sap_event', {
|
|
110
|
+
method: 'POST',
|
|
111
|
+
body: JSON.stringify({
|
|
112
|
+
p_user_id: userId || null,
|
|
113
|
+
p_session_id: null,
|
|
114
|
+
p_source: source,
|
|
115
|
+
p_model: model || null,
|
|
116
|
+
p_prompt_tokens: promptTokens || null,
|
|
117
|
+
p_completion_tokens: completionTokens || null,
|
|
118
|
+
p_kwh: kwh,
|
|
119
|
+
p_co2_g: co2_g,
|
|
120
|
+
p_water_ml: water_ml,
|
|
121
|
+
}),
|
|
122
|
+
}, accessToken).catch(() => { /* never surface SAP errors */ });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
module.exports = { sendOtp, verifyOtp, refreshSession, select, upsert, trackSap, SUPABASE_URL, SUPABASE_ANON_KEY };
|