@walkhi/code-relax 0.1.0-beta.23 → 0.1.0-beta.25

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.
@@ -1,136 +1,141 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { recordDailyUsage } from './usage-daily.mjs';
3
-
4
- const epoch = value => new Date(`${value.replace(' ', 'T')}Z`).getTime();
5
-
6
- // Count confirmed intervals only; a lost connection never creates estimated time.
7
- export function usageMeter(pool) {
8
- async function action(connection, computerId, clientId, kind, key) {
9
- if (!connection.userId || !['message', 'turn'].includes(kind) || typeof key !== 'string' || !key || key.length > 128) return;
10
- const column = kind === 'message' ? 'message_count' : 'turn_count';
11
- const db = await pool.getConnection();
12
- try {
13
- await db.beginTransaction();
14
- const [result] = await db.execute(`INSERT IGNORE INTO relay_usage_actions
15
- (computer_id,kind,action_key,user_id,client_id,occurred_at)
16
- VALUES (?,?,?,?,?,UTC_TIMESTAMP(3))`,
17
- [computerId, kind, key, connection.userId, clientId]);
18
- if (result.affectedRows === 1) {
19
- await db.execute(`INSERT INTO relay_usage_totals (user_id,${column},updated_at)
20
- VALUES (?,1,UTC_TIMESTAMP(3)) ON DUPLICATE KEY UPDATE ${column}=${column}+1,
21
- updated_at=VALUES(updated_at)`, [connection.userId]);
22
- await db.execute(`INSERT INTO relay_usage_computer_totals (computer_id,${column},updated_at)
23
- VALUES (?,1,UTC_TIMESTAMP(3)) ON DUPLICATE KEY UPDATE ${column}=${column}+1,
24
- updated_at=VALUES(updated_at)`, [computerId]);
25
- }
26
- await db.commit();
27
- return result.affectedRows === 1;
28
- } catch (error) { await db.rollback(); throw error; }
29
- finally { db.release(); }
30
- }
31
- async function turnOrigin(computerId, key) {
32
- const [rows] = await pool.execute(`SELECT user_id,client_id FROM relay_usage_actions
33
- WHERE computer_id=? AND kind='turn' AND action_key=?`, [computerId, key]);
34
- return rows[0] ? { userId: rows[0].user_id, clientId: rows[0].client_id } : null;
35
- }
36
- async function pulse(connection, active, computerId, clientId, externalKey = null) {
37
- if (!connection.userId) return;
38
- if (!active && !connection.usageSessionId) return;
39
- if (active && !connection.usageSessionId) {
40
- const id = randomUUID();
41
- await pool.execute(`INSERT INTO relay_usage_sessions
42
- (id,kind,external_key,user_id,computer_id,client_id,started_at,confirmed_until,charged_seconds)
43
- VALUES (?,'task',?,?,?,?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3),0)`, [id, externalKey, connection.userId, computerId, clientId]);
44
- connection.usageSessionId = id;
45
- return;
46
- }
47
- const id = connection.usageSessionId;
48
- const db = await pool.getConnection();
49
- try {
50
- await db.beginTransaction();
51
- const [rows] = await db.execute('SELECT user_id,computer_id,confirmed_until,ended_at FROM relay_usage_sessions WHERE id=? FOR UPDATE', [id]);
52
- const row = rows[0];
53
- if (!row || row.ended_at) throw new Error('Invalid relay usage session');
54
- const [clock] = await db.query('SELECT UTC_TIMESTAMP(3) AS now');
55
- const now = clock[0].now;
56
- const nowMs = epoch(now);
57
- const chargeStart = Math.max(epoch(row.confirmed_until), nowMs - 20000);
58
- const seconds = Math.max(0, nowMs - chargeStart) / 1000;
59
- const [plans] = await db.execute('SELECT tier,valid_until FROM relay_usage_entitlements WHERE user_id=?', [row.user_id]);
60
- const subscribed = plans[0]?.tier === 'subscriber' && plans[0].valid_until && epoch(plans[0].valid_until) > epoch(now);
61
- const freeSeconds = subscribed ? 0 : seconds;
62
- await db.execute(`UPDATE relay_usage_sessions SET confirmed_until=?,ended_at=?,charged_seconds=charged_seconds+?,
63
- free_charged_seconds=free_charged_seconds+? WHERE id=?`, [now, active ? null : now, seconds, freeSeconds, id]);
64
- if (seconds > 0) {
65
- await recordDailyUsage(db, row.user_id, row.computer_id, !subscribed,
66
- chargeStart, nowMs, now);
67
- await db.execute(`INSERT INTO relay_usage_totals (user_id,task_seconds,updated_at)
68
- VALUES (?,?,?) ON DUPLICATE KEY UPDATE task_seconds=task_seconds+VALUES(task_seconds),
69
- updated_at=VALUES(updated_at)`, [row.user_id, seconds, now]);
70
- await db.execute(`INSERT INTO relay_usage_computer_totals (computer_id,task_seconds,free_task_seconds,updated_at)
71
- VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE task_seconds=task_seconds+VALUES(task_seconds),
72
- free_task_seconds=free_task_seconds+VALUES(free_task_seconds),updated_at=VALUES(updated_at)`,
73
- [row.computer_id, seconds, freeSeconds, now]);
74
- }
75
- await db.commit();
76
- if (!active) connection.usageSessionId = undefined;
77
- } catch (error) { await db.rollback(); throw error; }
78
- finally { db.release(); }
79
- }
80
-
81
- async function lost(connection) {
82
- const id = connection.usageSessionId;
83
- connection.usageSessionId = undefined;
84
- if (!id) return;
85
- await pool.execute(`UPDATE relay_usage_sessions SET ended_at=confirmed_until
86
- WHERE id=? AND ended_at IS NULL`, [id]);
87
- }
88
-
89
- return { action, turnOrigin, pulse, lost };
90
- }
91
-
92
- export async function usageReport(pool, page, view = 'user') {
93
- if (view === 'computer') {
94
- const offset = (page - 1) * 30;
95
- const [counts] = await pool.query(`SELECT COUNT(*) AS total FROM relay_usage_computer_days
96
- WHERE usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND task_seconds>0`);
97
- const [rows] = await pool.execute(`SELECT c.id,
98
- d.task_seconds AS today_task_seconds,
99
- d.free_task_seconds AS today_free_task_seconds,
100
- COALESCE(a.message_count,0) AS message_count,
101
- COALESCE(a.turn_count,0) AS turn_count,
102
- COALESCE(GREATEST(s.last_used_at,a.last_used_at),s.last_used_at,a.last_used_at) AS last_used_at
103
- FROM relay_usage_computer_days d JOIN computers c ON c.id=d.computer_id
104
- LEFT JOIN (SELECT computer_id,SUM(kind='message') AS message_count,
105
- SUM(kind='turn') AS turn_count,MAX(occurred_at) AS last_used_at FROM relay_usage_actions
106
- WHERE occurred_at >= DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) - INTERVAL 8 HOUR
107
- AND occurred_at < DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) + INTERVAL 16 HOUR
108
- GROUP BY computer_id) a ON a.computer_id=c.id
109
- LEFT JOIN (SELECT computer_id,MAX(confirmed_until) AS last_used_at
110
- FROM relay_usage_sessions GROUP BY computer_id) s ON s.computer_id=c.id
111
- WHERE d.usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND d.task_seconds>0
112
- ORDER BY d.task_seconds DESC,c.id LIMIT ? OFFSET ?`, [30, offset]);
113
- return { page, pageSize: 30, total: counts[0].total, rows };
114
- }
115
- const offset = (page - 1) * 30;
116
- const [counts] = await pool.query(`SELECT COUNT(*) AS total FROM relay_usage_user_days d
117
- JOIN user_login_identities i ON i.user_id=d.user_id AND i.kind='email'
118
- WHERE d.usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND d.task_seconds>0`);
119
- const [rows] = await pool.execute(`SELECT u.id,i.normalized_value AS email,
120
- d.task_seconds AS today_task_seconds,
121
- COALESCE(a.message_count,0) AS message_count,
122
- COALESCE(a.turn_count,0) AS turn_count,
123
- COALESCE(GREATEST(s.last_used_at,a.last_used_at),s.last_used_at,a.last_used_at) AS last_used_at
124
- FROM relay_usage_user_days d JOIN users u ON u.id=d.user_id
125
- JOIN user_login_identities i ON i.user_id=u.id AND i.kind='email'
126
- LEFT JOIN (SELECT user_id,SUM(kind='message') AS message_count,
127
- SUM(kind='turn') AS turn_count,MAX(occurred_at) AS last_used_at FROM relay_usage_actions
128
- WHERE occurred_at >= DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) - INTERVAL 8 HOUR
129
- AND occurred_at < DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) + INTERVAL 16 HOUR
130
- GROUP BY user_id) a ON a.user_id=u.id
131
- LEFT JOIN (SELECT user_id,MAX(confirmed_until) AS last_used_at
132
- FROM relay_usage_sessions GROUP BY user_id) s ON s.user_id=u.id
133
- WHERE d.usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND d.task_seconds>0
134
- ORDER BY d.task_seconds DESC,u.id LIMIT ? OFFSET ?`, [30, offset]);
135
- return { page, pageSize: 30, total: counts[0].total, rows };
136
- }
1
+ import { randomUUID } from 'node:crypto';
2
+ import { recordDailyUsage } from './usage-daily.mjs';
3
+
4
+ const epoch = value => new Date(`${value.replace(' ', 'T')}Z`).getTime();
5
+
6
+ // Count confirmed intervals only; a lost connection never creates estimated time.
7
+ export function usageMeter(pool) {
8
+ async function action(connection, computerId, clientId, kind, key) {
9
+ if (!connection.userId || !['message', 'turn'].includes(kind) || typeof key !== 'string' || !key || key.length > 128) return;
10
+ const column = kind === 'message' ? 'message_count' : 'turn_count';
11
+ const db = await pool.getConnection();
12
+ try {
13
+ await db.beginTransaction();
14
+ const [users] = await db.execute("SELECT id FROM users WHERE id=? AND status='active' FOR UPDATE", [connection.userId]);
15
+ if (!users.length) { await db.commit(); return false; }
16
+ const [result] = await db.execute(`INSERT IGNORE INTO relay_usage_actions
17
+ (computer_id,kind,action_key,user_id,client_id,occurred_at)
18
+ VALUES (?,?,?,?,?,UTC_TIMESTAMP(3))`,
19
+ [computerId, kind, key, connection.userId, clientId]);
20
+ if (result.affectedRows === 1) {
21
+ await db.execute(`INSERT INTO relay_usage_totals (user_id,${column},updated_at)
22
+ VALUES (?,1,UTC_TIMESTAMP(3)) ON DUPLICATE KEY UPDATE ${column}=${column}+1,
23
+ updated_at=VALUES(updated_at)`, [connection.userId]);
24
+ await db.execute(`INSERT INTO relay_usage_computer_totals (computer_id,${column},updated_at)
25
+ VALUES (?,1,UTC_TIMESTAMP(3)) ON DUPLICATE KEY UPDATE ${column}=${column}+1,
26
+ updated_at=VALUES(updated_at)`, [computerId]);
27
+ }
28
+ await db.commit();
29
+ return result.affectedRows === 1;
30
+ } catch (error) { await db.rollback(); throw error; }
31
+ finally { db.release(); }
32
+ }
33
+ async function turnOrigin(computerId, key) {
34
+ const [rows] = await pool.execute(`SELECT a.user_id,a.client_id FROM relay_usage_actions a JOIN users u ON u.id=a.user_id
35
+ WHERE a.computer_id=? AND a.kind='turn' AND a.action_key=? AND u.status='active'`, [computerId, key]);
36
+ return rows[0] ? { userId: rows[0].user_id, clientId: rows[0].client_id } : null;
37
+ }
38
+ async function pulse(connection, active, computerId, clientId, externalKey = null) {
39
+ if (!connection.userId) return;
40
+ if (!active && !connection.usageSessionId) return;
41
+ if (active && !connection.usageSessionId) {
42
+ const id = randomUUID();
43
+ const [inserted] = await pool.execute(`INSERT INTO relay_usage_sessions
44
+ (id,kind,external_key,user_id,computer_id,client_id,started_at,confirmed_until,charged_seconds)
45
+ SELECT ?,'task',?,?,?,?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3),0 FROM users WHERE id=? AND status='active'`, [id, externalKey, connection.userId, computerId, clientId, connection.userId]);
46
+ if (!inserted.affectedRows) return;
47
+ connection.usageSessionId = id;
48
+ return;
49
+ }
50
+ const id = connection.usageSessionId;
51
+ const db = await pool.getConnection();
52
+ try {
53
+ await db.beginTransaction();
54
+ const [users] = await db.execute("SELECT id FROM users WHERE id=? AND status='active' FOR UPDATE", [connection.userId]);
55
+ if (!users.length) { await db.commit(); connection.usageSessionId = undefined; return; }
56
+ const [rows] = await db.execute('SELECT user_id,computer_id,confirmed_until,ended_at FROM relay_usage_sessions WHERE id=? FOR UPDATE', [id]);
57
+ const row = rows[0];
58
+ if (!row || row.ended_at) throw new Error('Invalid relay usage session');
59
+ const [clock] = await db.query('SELECT UTC_TIMESTAMP(3) AS now');
60
+ const now = clock[0].now;
61
+ const nowMs = epoch(now);
62
+ const chargeStart = Math.max(epoch(row.confirmed_until), nowMs - 20000);
63
+ const seconds = Math.max(0, nowMs - chargeStart) / 1000;
64
+ const [plans] = await db.execute('SELECT tier,valid_until FROM relay_usage_entitlements WHERE user_id=?', [row.user_id]);
65
+ const subscribed = plans[0]?.tier === 'subscriber' && plans[0].valid_until && epoch(plans[0].valid_until) > epoch(now);
66
+ const freeSeconds = subscribed ? 0 : seconds;
67
+ await db.execute(`UPDATE relay_usage_sessions SET confirmed_until=?,ended_at=?,charged_seconds=charged_seconds+?,
68
+ free_charged_seconds=free_charged_seconds+? WHERE id=?`, [now, active ? null : now, seconds, freeSeconds, id]);
69
+ if (seconds > 0) {
70
+ await recordDailyUsage(db, row.user_id, row.computer_id, !subscribed,
71
+ chargeStart, nowMs, now);
72
+ await db.execute(`INSERT INTO relay_usage_totals (user_id,task_seconds,updated_at)
73
+ VALUES (?,?,?) ON DUPLICATE KEY UPDATE task_seconds=task_seconds+VALUES(task_seconds),
74
+ updated_at=VALUES(updated_at)`, [row.user_id, seconds, now]);
75
+ await db.execute(`INSERT INTO relay_usage_computer_totals (computer_id,task_seconds,free_task_seconds,updated_at)
76
+ VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE task_seconds=task_seconds+VALUES(task_seconds),
77
+ free_task_seconds=free_task_seconds+VALUES(free_task_seconds),updated_at=VALUES(updated_at)`,
78
+ [row.computer_id, seconds, freeSeconds, now]);
79
+ }
80
+ await db.commit();
81
+ if (!active) connection.usageSessionId = undefined;
82
+ } catch (error) { await db.rollback(); throw error; }
83
+ finally { db.release(); }
84
+ }
85
+
86
+ async function lost(connection) {
87
+ const id = connection.usageSessionId;
88
+ connection.usageSessionId = undefined;
89
+ if (!id) return;
90
+ await pool.execute(`UPDATE relay_usage_sessions SET ended_at=confirmed_until
91
+ WHERE id=? AND ended_at IS NULL`, [id]);
92
+ }
93
+
94
+ return { action, turnOrigin, pulse, lost };
95
+ }
96
+
97
+ export async function usageReport(pool, page, view = 'user') {
98
+ if (view === 'computer') {
99
+ const offset = (page - 1) * 30;
100
+ const [counts] = await pool.query(`SELECT COUNT(*) AS total FROM relay_usage_computer_days
101
+ WHERE usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND task_seconds>0`);
102
+ const [rows] = await pool.execute(`SELECT c.id,
103
+ d.task_seconds AS today_task_seconds,
104
+ d.free_task_seconds AS today_free_task_seconds,
105
+ COALESCE(a.message_count,0) AS message_count,
106
+ COALESCE(a.turn_count,0) AS turn_count,
107
+ COALESCE(GREATEST(s.last_used_at,a.last_used_at),s.last_used_at,a.last_used_at) AS last_used_at
108
+ FROM relay_usage_computer_days d JOIN computers c ON c.id=d.computer_id
109
+ LEFT JOIN (SELECT computer_id,SUM(kind='message') AS message_count,
110
+ SUM(kind='turn') AS turn_count,MAX(occurred_at) AS last_used_at FROM relay_usage_actions
111
+ WHERE occurred_at >= DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) - INTERVAL 8 HOUR
112
+ AND occurred_at < DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) + INTERVAL 16 HOUR
113
+ GROUP BY computer_id) a ON a.computer_id=c.id
114
+ LEFT JOIN (SELECT computer_id,MAX(confirmed_until) AS last_used_at
115
+ FROM relay_usage_sessions GROUP BY computer_id) s ON s.computer_id=c.id
116
+ WHERE d.usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND d.task_seconds>0
117
+ ORDER BY d.task_seconds DESC,c.id LIMIT ? OFFSET ?`, [30, offset]);
118
+ return { page, pageSize: 30, total: counts[0].total, rows };
119
+ }
120
+ const offset = (page - 1) * 30;
121
+ const [counts] = await pool.query(`SELECT COUNT(*) AS total FROM relay_usage_user_days d
122
+ JOIN user_login_identities i ON i.user_id=d.user_id AND i.kind='email'
123
+ WHERE d.usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND d.task_seconds>0`);
124
+ const [rows] = await pool.execute(`SELECT u.id,i.normalized_value AS email,
125
+ d.task_seconds AS today_task_seconds,
126
+ COALESCE(a.message_count,0) AS message_count,
127
+ COALESCE(a.turn_count,0) AS turn_count,
128
+ COALESCE(GREATEST(s.last_used_at,a.last_used_at),s.last_used_at,a.last_used_at) AS last_used_at
129
+ FROM relay_usage_user_days d JOIN users u ON u.id=d.user_id
130
+ JOIN user_login_identities i ON i.user_id=u.id AND i.kind='email'
131
+ LEFT JOIN (SELECT user_id,SUM(kind='message') AS message_count,
132
+ SUM(kind='turn') AS turn_count,MAX(occurred_at) AS last_used_at FROM relay_usage_actions
133
+ WHERE occurred_at >= DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) - INTERVAL 8 HOUR
134
+ AND occurred_at < DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) + INTERVAL 16 HOUR
135
+ GROUP BY user_id) a ON a.user_id=u.id
136
+ LEFT JOIN (SELECT user_id,MAX(confirmed_until) AS last_used_at
137
+ FROM relay_usage_sessions GROUP BY user_id) s ON s.user_id=u.id
138
+ WHERE d.usage_date=DATE(UTC_TIMESTAMP() + INTERVAL 8 HOUR) AND d.task_seconds>0
139
+ ORDER BY d.task_seconds DESC,u.id LIMIT ? OFFSET ?`, [30, offset]);
140
+ return { page, pageSize: 30, total: counts[0].total, rows };
141
+ }
@@ -299,8 +299,9 @@ async function handleRequest(request, response) {
299
299
  return;
300
300
  }
301
301
 
302
- if (request.method === 'GET' && url.pathname === '/api/turn-events') {
303
- response.startEvents();
302
+ if (request.method === 'GET' && url.pathname === '/api/turn-events') {
303
+ const execution = sharedServer;
304
+ response.startEvents();
304
305
  const listener = ({ method, params }) => {
305
306
  if (!['turn/started', 'turn/completed'].includes(method)) return;
306
307
  const threadId = params?.threadId, turnId = params?.turn?.id;
@@ -309,11 +310,11 @@ async function handleRequest(request, response) {
309
310
  }
310
311
  };
311
312
  const disconnected = () => response.end();
312
- sharedServer.on('notification', listener);
313
- sharedServer.on('disconnected', disconnected);
314
- response.once('close', () => {
315
- sharedServer.off('notification', listener);
316
- sharedServer.off('disconnected', disconnected);
313
+ execution.on('notification', listener);
314
+ execution.on('disconnected', disconnected);
315
+ response.once('close', () => {
316
+ execution.off('notification', listener);
317
+ execution.off('disconnected', disconnected);
317
318
  });
318
319
  return;
319
320
  }
@@ -375,12 +376,13 @@ async function handleRequest(request, response) {
375
376
  }
376
377
 
377
378
  const timelineMatch = /^\/api\/threads\/([^/]+)\/timeline$/.exec(url.pathname);
378
- if (request.method === 'GET' && timelineMatch) {
379
- const threadId = decodeURIComponent(timelineMatch[1]);
380
- const timeline = normalizeSharedTimeline(await sharedServer.timeline(threadId, sharedHistoryPageOptions()));
381
- if (request.socketRequest) {
382
- response.on('progress', () => sharedServer.keepSnapshotAlive(threadId, timeline.sync));
383
- response.once('close', () => sharedServer.keepSnapshotAlive(threadId, timeline.sync));
379
+ if (request.method === 'GET' && timelineMatch) {
380
+ const threadId = decodeURIComponent(timelineMatch[1]);
381
+ const execution = sharedServer;
382
+ const timeline = normalizeSharedTimeline(await execution.timeline(threadId, sharedHistoryPageOptions()));
383
+ if (request.socketRequest) {
384
+ response.on('progress', () => execution.keepSnapshotAlive(threadId, timeline.sync));
385
+ response.once('close', () => execution.keepSnapshotAlive(threadId, timeline.sync));
384
386
  }
385
387
  sendJson(response, 200, timeline);
386
388
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@walkhi/code-relax",
3
- "version": "0.1.0-beta.23",
3
+ "version": "0.1.0-beta.25",
4
4
  "license": "UNLICENSED",
5
5
  "type": "module",
6
6
  "scripts": {